diff --git a/.gitignore b/.gitignore
index f5ac8de..ccae8fc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
padlock-cloud
+db
diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json
deleted file mode 100644
index 2d02add..0000000
--- a/Godeps/Godeps.json
+++ /dev/null
@@ -1,136 +0,0 @@
-{
- "ImportPath": "github.com/maklesoft/padlock-cloud",
- "GoVersion": "go1.6",
- "GodepVersion": "v60",
- "Deps": [
- {
- "ImportPath": "github.com/Sirupsen/logrus",
- "Comment": "v0.10.0-28-ga283a10",
- "Rev": "a283a10442df8dc09befd873fab202bf8a253d6a"
- },
- {
- "ImportPath": "github.com/alecthomas/template",
- "Rev": "a0175ee3bccc567396460bf5acd36800cb10c49c"
- },
- {
- "ImportPath": "github.com/alecthomas/template/parse",
- "Rev": "a0175ee3bccc567396460bf5acd36800cb10c49c"
- },
- {
- "ImportPath": "github.com/alecthomas/units",
- "Rev": "2efee857e7cfd4f3d0138cc3cbb1b4966962b93a"
- },
- {
- "ImportPath": "github.com/golang/snappy",
- "Rev": "723cc1e459b8eea2dea4583200fd60757d40097a"
- },
- {
- "ImportPath": "github.com/gravitational/configure",
- "Rev": "b4d67e3fd8c998457775c53e36e36e83ffc98dc1"
- },
- {
- "ImportPath": "github.com/gravitational/configure/cstrings",
- "Rev": "b4d67e3fd8c998457775c53e36e36e83ffc98dc1"
- },
- {
- "ImportPath": "github.com/gravitational/trace",
- "Rev": "3a57d2a585a6d721265df44bae173af5ff71628e"
- },
- {
- "ImportPath": "github.com/hashicorp/golang-lru",
- "Rev": "a0d98a5f288019575c6d1f4bb1573fef2d1fcdc4"
- },
- {
- "ImportPath": "github.com/hashicorp/golang-lru/simplelru",
- "Rev": "a0d98a5f288019575c6d1f4bb1573fef2d1fcdc4"
- },
- {
- "ImportPath": "github.com/jonboulle/clockwork",
- "Comment": "v0.1.0-2-ge3653ac",
- "Rev": "e3653ace2d63753697e0e5b07b9393971c0bba9d"
- },
- {
- "ImportPath": "github.com/rs/cors",
- "Rev": "ceb1fbf238d7711a11a86a2622d0b85305348aeb"
- },
- {
- "ImportPath": "github.com/rs/xhandler",
- "Rev": "d9d9599b6aaf6a058cb7b1f48291ded2cbd13390"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/cache",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/comparer",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/errors",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/filter",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/iterator",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/journal",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/memdb",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/opt",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/storage",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/table",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb/util",
- "Rev": "1a9d62f03ea92815b46fcaab357cfd4df264b1a0"
- },
- {
- "ImportPath": "golang.org/x/net/context",
- "Rev": "0cb26f788dd4625d1956c6fd97ffc4c90669d129"
- },
- {
- "ImportPath": "golang.org/x/sys/unix",
- "Rev": "a646d33e2ee3172a661fc09bca23bb4889a41bc8"
- },
- {
- "ImportPath": "gopkg.in/alecthomas/kingpin.v2",
- "Comment": "v2.2.2",
- "Rev": "e5900212cbf65b181d3d8e08308ef06a01d117cf"
- },
- {
- "ImportPath": "gopkg.in/throttled/throttled.v2",
- "Comment": "v2.0.3",
- "Rev": "b5675e93f9d999b22f92d859a5bf2138d3641af4"
- },
- {
- "ImportPath": "gopkg.in/throttled/throttled.v2/store/memstore",
- "Comment": "v2.0.3",
- "Rev": "b5675e93f9d999b22f92d859a5bf2138d3641af4"
- },
- {
- "ImportPath": "gopkg.in/yaml.v2",
- "Rev": "e4d366fc3c7938e2958e662b4258c7a89e1f0e3e"
- }
- ]
-}
diff --git a/Godeps/Readme b/Godeps/Readme
deleted file mode 100644
index 4cdaa53..0000000
--- a/Godeps/Readme
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory tree is generated automatically by godep.
-
-Please do not edit.
-
-See https://github.com/tools/godep for more information.
diff --git a/README.md b/README.md
index a237b56..44f220d 100644
--- a/README.md
+++ b/README.md
@@ -62,7 +62,7 @@ server:
port: 5555
tls_cert: cert.crt
tls_key: cert.key
- host: cloud.padlock.io
+ base_url: https://cloud.padlock.io
leveldb:
path: path/to/db
email:
@@ -77,7 +77,7 @@ log:
```
**NOTE**: If you are using a config file, all other flags and environment
-variables will be ingored.
+variables will be ignored.
## Security Considerations
@@ -90,7 +90,7 @@ through plain http. You should make sure that in this case the server does
**not** listen on a public port and that any reverse proxies that handle
outgoing connections are protected via TLS.
-### Link spoofing and the --host option
+### Link spoofing and the --base-url option
Padlock Cloud frequently uses confirmation links for things like activating
authentication tokens, confirmation for deleting an account etc. They usually
@@ -103,24 +103,23 @@ https://hostname:port/activate/?v=1&t=cdB6iEdL4o5PfhLey30Rrg
These links are sent out to a users email address and serve as a form of
authentication. Only users that actually have control over the email account
-accociated with their Padlock Cloud account may access the correponding data.
+associated with their Padlock Cloud account may access the corresponding data.
-Now the `hostname` and `port` portion of the url will obviously differ based on
+Now the `hostname` and `port` portion of the URL will obviously differ based on
the environment. By default, the app will simply use the value provided by the
`Host` header of the incoming request. But the `Host` header can easily be
faked and unless the server is running behind a reverse proxy that sets the it
-to the correct value, this opens the app up to a vulnerabilty we call 'link
-spoofing'. Let's say an attacker sends an authentiation request to our server
+to the correct value, this opens the app up to a vulnerability we call 'link
+spoofing'. Let's say an attacker sends an authentication request to our server
using a targets email address, but changes the `Host` header to a server that
he controls. The email that is sent to the target will now contain a link that
points to the attackers server instead of our own and once the user clicks the
link the attacker is in possession of the activation token which can in turn be
used to activate the authentication token he already has. There is a simple
-solution for this: Explicitly provide a hostname and port to be used for link
-generation when starting up the server. The `runserver` command provides the
-`--host` flag for this. This is a string that contains the hostname and
-optionally a port, e.g. `example.com:3000` or simply `example.com`. it is
-recommended to use this option in production environments at all times!
+solution for this: Explicitly provide a base URL to be used for constructing
+links when starting up the server. The `runserver` command provides the
+`--base-url` flag for this. It is recommended to use this option in production
+environments at all times!
## Troubleshooting
diff --git a/assets/static/css/base.css b/assets/static/css/base.css
new file mode 100644
index 0000000..f305028
--- /dev/null
+++ b/assets/static/css/base.css
@@ -0,0 +1,184 @@
+body {
+ padding: 0;
+ margin: 0;
+ font-family: "Clear Sans", "Helvetica Neue", Helvetica, sans-serif;
+ font-size: 18px;
+ color: #333;
+ font-weight: 300;
+ -webkit-tap-highlight-color: transparent;
+}
+
+body, input, button {
+ -webkit-font-smoothing: antialiased;
+}
+
+input:not([type="checkbox"]), button {
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ border-radius: 0;
+ font-size: inherit;
+ font-family: inherit;
+ padding: 10px 15px;
+ background: #fff;
+ border: solid 1px #ccc;
+ min-width: 0;
+}
+
+input[type="checkbox"] {
+ vertical-align: middle;
+ cursor: pointer;
+}
+
+button {
+ border: none;
+ background: #59c6ff;
+ color: #fff;
+ cursor: pointer;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+button.light {
+ background: none;
+ color: #59c6ff;
+ padding: 0;
+ margin: 5px 0 0 2px;
+}
+
+*:focus {
+ outline: none;
+}
+
+h1 {
+ font-size: 250%;
+ font-weight: 100;
+ margin: 20px 0;
+}
+
+h2 {
+ font-size: 120%;
+ font-weight: 400;
+}
+
+h3 {
+ font-size: 110%;
+ font-weight: 400;
+}
+
+a {
+ color: #59c6ff;
+ text-decoration: none;
+ font-weight: 400;
+}
+
+button:hover, a:hover {
+ opacity: 0.7;
+}
+
+section {
+ padding: 0 40px;
+ margin: 40px 0;
+ clear: both;
+}
+
+footer {
+ display: block;
+ padding: 10px;
+ text-align: center;
+ font-size: 80%;
+ border-top: solid 1px #ccc;
+}
+
+footer .copyright {
+ color: #ccc;
+}
+
+footer a {
+ margin: 0 5px;
+}
+
+ul {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+
+th {
+ text-align: left;
+ vertical-align: top;
+ width: 150px;
+}
+
+svg.icon {
+ fill: currentColor;
+ stroke: currentColor;
+}
+
+header {
+ background: #ffffff;
+ position: fixed;
+ top: 0;
+ width: 100%;
+ z-index: 1;
+ padding: 0 10px;
+ box-sizing: border-box;
+ border-bottom: solid 1px #ccc;
+}
+
+header .inner {
+ height: 50px;
+ width: 100%;
+ margin: 0 auto;
+}
+
+header .inner, header .home, header nav, header nav ul {
+ display: flex;
+ align-items: center;
+}
+
+header nav ul li {
+ display: inline-block;
+ margin-left: 10px;
+}
+
+header .logo {
+ width: 35px;
+ height: 35px;
+ margin-right: 10px;
+ margin-left: 3px;
+}
+
+header .spacer {
+ flex: 1;
+}
+
+main {
+ margin: 80px auto;
+}
+
+header .inner, main {
+ max-width: 800px;
+}
+
+.account-email {
+ font-size: 90%;
+ font-weight: bold;
+}
+
+.note {
+ background: rgba(89, 198, 255, 0.1);
+ padding: 20px;
+ border: solid 1px #59c6ff;
+}
+
+@media (max-width: 500px) {
+ header .home .type {
+ display: none;
+ }
+
+ section {
+ padding-left: 20px;
+ padding-right: 20px;
+ }
+}
diff --git a/assets/static/css/dashboard.css b/assets/static/css/dashboard.css
new file mode 100644
index 0000000..12cfa41
--- /dev/null
+++ b/assets/static/css/dashboard.css
@@ -0,0 +1,27 @@
+ul.paired-devices li {
+ padding: 15px 20px;
+ border: solid 1px #eee;
+ margin: 10px 0;
+ font-size: 90%;
+}
+
+.expired {
+ opacity: 0.5;
+}
+
+.expired-label {
+ float: right;
+ color: red;
+}
+
+@media (max-width: 500px) {
+ .expired-label {
+ float: none;
+ margin: 0 3px;
+ }
+
+ tr {
+ display: flex;
+ flex-direction: column;
+ }
+}
diff --git a/assets/static/css/fonts.css b/assets/static/css/fonts.css
new file mode 100644
index 0000000..3e9768c
--- /dev/null
+++ b/assets/static/css/fonts.css
@@ -0,0 +1,24 @@
+@font-face {
+ font-family: 'Clear Sans';
+ font-style: normal;
+ font-weight: 100;
+ src: local('Clear Sans Thin'), local('ClearSans-Thin'), url(../fonts/ClearSans-Thin.woff) format('woff');
+}
+@font-face {
+ font-family: 'Clear Sans';
+ font-style: normal;
+ font-weight: 300;
+ src: local('Clear Sans Light'), local('ClearSans-Light'), url(../fonts/ClearSans-Light.woff) format('woff');
+}
+@font-face {
+ font-family: 'Clear Sans';
+ font-style: normal;
+ font-weight: 400;
+ src: local('Clear Sans Regular'), local('ClearSans-Regular'), url(../fonts/ClearSans-Regular.woff) format('woff');
+}
+@font-face {
+ font-family: 'Clear Sans';
+ font-style: normal;
+ font-weight: 700;
+ src: local('Clear Sans Bold'), local('ClearSans-Bold'), url(../fonts/ClearSans-Bold.woff) format('woff');
+}
diff --git a/assets/static/css/login.css b/assets/static/css/login.css
new file mode 100644
index 0000000..db98c48
--- /dev/null
+++ b/assets/static/css/login.css
@@ -0,0 +1,21 @@
+.login-form {
+ display: flex;
+ margin: 30px 0;
+}
+
+.login-form input[name="email"] {
+ display: block;
+ flex: 1;
+ margin-right: 5px;
+}
+
+@media (max-width: 500px) {
+ .login-form {
+ flex-direction: column;
+ }
+
+ .login-form input[name="email"] {
+ margin-right: 0;
+ margin-bottom: 5px;
+ }
+}
diff --git a/assets/static/fonts/ClearSans-Bold.woff b/assets/static/fonts/ClearSans-Bold.woff
new file mode 100755
index 0000000..bda6eb2
Binary files /dev/null and b/assets/static/fonts/ClearSans-Bold.woff differ
diff --git a/assets/static/fonts/ClearSans-Light.woff b/assets/static/fonts/ClearSans-Light.woff
new file mode 100755
index 0000000..bae448b
Binary files /dev/null and b/assets/static/fonts/ClearSans-Light.woff differ
diff --git a/assets/static/fonts/ClearSans-Regular.woff b/assets/static/fonts/ClearSans-Regular.woff
new file mode 100755
index 0000000..f4aacf7
Binary files /dev/null and b/assets/static/fonts/ClearSans-Regular.woff differ
diff --git a/assets/static/fonts/ClearSans-Thin.woff b/assets/static/fonts/ClearSans-Thin.woff
new file mode 100755
index 0000000..aa501c6
Binary files /dev/null and b/assets/static/fonts/ClearSans-Thin.woff differ
diff --git a/assets/static/img/favicon.png b/assets/static/img/favicon.png
new file mode 100644
index 0000000..fde13cd
Binary files /dev/null and b/assets/static/img/favicon.png differ
diff --git a/assets/static/img/padlock-cloud.svg b/assets/static/img/padlock-cloud.svg
new file mode 100644
index 0000000..3372832
--- /dev/null
+++ b/assets/static/img/padlock-cloud.svg
@@ -0,0 +1,4 @@
+
diff --git a/assets/templates/activate-auth-token-email.txt b/assets/templates/activate-auth-token-email.txt
deleted file mode 100644
index 7db0506..0000000
--- a/assets/templates/activate-auth-token-email.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-Hi there!
-
-You are receiving this email because you requested to pair a device with the Padlock Cloud account {{ .email }}. Please compare the connection ID below with the one displayed on your device. If the codes match, follow the activation link to complete the process!
-
-Connection ID: {{ .conn_id }}
-
-Activation link: {{ .activation_link }}
-
-WARNING: This device will gain access to your (encrypted) data! If the code displayed on your device does not match the one above, or if you did not send a connection request at all, DO NOT follow the link above!
-
-Best,
-The Padlock Team
diff --git a/assets/templates/activate-auth-token-success.html b/assets/templates/activate-auth-token-success.html
deleted file mode 100644
index 564b655..0000000
--- a/assets/templates/activate-auth-token-success.html
+++ /dev/null
@@ -1,43 +0,0 @@
-
-
-
- Padlock Cloud - Device Connected
-
-
-
-
-
- You have successfully connected your device with the account {{ .email }}!
- You can now use the app to synchronize with Padlock Cloud!
-
-
-
-
-
diff --git a/assets/templates/delete-store-email.txt b/assets/templates/delete-store-email.txt
deleted file mode 100644
index 6a4e0d8..0000000
--- a/assets/templates/delete-store-email.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Hi there!
-
-You are receiving this email because you requested to delete all data for the Padlock Cloud account {{ .email }}. To confirm the request, please visit the following link.
-
-WARNING: All your data will be deleted permanently and can not be restored afterwards!
-
-{{ .delete_link }}
-
-Best,
-The Padlock Team
diff --git a/assets/templates/delete-store-success.html b/assets/templates/delete-store-success.html
deleted file mode 100644
index 22300e5..0000000
--- a/assets/templates/delete-store-success.html
+++ /dev/null
@@ -1,42 +0,0 @@
-
-
-
- Padlock Cloud - Data Deleted
-
-
-
-
-
- All data for the account {{ .email }} has been deleted successfully!
-
-
-
-
-
\ No newline at end of file
diff --git a/assets/templates/email/activate-auth-token.txt b/assets/templates/email/activate-auth-token.txt
new file mode 100644
index 0000000..5993b45
--- /dev/null
+++ b/assets/templates/email/activate-auth-token.txt
@@ -0,0 +1,15 @@
+{{ define "main" -}}
+{{ if eq .token.Type "web" -}}
+You are receiving this email because you requested to log into your Padlock Cloud account {{ .token.Email }} through your browser. Just click the link below to log in!
+
+Click to log in: {{ .activation_link }}
+{{- else -}}
+You are receiving this email because you requested to pair a device with the Padlock Cloud account {{ .token.Email }}. Please compare the connection ID below with the one displayed on your device. If the codes match, follow the activation link to complete the process!
+
+Connection ID: {{ .token.Id }}
+
+Activation link: {{ .activation_link }}
+
+WARNING: This device will gain access to your (encrypted) data! If the code displayed on your device does not match the one above, or if you did not send a connection request at all, DO NOT follow the link above!
+{{- end }}
+{{- end }}
diff --git a/assets/templates/email/base.txt b/assets/templates/email/base.txt
new file mode 100644
index 0000000..d4f4153
--- /dev/null
+++ b/assets/templates/email/base.txt
@@ -0,0 +1,7 @@
+Hi there!
+
+{{ block "main" . }}
+{{ end }}
+
+Best,
+The Padlock Team
diff --git a/assets/templates/deprecated-version-email.txt b/assets/templates/email/deprecated-version.txt
similarity index 91%
rename from assets/templates/deprecated-version-email.txt
rename to assets/templates/email/deprecated-version.txt
index f94502f..c2069de 100644
--- a/assets/templates/deprecated-version-email.txt
+++ b/assets/templates/email/deprecated-version.txt
@@ -1,5 +1,4 @@
-Hi there!
-
+{{ define "main" -}}
Thanks for using Padlock!
You're receiving this email because you tried to use Padlock Cloud with an outdated version of the app. Please update to the newest version using one of the following links:
@@ -7,6 +6,4 @@ You're receiving this email because you tried to use Padlock Cloud with an outda
Android: https://play.google.com/store/apps/details?id=com.maklesoft.padlock
iOS: https://itunes.apple.com/app/id871710139
Google Chrome: https://chrome.google.com/webstore/detail/padlock/npkoefjfcjbknoeadfkbcdpbapaamcif
-
-Thanks,
-The Padlock Team
+{{- end }}
diff --git a/assets/templates/error-page.html b/assets/templates/error-page.html
deleted file mode 100644
index 12a6f40..0000000
--- a/assets/templates/error-page.html
+++ /dev/null
@@ -1,40 +0,0 @@
-
-
-
- Padlock Cloud
-
-
-
-
-
+ {{ end }}
+{{ end }}
+
+{{ define "dashboard-manage-account" }}
+
+
Manage Account
+ {{ if eq .action "resetdata" }}
+
+ Are you sure you want to delete all your data on Padlock Cloud?
+ This action can not be undone!
+ (Data stored locally on your devices will not be affected)
+
+
+ {{ else if .datareset }}
+
+ Your data has been reset successfully!
+
+ {{ else }}
+ Reset Data
+ {{ end }}
+
+{{ end }}
+
+{{ define "dashboard-manage-devices" }}
+
+
Paired Devices
+
+ {{ $csrfField := .csrfField }}
+ {{ with .account.AuthTokensByType "api" }}
+ {{ range . }}
+
+
+{{ end }}
diff --git a/assets/templates/page/login.html b/assets/templates/page/login.html
new file mode 100644
index 0000000..cd1011c
--- /dev/null
+++ b/assets/templates/page/login.html
@@ -0,0 +1,26 @@
+{{ define "css" }}
+
+{{ end }}
+{{ define "main" }}
+
+
Log In
+ {{ if .submitted }}
+
+ Wow, that was easy! We've sent and email to {{ .email }} with a magic login link.
+ Go ahead, check your inbox! (You can close this window now.)
+
+ {{ else }}
+
+ We know, even with a great password manager like Padlock passwords still suck. So we have
+ a much easier way for you to log in! Simply enter your email address and we'll send you a
+ magic login link!
+
+
+ {{ end }}
+
+{{ end }}
diff --git a/padlockcloud/auth.go b/padlockcloud/auth.go
index 79d6995..154e7a7 100644
--- a/padlockcloud/auth.go
+++ b/padlockcloud/auth.go
@@ -2,18 +2,105 @@ package padlockcloud
import "time"
import "encoding/json"
+import "encoding/base64"
+import "net/http"
+import "regexp"
+import "fmt"
+import "errors"
+
+var authStringPattern = regexp.MustCompile("^(?:AuthToken|ApiKey) (.+):(.+)$")
+var authMaxAge = func(authType string) time.Duration {
+ switch authType {
+ case "web":
+ return time.Hour
+ default:
+ return time.Duration(0)
+ }
+}
// A wrapper for an api key containing some meta info like the user and device name
type AuthToken struct {
- Email string
- Token string
- Id string
- Created time.Time
- LastUsed time.Time
+ Email string
+ Token string
+ Type string
+ Id string
+ Created time.Time
+ LastUsed time.Time
+ Expires time.Time
+ ClientVersion string
+ account *Account
+}
+
+// Returns the account associated with this auth token
+func (t *AuthToken) Account() *Account {
+ return t.account
+}
+
+// Validates the auth token against account `a`, i.e. looks for the corresponding
+// token in the accounts `AuthTokens` slice. If found, the token is considered valid
+// and it's value is updated with the value of the corresponding auth token in `a.AuthTokens`
+// and the `account` field is set to `a`
+func (t *AuthToken) Validate(a *Account) bool {
+ if _, at := a.findAuthToken(t); at != nil && at.Token == t.Token {
+ *t = *at
+ t.account = a
+ return true
+ }
+
+ return false
+}
+
+// Returns a string representation of the auth token in the form "AuthToken base64(t.Email):t.Token"
+func (t *AuthToken) String() string {
+ return fmt.Sprintf(
+ "AuthToken %s:%s",
+ base64.RawURLEncoding.EncodeToString([]byte(t.Email)),
+ t.Token,
+ )
+}
+
+// Returns true if `t` is expires, false otherwise
+func (t *AuthToken) Expired() bool {
+ return !t.Expires.IsZero() && t.Expires.Before(time.Now())
+}
+
+// Creates an auth token from it's string representation of the form "AuthToken base64(t.Email):t.Token"
+func AuthTokenFromString(str string) (*AuthToken, error) {
+ // Check if the Authorization header exists and is well formed
+ if !authStringPattern.MatchString(str) {
+ return nil, errors.New("invalid credentials")
+ }
+
+ // Extract email and auth token from Authorization header
+ matches := authStringPattern.FindStringSubmatch(str)
+ email := matches[1]
+ // Try to decode email in case it's in base64
+ if dec, err := base64.RawURLEncoding.DecodeString(matches[1]); err == nil {
+ email = string(dec)
+ }
+ t := &AuthToken{
+ Email: email,
+ Token: matches[2],
+ }
+ return t, nil
+}
+
+// Creates an auth token from a given request by parsing the `Authorization` header
+// and `auth` cookie
+func AuthTokenFromRequest(r *http.Request) (*AuthToken, error) {
+ authString := r.Header.Get("Authorization")
+
+ if authString == "" {
+ if cookie, err := r.Cookie("auth"); err == nil {
+ authString = cookie.Value
+ }
+ }
+
+ return AuthTokenFromString(authString)
}
// Creates a new auth token for a given `email`
-func NewAuthToken(email string) (*AuthToken, error) {
+func NewAuthToken(email string, t string) (*AuthToken, error) {
authT, err := token()
if err != nil {
return nil, err
@@ -23,12 +110,24 @@ func NewAuthToken(email string) (*AuthToken, error) {
return nil, err
}
+ if t == "" {
+ t = "api"
+ }
+
+ var expires time.Time
+
+ if maxAge := authMaxAge(t); maxAge != 0 {
+ expires = time.Now().Add(maxAge)
+ }
+
return &AuthToken{
- email,
- authT,
- id,
- time.Now(),
- time.Now(),
+ Email: email,
+ Token: authT,
+ Type: t,
+ Id: id,
+ Created: time.Now(),
+ LastUsed: time.Now(),
+ Expires: expires,
}, nil
}
@@ -37,6 +136,8 @@ type Account struct {
// The email servers as a unique identifier and as a means for
// requesting/activating api keys
Email string
+ // Time the account was created
+ Created time.Time
// A set of api keys that can be used to access the data associated with this
// account
AuthTokens []*AuthToken
@@ -54,6 +155,10 @@ func (acc *Account) Deserialize(data []byte) error {
// Implementation of the `Storable.Serialize` method
func (acc *Account) Serialize() ([]byte, error) {
+ if acc.Created.IsZero() {
+ acc.Created = time.Now()
+ }
+ acc.RemoveOldAuthTokens()
return json.Marshal(acc)
}
@@ -63,26 +168,77 @@ func (a *Account) AddAuthToken(token *AuthToken) {
a.AuthTokens = append(a.AuthTokens, token)
}
-// Checks if a given api key is valid for this account
-func (a *Account) ValidateAuthToken(token string) bool {
- // Check if the account contains any AuthToken with that matches
- // the given key
- for _, authToken := range a.AuthTokens {
- if authToken.Token == token {
- authToken.LastUsed = time.Now()
- return true
+// Returns the matching AuthToken instance by comparing Token field, Id or both
+// If either Id or Token field is empty, only the other one will compared. If
+// both are empty, nil is returned
+func (a *Account) findAuthToken(at *AuthToken) (int, *AuthToken) {
+ if at.Token == "" && at.Id == "" {
+ return -1, nil
+ }
+ for i, t := range a.AuthTokens {
+ if t != nil &&
+ (at.Token == "" || t.Token == at.Token) &&
+ (at.Id == "" || t.Id == at.Id) {
+ return i, t
+ fmt.Println(at, i, t)
}
}
+ return -1, nil
+}
- return false
+// Updates the correspoding auth token in the accounts `AuthTokens` slice with the
+// value of `t`
+func (a *Account) UpdateAuthToken(t *AuthToken) {
+ if _, at := a.findAuthToken(t); at != nil {
+ *at = *t
+ }
+}
+
+// Removes the corresponding auth token from the accounts `AuthTokens` slice
+func (a *Account) RemoveAuthToken(t *AuthToken) {
+ if i, _ := a.findAuthToken(t); i != -1 {
+ s := a.AuthTokens
+ s[i] = s[len(s)-1]
+ s[len(s)-1] = nil
+ a.AuthTokens = s[:len(s)-1]
+ }
+}
+
+// Filters out auth tokens that have been expired for 7 days or more
+func (a *Account) RemoveOldAuthTokens() {
+ s := a.AuthTokens[:0]
+
+ for _, t := range a.AuthTokens {
+ var maxAge time.Duration = 0
+ // Keep expired api tokens around for a while longer
+ if t.Type == "api" {
+ maxAge = 7 * 24 * time.Hour
+ }
+ if t.Expires.IsZero() || t.Expires.After(time.Now().Add(-maxAge)) {
+ s = append(s, t)
+ }
+ }
+
+ a.AuthTokens = s
+}
+
+func (a *Account) AuthTokensByType(typ string) []*AuthToken {
+ var tokens []*AuthToken
+ for _, t := range a.AuthTokens {
+ if t != nil && t.Type == typ {
+ tokens = append(tokens, t)
+ }
+ }
+ return tokens
}
// AuthRequest represents an api key - activation token pair used to activate a given api key
// `AuthRequest.Token` is used to activate the AuthToken through a separate channel (e.g. email)
type AuthRequest struct {
Token string
- AuthToken AuthToken
+ AuthToken *AuthToken
Created time.Time
+ Redirect string
}
// Implementation of the `Storable.Key` interface method
@@ -101,9 +257,9 @@ func (ar *AuthRequest) Serialize() ([]byte, error) {
}
// Creates a new `AuthRequest` with a given `email`
-func NewAuthRequest(email string) (*AuthRequest, error) {
+func NewAuthRequest(email string, tType string) (*AuthRequest, error) {
// Create new auth token
- authToken, err := NewAuthToken(email)
+ authToken, err := NewAuthToken(email, tType)
if err != nil {
return nil, err
}
@@ -114,7 +270,7 @@ func NewAuthRequest(email string) (*AuthRequest, error) {
return nil, err
}
- return &AuthRequest{actToken, *authToken, time.Now()}, nil
+ return &AuthRequest{actToken, authToken, time.Now(), ""}, nil
}
func init() {
diff --git a/padlockcloud/auth_test.go b/padlockcloud/auth_test.go
index 16b2803..f9a2235 100644
--- a/padlockcloud/auth_test.go
+++ b/padlockcloud/auth_test.go
@@ -1,27 +1,88 @@
package padlockcloud
import "testing"
+import "fmt"
+
+func TestAuthTokenFromString(t *testing.T) {
+ token, err := NewAuthToken("martin@padlock.io", "api")
+ str := token.String()
+ token2, err := AuthTokenFromString(str)
+ if err != nil || token.Email != token2.Email || token.Token != token2.Token {
+ t.Fatal("Token should be parsed correctly from string")
+ }
+
+ if token, err := AuthTokenFromString(""); token != nil || err == nil {
+ t.Fatal("Trying to get an auth token from an empty string should fail with an error")
+ }
+
+ if token, err := AuthTokenFromString(
+ fmt.Sprintf("AuthToken %s:%s", "martin@padlock.io", "asdf"),
+ ); err != nil || token.Email != "martin@padlock.io" {
+ t.Fatal("If email is not base64 encoded, authtoken is still parsed correctly")
+ }
+}
+
+func TestManageAuthTokens(t *testing.T) {
+ acc := &Account{}
+ t1, _ := NewAuthToken("martin@padlock.io", "api")
+
+ if acc.AddAuthToken(t1); len(acc.AuthTokens) != 1 || acc.AuthTokens[0] != t1 {
+ t.Fatal("Add auth token")
+ }
+
+ t2 := &AuthToken{Token: t1.Token}
+
+ if i, t3 := acc.findAuthToken(t2); i != 0 || t1 != t3 {
+ t.Fatal("Find auth token by token value")
+ }
+
+ t2.Token = ""
+ t2.Id = t1.Id
+ if i, t3 := acc.findAuthToken(t2); i != 0 || t1 != t3 {
+ t.Fatal("Find auth token by id")
+ }
+
+ t2.Id = "asdf"
+ if i, t3 := acc.findAuthToken(t2); i != -1 || t3 != nil {
+ t.Fatal("Fail to find invalid auth token")
+ }
+
+ t2.Id = t1.Id
+ t2.Email = "asdf"
+ if acc.UpdateAuthToken(t2); t1.Email != "asdf" {
+ t.Fatal("Update auth token")
+ }
+
+ if acc.RemoveAuthToken(t2); len(acc.AuthTokens) != 0 {
+ t.Fatal("Remove auth token")
+ }
+}
func TestValidateAuthToken(t *testing.T) {
acc := &Account{}
- token, err := NewAuthToken("")
- if err != nil {
- t.Fatal(err)
+ t1, _ := NewAuthToken("asdf", "api")
+ t2, _ := NewAuthToken("fsda", "api")
+ acc.AddAuthToken(t1)
+
+ if t2.Validate(acc) {
+ t.Fatal("Validate should fail")
}
- acc.AddAuthToken(token)
+ if t2.Id = t1.Id; t2.Validate(acc) {
+ t.Fatal("Validate should fail")
+ }
- lastUsed := token.LastUsed
+ t2.Token = t1.Token
- if valid := acc.ValidateAuthToken(token.Token); !valid {
- t.Fatal("Validating a valid auth token should return true")
+ if !t2.Validate(acc) {
+ t.Fatal("Validate should return true")
}
- if !token.LastUsed.After(lastUsed) {
- t.Fatal("LastUsed field should have been updated during validation")
+ if t2.Email != t1.Email {
+ t.Fatal("Validated token should take on value of original token")
}
- if valid := acc.ValidateAuthToken(""); valid {
- t.Fatal("Validating invalid auth token should return false")
+ if t2.account != acc {
+ t.Fatal("account field should be set after validation")
}
}
diff --git a/padlockcloud/cli.go b/padlockcloud/cli.go
index ad691d9..c5e7336 100644
--- a/padlockcloud/cli.go
+++ b/padlockcloud/cli.go
@@ -4,6 +4,7 @@ import "fmt"
import "path/filepath"
import "io/ioutil"
import "errors"
+import "encoding/base64"
import "gopkg.in/yaml.v2"
import "gopkg.in/urfave/cli.v1"
@@ -51,11 +52,14 @@ func (cliApp *CliApp) RunServer(context *cli.Context) error {
cfg, _ := yaml.Marshal(cliApp.Config)
cliApp.Server.Info.Printf("Running server with the following configuration:\n%s", cfg)
- if cliApp.Config.Server.Host == "" {
- fmt.Printf("\nWARNING: No --host option provided for generating urls. The 'Host' header from\n" +
- "incoming requests will be used instead. Note that the 'Host' header can easily be\n" +
- "spoofed! Unless you're running this server behind a reverse proxy you probably want\n" +
- "to provide an explicit host string! See the README for details.\n\n")
+ if cliApp.Config.Server.BaseUrl == "" {
+ fmt.Printf("\nWARNING: No --base-url option provided for constructing urls. The 'Host' header\n" +
+ "from incoming requests will be used instead which makes the server vulnerable to URL\n" +
+ "spoofing attacks! See the README for details.\n\n")
+ }
+
+ if err := cliApp.Server.Init(); err != nil {
+ return err
}
return cliApp.Server.Start()
@@ -67,21 +71,20 @@ func (cliApp *CliApp) ListAccounts(context *cli.Context) error {
}
defer cliApp.Storage.Close()
- var acc *Account
- accs, err := cliApp.Storage.List(acc)
+ acc := &Account{}
+ iter, err := cliApp.Storage.Iterator(acc)
if err != nil {
return err
}
+ defer iter.(*LevelDBIterator).Release()
- if len(accs) == 0 {
- fmt.Println("No existing accounts!")
- } else {
- output := ""
- for _, email := range accs {
- output = output + email + "\n"
- }
- fmt.Print(output)
+ output := ""
+ for iter.Next() {
+ iter.Get(acc)
+ output = output + acc.Email + "\n"
}
+ fmt.Print(output)
+
return nil
}
@@ -148,6 +151,23 @@ func (cliApp *CliApp) DeleteAccount(context *cli.Context) error {
return cliApp.Storage.Delete(acc)
}
+func genSecret() (string, error) {
+ b, err := randomBytes(32)
+ if err != nil {
+ return "", err
+ }
+ return base64.StdEncoding.EncodeToString(b), nil
+}
+
+func (cliApp *CliApp) GenSecret(context *cli.Context) error {
+ s, err := genSecret()
+ if err != nil {
+ return err
+ }
+ fmt.Println(s)
+ return nil
+}
+
func NewCliApp() *CliApp {
storage := &LevelDBStorage{}
email := &EmailSender{}
@@ -274,12 +294,17 @@ func NewCliApp() *CliApp {
Destination: &config.Server.TLSKey,
},
cli.StringFlag{
- Name: "host",
- Usage: "Host string to used for generating urls. May include the port. " +
- "If not provided the requests 'Host' header is used.",
+ Name: "base-url",
+ Usage: "Base url for constructing urls",
Value: "",
- EnvVar: "PC_HOST",
- Destination: &config.Server.Host,
+ EnvVar: "PC_BASE_URL",
+ Destination: &config.Server.BaseUrl,
+ },
+ cli.BoolFlag{
+ Name: "cors",
+ Usage: "Enable Cross-Origin Resource Sharing",
+ EnvVar: "PC_CORS",
+ Destination: &config.Server.Cors,
},
},
Action: cliApp.RunServer,
@@ -310,6 +335,11 @@ func NewCliApp() *CliApp {
},
},
},
+ {
+ Name: "gensecret",
+ Usage: "Generate random 32 byte secret",
+ Action: cliApp.GenSecret,
+ },
}
cliApp.Before = func(context *cli.Context) error {
diff --git a/padlockcloud/cli_test.go b/padlockcloud/cli_test.go
index 9d37327..8487184 100644
--- a/padlockcloud/cli_test.go
+++ b/padlockcloud/cli_test.go
@@ -13,6 +13,7 @@ func NewSampleConfig(dir string) CliConfig {
logfile := filepath.Join(dir, "LOG.txt")
errfile := filepath.Join(dir, "ERR.txt")
dbpath := filepath.Join(dir, "db")
+ secret, _ := genSecret()
return CliConfig{
LogConfig{
@@ -25,7 +26,8 @@ func NewSampleConfig(dir string) CliConfig {
Port: 5555,
TLSCert: "",
TLSKey: "",
- Host: "myhostname.com",
+ BaseUrl: "http://example.com",
+ Secret: secret,
},
LevelDBConfig{
Path: dbpath,
@@ -40,6 +42,10 @@ func NewSampleConfig(dir string) CliConfig {
}
func TestCliFlags(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping test in short mode.")
+ }
+
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal(err)
@@ -75,6 +81,10 @@ func TestCliFlags(t *testing.T) {
}
func TestCliConfigFile(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping test in short mode.")
+ }
+
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal(err)
@@ -106,7 +116,7 @@ func TestCliConfigFile(t *testing.T) {
!reflect.DeepEqual(*app.Storage.Config, cfg.LevelDB) ||
!reflect.DeepEqual(*app.Server.Config, cfg.Server) ||
!reflect.DeepEqual(*app.Sender.(*EmailSender).Config, cfg.Email) {
- yamlData2, _ := yaml.Marshal(cfg)
+ yamlData2, _ := yaml.Marshal(app.Config)
t.Fatalf("Config file not loaded correctly. \n\nExpected: \n\n%s\n\n Got: \n\n%s\n", yamlData, yamlData2)
}
diff --git a/padlockcloud/cors.go b/padlockcloud/cors.go
index ccf20d9..4f53f16 100644
--- a/padlockcloud/cors.go
+++ b/padlockcloud/cors.go
@@ -7,6 +7,7 @@ func Cors(handler http.Handler) http.Handler {
return cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"HEAD", "GET", "POST", "PUT", "DELETE"},
- AllowedHeaders: []string{"Authorization", "Accept", "Content-Type", "Require-Subscription"},
+ AllowedHeaders: []string{"Authorization", "Accept", "Content-Type", "X-Client-Version"},
+ ExposedHeaders: []string{"X-Sub-Required", "X-Sub-Status", "X-Sub-Trial-End"},
}).Handler(handler)
}
diff --git a/padlockcloud/error.go b/padlockcloud/error.go
index fc91c01..4c54a06 100644
--- a/padlockcloud/error.go
+++ b/padlockcloud/error.go
@@ -15,6 +15,7 @@ type ErrorResponse interface {
}
type BadRequest struct {
+ Msg string
}
func (e *BadRequest) Code() string {
@@ -22,7 +23,7 @@ func (e *BadRequest) Code() string {
}
func (e *BadRequest) Error() string {
- return fmt.Sprintf("%s", e.Code())
+ return fmt.Sprintf("%s - %s", e.Code(), e.Msg)
}
func (e *BadRequest) Status() int {
@@ -30,48 +31,69 @@ func (e *BadRequest) Status() int {
}
func (e *BadRequest) Message() string {
- return http.StatusText(e.Status())
+ return fmt.Sprintf("%s: %s", http.StatusText(e.Status()), e.Msg)
}
-type InvalidToken struct {
+type InvalidAuthToken struct {
+ email string
token string
}
-func (e *InvalidToken) Code() string {
- return "invalid_token"
+func (e *InvalidAuthToken) Code() string {
+ return "invalid_auth_token"
}
-func (e *InvalidToken) Error() string {
- return fmt.Sprintf("%s - %s", e.Code(), e.token)
+func (e *InvalidAuthToken) Error() string {
+ return fmt.Sprintf("%s - %s:%s", e.Code(), e.email, e.token)
}
-func (e *InvalidToken) Status() int {
- return http.StatusBadRequest
+func (e *InvalidAuthToken) Status() int {
+ return http.StatusUnauthorized
}
-func (e *InvalidToken) Message() string {
- return "Invalid Token"
+func (e *InvalidAuthToken) Message() string {
+ return fmt.Sprintf("%s - %s", http.StatusText(e.Status()), "No valid authorization token provided")
}
-type Unauthorized struct {
+type ExpiredAuthToken struct {
email string
token string
}
-func (e *Unauthorized) Code() string {
- return "unauthorized"
+func (e *ExpiredAuthToken) Code() string {
+ return "expired_auth_token"
}
-func (e *Unauthorized) Error() string {
+func (e *ExpiredAuthToken) Error() string {
return fmt.Sprintf("%s - %s:%s", e.Code(), e.email, e.token)
}
-func (e *Unauthorized) Status() int {
+func (e *ExpiredAuthToken) Status() int {
return http.StatusUnauthorized
}
-func (e *Unauthorized) Message() string {
- return http.StatusText(e.Status())
+func (e *ExpiredAuthToken) Message() string {
+ return fmt.Sprintf("%s - %s", http.StatusText(e.Status()), "The provided authorization token has expired")
+}
+
+type InvalidCsrfToken struct {
+ reason error
+}
+
+func (e *InvalidCsrfToken) Code() string {
+ return "invalid_csrf_token"
+}
+
+func (e *InvalidCsrfToken) Error() string {
+ return fmt.Sprintf("%s - %s", e.Code(), e.reason)
+}
+
+func (e *InvalidCsrfToken) Status() int {
+ return http.StatusForbidden
+}
+
+func (e *InvalidCsrfToken) Message() string {
+ return fmt.Sprintf("%s - %s", http.StatusText(e.Status()), "Invalid CSRF Token")
}
type MethodNotAllowed struct {
@@ -135,7 +157,8 @@ func (e *AccountNotFound) Message() string {
}
type UnsupportedApiVersion struct {
- version int
+ found int
+ expected int
}
func (e *UnsupportedApiVersion) Code() string {
@@ -143,7 +166,7 @@ func (e *UnsupportedApiVersion) Code() string {
}
func (e *UnsupportedApiVersion) Error() string {
- return fmt.Sprintf("%s - %d", e.Code(), e.version)
+ return fmt.Sprintf("%s - %d!=%d", e.Code(), e.found, e.expected)
}
func (e *UnsupportedApiVersion) Status() int {
@@ -151,25 +174,25 @@ func (e *UnsupportedApiVersion) Status() int {
}
func (e *UnsupportedApiVersion) Message() string {
- return fmt.Sprintf("The api version you are using (%d) is not supported. Please use version %d", e.version, ApiVersion)
+ return fmt.Sprintf("The api version you are using (%d) is not supported. Please use version %d", e.found, e.expected)
}
-type TooManyRequests struct {
+type RateLimitExceeded struct {
}
-func (e *TooManyRequests) Code() string {
- return "too_many_requests"
+func (e *RateLimitExceeded) Code() string {
+ return "rate_limit_exceeded"
}
-func (e *TooManyRequests) Error() string {
+func (e *RateLimitExceeded) Error() string {
return fmt.Sprintf("%s", e.Code())
}
-func (e *TooManyRequests) Status() int {
+func (e *RateLimitExceeded) Status() int {
return http.StatusTooManyRequests
}
-func (e *TooManyRequests) Message() string {
+func (e *RateLimitExceeded) Message() string {
return http.StatusText(e.Status())
}
@@ -178,7 +201,7 @@ type ServerError struct {
}
func (e *ServerError) Error() string {
- return fmt.Sprintf("%s - %s", e.Code(), e.error.Error())
+ return fmt.Sprintf("%s - %v", e.Code(), e.error)
}
func (e *ServerError) Code() string {
diff --git a/padlockcloud/handler.go b/padlockcloud/handler.go
new file mode 100644
index 0000000..dce950b
--- /dev/null
+++ b/padlockcloud/handler.go
@@ -0,0 +1,527 @@
+package padlockcloud
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+type Handler interface {
+ Handle(http.ResponseWriter, *http.Request, *AuthToken) error
+}
+
+type VoidHandler struct {
+}
+
+func (h *VoidHandler) Handle(w http.ResponseWriter, r *http.Request, a *AuthToken) error {
+ return nil
+}
+
+type RequestAuthToken struct {
+ *Server
+}
+
+// Handler function for requesting an api key. Generates a key-token pair and stores them.
+// The token can later be used to activate the api key. An email is sent to the corresponding
+// email address with an activation url. Expects `email` and `device_name` parameters through either
+// multipart/form-data or application/x-www-urlencoded parameters
+func (h *RequestAuthToken) Handle(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ create := r.Method == "POST"
+ email := r.PostFormValue("email")
+ tType := r.PostFormValue("type")
+ redirect := r.PostFormValue("redirect")
+ if tType == "" {
+ tType = "api"
+ }
+
+ // Make sure email field is set
+ if email == "" {
+ return &BadRequest{"no email provided"}
+ }
+
+ if tType != "api" && tType != "web" {
+ return &BadRequest{"unsupported auth token type"}
+ }
+
+ if redirect != "" {
+ if url, err := url.Parse(redirect); err != nil || h.Endpoints[url.Path] == nil {
+ return &BadRequest{"invalid redirect path"}
+ }
+ }
+
+ // If the client does not explicitly state that the server should create a new account for this email
+ // address in case it does not exist, we have to check if an account exists first
+ if !create {
+ acc := &Account{Email: email}
+ if err := h.Storage.Get(acc); err != nil {
+ if err == ErrNotFound {
+ // See if there exists a data store for this account
+ if err := h.Storage.Get(&DataStore{Account: acc}); err != nil {
+ if err == ErrNotFound {
+ return &AccountNotFound{email}
+ } else {
+ return err
+ }
+ }
+ } else {
+ return err
+ }
+ }
+ }
+
+ authRequest, err := NewAuthRequest(email, tType)
+ if err != nil {
+ return err
+ }
+
+ authRequest.Redirect = redirect
+
+ // Save key-token pair to database for activating it later in a separate request
+ err = h.Storage.Put(authRequest)
+ if err != nil {
+ return err
+ }
+
+ var response []byte
+ var emailBody bytes.Buffer
+ var emailSubj string
+
+ switch tType {
+ case "api":
+ if response, err = json.Marshal(map[string]string{
+ "id": authRequest.AuthToken.Id,
+ "token": authRequest.AuthToken.Token,
+ "email": authRequest.AuthToken.Email,
+ }); err != nil {
+ return err
+ }
+ emailSubj = "Connect to Padlock Cloud"
+
+ w.Header().Set("Content-Type", "application/json")
+ case "web":
+ var buff bytes.Buffer
+ if err := h.Templates.LoginPage.Execute(&buff, map[string]interface{}{
+ "submitted": true,
+ "email": email,
+ }); err != nil {
+ return err
+ }
+
+ response = buff.Bytes()
+ emailSubj = "Log in to Padlock Cloud"
+
+ w.Header().Set("Content-Type", "text/html")
+ }
+
+ // Render activation email
+ if err := h.Templates.ActivateAuthTokenEmail.Execute(&emailBody, map[string]interface{}{
+ "activation_link": fmt.Sprintf("%s/activate/?t=%s", h.BaseUrl(r), authRequest.Token),
+ "token": authRequest.AuthToken,
+ }); err != nil {
+ return err
+ }
+
+ if !h.emailRateLimiter.RateLimit(getIp(r), email) {
+ // Send email with activation link
+ go func() {
+ if err := h.Sender.Send(email, emailSubj, emailBody.String()); err != nil {
+ h.LogError(&ServerError{err}, r)
+ }
+ }()
+ } else {
+ return &RateLimitExceeded{}
+ }
+
+ h.Info.Printf("%s - auth_token:request - %s:%s:%s\n", formatRequest(r), email, tType, authRequest.AuthToken.Id)
+
+ w.WriteHeader(http.StatusAccepted)
+ w.Write(response)
+
+ return nil
+}
+
+type ActivateAuthToken struct {
+ *Server
+}
+
+func (h *ActivateAuthToken) GetAuthRequest(r *http.Request) (*AuthRequest, error) {
+ token := r.URL.Query().Get("t")
+
+ if token == "" {
+ return nil, &BadRequest{"no activation token provided"}
+ }
+
+ // Let's check if an unactivate api key exists for this token. If not,
+ // the token is not valid
+ authRequest := &AuthRequest{Token: token}
+ if err := h.Storage.Get(authRequest); err != nil {
+ if err == ErrNotFound {
+ return nil, &BadRequest{"invalid activation token"}
+ } else {
+ return nil, err
+ }
+ }
+
+ return authRequest, nil
+}
+
+func (h *ActivateAuthToken) Activate(authRequest *AuthRequest) error {
+ at := authRequest.AuthToken
+
+ // Create account instance with the given email address.
+ acc := &Account{Email: at.Email}
+
+ // Fetch existing account data. It's fine if no existing data is found. In that case we'll create
+ // a new entry in the database
+ if err := h.Storage.Get(acc); err != nil && err != ErrNotFound {
+ return err
+ }
+
+ // Add the new key to the account
+ acc.AddAuthToken(at)
+
+ // Save the changes
+ if err := h.Storage.Put(acc); err != nil {
+ return err
+ }
+
+ // Delete the authentication request from the database
+ if err := h.Storage.Delete(authRequest); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (h *ActivateAuthToken) SetAuthCookie(w http.ResponseWriter, at *AuthToken) {
+ http.SetCookie(w, &http.Cookie{
+ Name: "auth",
+ Value: at.String(),
+ HttpOnly: true,
+ Path: "/",
+ Secure: h.Secure,
+ })
+}
+
+func (h *ActivateAuthToken) Success(w http.ResponseWriter, r *http.Request, authRequest *AuthRequest) error {
+ redirect := authRequest.Redirect
+ at := authRequest.AuthToken
+
+ if at.Type == "web" {
+ h.SetAuthCookie(w, at)
+ }
+
+ if redirect == "" {
+ redirect = "/dashboard/"
+ }
+
+ if at.Type == "api" {
+ // If auth type is "api" also log them in so they can be redirected to dashboard
+ login, err := NewAuthRequest(at.Email, "web")
+ if err != nil {
+ return err
+ }
+
+ if err := h.Activate(login); err != nil {
+ return err
+ }
+
+ h.SetAuthCookie(w, login.AuthToken)
+ redirect = redirect + fmt.Sprintf("?paired=%s", at.Id)
+ }
+
+ http.Redirect(w, r, redirect, http.StatusFound)
+
+ h.Info.Printf("%s - auth_token:activate - %s:%s:%s\n", formatRequest(r), at.Email, at.Type, at.Id)
+
+ return nil
+}
+
+// Hander function for activating a given api key
+func (h *ActivateAuthToken) Handle(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ authRequest, err := h.GetAuthRequest(r)
+ if err != nil {
+ return err
+ }
+
+ if err := h.Activate(authRequest); err != nil {
+ return err
+ }
+
+ return h.Success(w, r, authRequest)
+}
+
+type ReadStore struct {
+ *Server
+}
+
+// Handler function for retrieving the data associated with a given account
+func (h *ReadStore) Handle(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ acc := auth.Account()
+
+ // Retrieve data from database. If not database entry is found, the `Content` field simply stays empty.
+ // This is not considered an error. Instead we simply return an empty response body. Clients should
+ // know how to deal with this.
+ data := &DataStore{Account: acc}
+ if err := h.Storage.Get(data); err != nil && err != ErrNotFound {
+ return err
+ }
+
+ h.Info.Printf("%s - data_store:read - %s\n", formatRequest(r), acc.Email)
+
+ // Return raw data in response body
+ w.Write(data.Content)
+
+ return nil
+}
+
+type WriteStore struct {
+ *Server
+}
+
+// Handler function for updating the data associated with a given account. This does NOT implement a
+// diffing algorith of any kind since Padlock Cloud is completely ignorant of the data structures involved.
+// Instead, clients should retrieve existing data through the `ReadStore` endpoint first, perform any necessary
+// decryption/parsing, consolidate the data with any existing local data and then reupload the full,
+// encrypted data set
+func (h *WriteStore) Handle(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ acc := auth.Account()
+
+ // Read data from request body into `DataStore` instance
+ data := &DataStore{Account: acc}
+ content, err := ioutil.ReadAll(r.Body)
+ if err != nil {
+ return err
+ }
+ data.Content = content
+
+ // Update database entry
+ if err := h.Storage.Put(data); err != nil {
+ return err
+ }
+
+ h.Info.Printf("%s - data_store:write - %s\n", formatRequest(r), acc.Email)
+
+ // Return with NO CONTENT status code
+ w.WriteHeader(http.StatusNoContent)
+
+ return nil
+}
+
+type DeleteStore struct {
+ *Server
+}
+
+func (h *DeleteStore) Handle(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ acc := auth.Account()
+
+ if err := h.Storage.Delete(&DataStore{Account: acc}); err != nil {
+ return err
+ }
+
+ http.Redirect(w, r, "/dashboard/?datareset=1", http.StatusFound)
+ return nil
+}
+
+type RequestDeleteStore struct {
+ *Server
+}
+
+// Handler function for requesting a data reset for a given account
+func (h *RequestDeleteStore) Handle(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ acc := auth.Account()
+
+ // Create AuthRequest
+ authRequest, err := NewAuthRequest(acc.Email, "web")
+ if err != nil {
+ return err
+ }
+
+ // After logging in, redirect to delete store page
+ authRequest.Redirect = "/dashboard/?action=resetdata"
+
+ // Save authrequest
+ if err := h.Storage.Put(authRequest); err != nil {
+ return err
+ }
+
+ // Render confirmation email
+ var buff bytes.Buffer
+ if err := h.Templates.ActivateAuthTokenEmail.Execute(&buff, map[string]interface{}{
+ "token": authRequest.AuthToken,
+ "activation_link": fmt.Sprintf("%s/activate/?t=%s", h.BaseUrl(r), authRequest.Token),
+ }); err != nil {
+ return err
+ }
+
+ body := buff.String()
+
+ if !h.emailRateLimiter.RateLimit(getIp(r), acc.Email) {
+ // Send email with activation link
+ go func() {
+ if err := h.Sender.Send(acc.Email, "Padlock Cloud Delete Request", body); err != nil {
+ h.LogError(&ServerError{err}, r)
+ }
+ }()
+ } else {
+ return &RateLimitExceeded{}
+ }
+
+ h.Info.Printf("%s - data_store:request_delete - %s", formatRequest(r), acc.Email)
+
+ // Send ACCEPTED status code
+ w.WriteHeader(http.StatusAccepted)
+
+ return nil
+}
+
+type LoginPage struct {
+ *Server
+}
+
+func (h *LoginPage) Handle(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ var b bytes.Buffer
+ if err := h.Templates.LoginPage.Execute(&b, nil); err != nil {
+ return err
+ }
+
+ b.WriteTo(w)
+
+ return nil
+}
+
+type Dashboard struct {
+ *Server
+}
+
+func (h *Dashboard) Handle(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ acc := auth.Account()
+
+ var b bytes.Buffer
+ if err := h.Templates.Dashboard.Execute(&b, map[string]interface{}{
+ "account": acc,
+ "paired": r.URL.Query().Get("paired"),
+ "revoked": r.URL.Query().Get("revoked"),
+ "datareset": r.URL.Query().Get("datareset"),
+ "action": r.URL.Query().Get("action"),
+ CSRFTemplateTag: CSRFTemplateField(r),
+ }); err != nil {
+ return err
+ }
+
+ b.WriteTo(w)
+ return nil
+}
+
+type Logout struct {
+ *Server
+}
+
+func (h *Logout) Handle(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ acc := auth.Account()
+
+ acc.RemoveAuthToken(auth)
+ if err := h.Storage.Put(acc); err != nil {
+ return err
+ }
+ http.SetCookie(w, &http.Cookie{
+ Name: "auth",
+ Value: "",
+ MaxAge: -1,
+ Path: "/",
+ HttpOnly: true,
+ Secure: h.Secure,
+ })
+ http.Redirect(w, r, "/login/", http.StatusFound)
+ return nil
+}
+
+type Revoke struct {
+ *Server
+}
+
+func (h *Revoke) Handle(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ token := r.PostFormValue("token")
+ id := r.PostFormValue("id")
+ if token == "" && id == "" {
+ return &BadRequest{"No token or id provided"}
+ }
+
+ acc := auth.Account()
+
+ t := &AuthToken{Token: token, Id: id}
+ if _, t = acc.findAuthToken(t); t == nil {
+ return &BadRequest{"No such token"}
+ }
+
+ t.Expires = time.Now().Add(-time.Minute)
+
+ acc.UpdateAuthToken(t)
+
+ if err := h.Storage.Put(acc); err != nil {
+ return err
+ }
+
+ http.Redirect(w, r, fmt.Sprintf("/dashboard/?revoked=%s", t.Id), http.StatusFound)
+
+ return nil
+}
+
+type StaticHandler struct {
+ fh http.Handler
+}
+
+func (h *StaticHandler) Handle(w http.ResponseWriter, r *http.Request, a *AuthToken) error {
+ h.fh.ServeHTTP(w, r)
+ return nil
+}
+
+func NewStaticHandler(dir string, path string) *StaticHandler {
+ // Serve up static files
+ fh := http.StripPrefix(path, http.FileServer(http.Dir(dir)))
+ return &StaticHandler{fh}
+}
+
+type RootHandler struct {
+ *Server
+}
+
+func (h *RootHandler) Handle(w http.ResponseWriter, r *http.Request, a *AuthToken) error {
+ if r.URL.Path != "/" {
+ return &UnsupportedEndpoint{r.URL.Path}
+ }
+
+ http.Redirect(w, r, "/dashboard/", http.StatusFound)
+ return nil
+}
+
+type HandlerFunc func(http.ResponseWriter, *http.Request, *AuthToken) error
+
+func (f HandlerFunc) Handle(w http.ResponseWriter, r *http.Request, a *AuthToken) error {
+ return f(w, r, a)
+}
+
+type Endpoint struct {
+ Handlers map[string]Handler
+ Version int
+ AuthType string
+}
+
+func (endpoint *Endpoint) Handle(w http.ResponseWriter, r *http.Request, a *AuthToken) error {
+ if h := endpoint.Handlers[r.Method]; h != nil {
+ return h.Handle(w, r, a)
+ } else {
+ return errors.New("Unexpected method: " + r.Method)
+ }
+}
+
+func HttpHandler(h Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ h.Handle(w, r, nil)
+ })
+}
diff --git a/padlockcloud/middleware.go b/padlockcloud/middleware.go
new file mode 100644
index 0000000..4a6b726
--- /dev/null
+++ b/padlockcloud/middleware.go
@@ -0,0 +1,152 @@
+package padlockcloud
+
+import "net/http"
+import "errors"
+import "fmt"
+import "strings"
+import "github.com/gorilla/csrf"
+
+var CSRFTemplateTag = csrf.TemplateTag
+var CSRFTemplateField = csrf.TemplateField
+
+type MiddleWare interface {
+ Wrap(Handler) Handler
+}
+
+type CheckEndpointVersion struct {
+ *Server
+ Version int
+}
+
+func (m *CheckEndpointVersion) Wrap(h Handler) Handler {
+ return HandlerFunc(func(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ // Contains deprecated 'ApiKey email:token' authentication scheme
+ depAuth := strings.Contains(r.Header.Get("Authorization"), "ApiKey")
+
+ version := versionFromRequest(r)
+
+ if depAuth || m.Version != 0 && version != m.Version {
+ m.SendDeprecatedVersionEmail(r)
+ return &UnsupportedApiVersion{version, m.Version}
+ }
+
+ return h.Handle(w, r, auth)
+ })
+}
+
+type Authenticate struct {
+ *Server
+ Type string
+}
+
+func (m *Authenticate) Wrap(h Handler) Handler {
+ return HandlerFunc(func(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ // Get auth token from request
+ auth, err := m.Authenticate(r)
+
+ // Endpoint requires authentation but no auth token could be aquired
+ if m.Type != "" && err != nil {
+ // If this endpoint requires web authentication, simply redirect to login page
+ if m.Type == "web" {
+ http.Redirect(w, r, "/login/", http.StatusFound)
+ return nil
+ }
+
+ return err
+ }
+
+ // Make sure auth token has the right type
+ if m.Type != "" && auth.Type != m.Type {
+ return &InvalidAuthToken{auth.Email, auth.Token}
+ }
+
+ return h.Handle(w, r, auth)
+ })
+}
+
+type CSRF struct {
+ *Server
+}
+
+func (m *CSRF) Wrap(h Handler) Handler {
+ return HandlerFunc(func(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ if auth != nil && auth.Type == "web" {
+ // Wrap the handler function in a http.Handler; Capture error in `e` variable for
+ // later use. We need to do this because the csrf middleware only works with a http.Handler
+ var err error
+ var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ err = h.Handle(w, r, auth)
+ })
+
+ handler = csrf.Protect(
+ m.secret,
+ csrf.Path("/"),
+ csrf.Secure(m.Secure),
+ csrf.ErrorHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ m.HandleError(&InvalidCsrfToken{csrf.FailureReason(r)}, w, r)
+ })),
+ )(handler)
+
+ handler.ServeHTTP(w, r)
+
+ return err
+ } else {
+ return h.Handle(w, r, auth)
+ }
+ })
+}
+
+type HandleError struct {
+ *Server
+}
+
+func (m *HandleError) Wrap(h Handler) Handler {
+ return HandlerFunc(func(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ err := h.Handle(w, r, auth)
+
+ if err != nil {
+ m.HandleError(err, w, r)
+ }
+
+ return err
+ })
+}
+
+type CheckMethod struct {
+ Allowed map[string]Handler
+}
+
+func (m *CheckMethod) Wrap(h Handler) Handler {
+ return HandlerFunc(func(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ if m.Allowed[r.Method] == nil {
+ return &MethodNotAllowed{r.Method}
+ }
+
+ return h.Handle(w, r, auth)
+ })
+}
+
+type HandlePanic struct {
+}
+
+func (m *HandlePanic) Wrap(h Handler) Handler {
+ return HandlerFunc(func(w http.ResponseWriter, r *http.Request, a *AuthToken) error {
+ var err error
+
+ func() {
+ defer func() {
+ if e := recover(); e != nil {
+ var ok bool
+ err, ok = e.(error)
+ if !ok {
+ err = errors.New(fmt.Sprintf("%v", e))
+ }
+ }
+ }()
+
+ err = h.Handle(w, r, a)
+ }()
+
+ return err
+ })
+}
diff --git a/padlockcloud/ratelimit.go b/padlockcloud/ratelimit.go
index 02fbd8a..a2f2c01 100644
--- a/padlockcloud/ratelimit.go
+++ b/padlockcloud/ratelimit.go
@@ -55,3 +55,39 @@ func RateLimit(handler http.Handler, quotas map[Route]RateQuota, deniedHandler h
}
})
}
+
+type EmailRateLimiter struct {
+ ipRateLimiter throttled.RateLimiter
+ emailRateLimiter throttled.RateLimiter
+}
+
+func (erl *EmailRateLimiter) RateLimit(ip string, email string) bool {
+ if erl == nil {
+ return false
+ }
+ ipLimited, _, _ := erl.ipRateLimiter.RateLimit(ip, 1)
+ emailLimited, _, _ := erl.ipRateLimiter.RateLimit(email, 1)
+ return ipLimited || emailLimited
+}
+
+func NewEmailRateLimiter(ipQuota RateQuota, emailQuota RateQuota) (*EmailRateLimiter, error) {
+ store, err := memstore.New(65536)
+ if err != nil {
+ return nil, err
+ }
+
+ ipRateLimiter, err := throttled.NewGCRARateLimiter(store, throttled.RateQuota(ipQuota))
+ if err != nil {
+ return nil, err
+ }
+
+ emailRateLimiter, err := throttled.NewGCRARateLimiter(store, throttled.RateQuota(emailQuota))
+ if err != nil {
+ return nil, err
+ }
+
+ return &EmailRateLimiter{
+ ipRateLimiter,
+ emailRateLimiter,
+ }, nil
+}
diff --git a/padlockcloud/ratelimit_test.go b/padlockcloud/ratelimit_test.go
index 250b899..1b1f443 100644
--- a/padlockcloud/ratelimit_test.go
+++ b/padlockcloud/ratelimit_test.go
@@ -6,6 +6,10 @@ import "testing"
import "time"
func TestRateLimit(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping test in short mode.")
+ }
+
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
diff --git a/padlockcloud/server.go b/padlockcloud/server.go
index 9c940e9..0768c6d 100644
--- a/padlockcloud/server.go
+++ b/padlockcloud/server.go
@@ -1,44 +1,21 @@
package padlockcloud
-import "net"
import "net/http"
import "net/http/httputil"
-import "io/ioutil"
import "fmt"
-import "encoding/json"
+import "encoding/base64"
import "regexp"
-import "errors"
import "bytes"
+import "strings"
import "time"
import "strconv"
import "path/filepath"
-import "strings"
import "gopkg.in/tylerb/graceful.v1"
const (
ApiVersion = 1
)
-// Extracts a uuid-formated token from a given url
-func tokenFromRequest(r *http.Request) (string, error) {
- token := r.URL.Query().Get("t")
-
- if token == "" {
- return "", &InvalidToken{token}
- }
-
- return token, nil
-}
-
-// Returns the appropriate protocol based on whether a request was made via https or not
-func schemeFromRequest(r *http.Request) string {
- if r.TLS != nil {
- return "https"
- } else {
- return "http"
- }
-}
-
func versionFromRequest(r *http.Request) int {
var vString string
accept := r.Header.Get("Accept")
@@ -47,6 +24,10 @@ func versionFromRequest(r *http.Request) int {
if reg.MatchString(accept) {
vString = reg.FindStringSubmatch(accept)[1]
} else {
+ vString = r.PostFormValue("api_version")
+ }
+
+ if vString == "" {
vString = r.URL.Query().Get("v")
}
@@ -71,59 +52,6 @@ func formatRequestVerbose(r *http.Request) string {
return string(dump)
}
-func CheckVersion(r *http.Request) (bool, int) {
- version := versionFromRequest(r)
- return version == ApiVersion, version
-}
-
-func credentialsFromRequest(r *http.Request) (string, string) {
- // Extract email and authentication token from Authorization header
- re := regexp.MustCompile("^AuthToken (.+):(.+)$")
- authHeader := r.Header.Get("Authorization")
-
- // Check if the Authorization header exists and is well formed
- if !re.MatchString(authHeader) {
- return "", ""
- }
-
- // Extract email and auth token from Authorization header
- matches := re.FindStringSubmatch(authHeader)
- return matches[1], matches[2]
-}
-
-// Represents a request for reseting the data associated with a given account. `RequestReset.Token` is used
-// for validating the request through a separate channel (e.g. email)
-type DeleteStoreRequest struct {
- Token string
- Account string
- Created time.Time
-}
-
-// Implementation of the `Storable.Key` interface method
-func (rr *DeleteStoreRequest) Key() []byte {
- return []byte(rr.Token)
-}
-
-// Implementation of the `Storable.Deserialize` interface method
-func (rr *DeleteStoreRequest) Deserialize(data []byte) error {
- return json.Unmarshal(data, rr)
-}
-
-// Implementation of the `Storable.Serialize` interface method
-func (rr *DeleteStoreRequest) Serialize() ([]byte, error) {
- return json.Marshal(rr)
-}
-
-// Creates a new `DeleteStoreRequest` with a given `email`
-func NewDeleteStoreRequest(email string) (*DeleteStoreRequest, error) {
- // Generate a new delete token
- token, err := token()
- if err != nil {
- return nil, err
- }
- return &DeleteStoreRequest{token, email, time.Now()}, nil
-}
-
// DataStore represents the data associated to a given account
type DataStore struct {
Account *Account
@@ -156,8 +84,12 @@ type ServerConfig struct {
TLSCert string `yaml:"tls_cert"`
// Path to TLS key file
TLSKey string `yaml:"tls_key"`
- // Explicit host to use in place of http.Request::Host when generating urls and such
- Host string `yaml:"host"`
+ // Explicit base url to use in place of http.Request::Host when generating urls and such
+ BaseUrl string `yaml:"base_url"`
+ // Secret used for authenticating cookies
+ Secret string `yaml:"secret"`
+ // Enable Cross-Origin Resource Sharing
+ Cors bool `yaml:"cors"`
}
// The Server type holds all the contextual data and logic used for running a Padlock Cloud instances
@@ -165,61 +97,86 @@ type ServerConfig struct {
type Server struct {
*graceful.Server
*Log
- mux *http.ServeMux
- Listener net.Listener
- Storage Storage
- Sender Sender
- Templates *Templates
- Config *ServerConfig
-}
-
-func (server *Server) GetHost(r *http.Request) string {
- if server.Config.Host != "" {
- return server.Config.Host
+ Storage Storage
+ Sender Sender
+ Templates *Templates
+ Config *ServerConfig
+ Secure bool
+ Endpoints map[string]*Endpoint
+ secret []byte
+ emailRateLimiter *EmailRateLimiter
+ authRequestCleaner *StorageCleaner
+}
+
+func (server *Server) BaseUrl(r *http.Request) string {
+ if server.Config.BaseUrl != "" {
+ return strings.TrimSuffix(server.Config.BaseUrl, "/")
} else {
- return r.Host
+ var scheme string
+ if server.Secure {
+ scheme = "https"
+ } else {
+ scheme = "http"
+ }
+ return fmt.Sprintf("%s://%s", scheme, r.Host)
}
}
// Retreives Account object from a http.Request object by evaluating the Authorization header and
-// cross-checking it with api keys of existing accounts. Returns an `Unauthorized` error
+// cross-checking it with api keys of existing accounts. Returns an `InvalidAuthToken` error
// if no valid Authorization header is provided or if the provided email:api_key pair does not match
// any of the accounts in the database.
-func (server *Server) AccountFromRequest(r *http.Request) (*Account, error) {
- email, token := credentialsFromRequest(r)
- if email == "" || token == "" {
- return nil, &Unauthorized{email, token}
+func (server *Server) Authenticate(r *http.Request) (*AuthToken, error) {
+ authToken, err := AuthTokenFromRequest(r)
+ if err != nil {
+ return nil, &InvalidAuthToken{}
}
- acc := &Account{Email: email}
+
+ invalidErr := &InvalidAuthToken{authToken.Email, authToken.Token}
+
+ acc := &Account{Email: authToken.Email}
// Fetch account for the given email address
- err := server.Storage.Get(acc)
- if err != nil {
+ if err := server.Storage.Get(acc); err != nil {
if err == ErrNotFound {
- return nil, &Unauthorized{email, token}
+ return nil, invalidErr
} else {
return nil, err
}
}
- // Check if the provide api token is valid
- if !acc.ValidateAuthToken(token) {
- return nil, &Unauthorized{email, token}
+ // Find the fully populated auth token struct on account. If not found, the value will be nil
+ // and we know that the provided token is not valid
+ if !authToken.Validate(acc) {
+ return nil, invalidErr
}
+ // Check if the token is expired
+ if authToken.Expired() {
+ return nil, &ExpiredAuthToken{authToken.Email, authToken.Token}
+ }
+
+ // If everything checks out, update the `LastUsed` field with the current time
+ authToken.LastUsed = time.Now()
+ // Update client version
+ authToken.ClientVersion = r.Header.Get("X-Client-Version")
+
+ acc.UpdateAuthToken(authToken)
+
// Save account info to persist last used data for auth tokens
if err := server.Storage.Put(acc); err != nil {
return nil, err
}
- return acc, nil
+ return authToken, nil
}
-func (server *Server) PrintError(err error, r *http.Request) {
- if _, ok := err.(*ServerError); ok {
- server.Error.Printf("%s - %s\nRequest:\n%s\n", formatRequest(r), err, formatRequestVerbose(r))
- } else {
- server.Info.Printf("%s - %s", formatRequest(r), err)
+func (server *Server) LogError(err error, r *http.Request) {
+ switch e := err.(type) {
+ case *ServerError, *InvalidCsrfToken:
+ server.Error.Printf("%s - %v\nRequest:\n%s\n", formatRequest(r), e, formatRequestVerbose(r))
+ default:
+ server.Info.Printf("%s - %v", formatRequest(r), e)
}
}
@@ -232,7 +189,7 @@ func (server *Server) HandleError(e error, w http.ResponseWriter, r *http.Reques
err = &ServerError{e}
}
- server.PrintError(e, r)
+ server.LogError(err, r)
var response []byte
accept := r.Header.Get("Accept")
@@ -240,14 +197,13 @@ func (server *Server) HandleError(e error, w http.ResponseWriter, r *http.Reques
if accept == "application/json" || strings.HasPrefix(accept, "application/vnd.padlock") {
w.Header().Set("Content-Type", "application/json")
response = JsonifyErrorResponse(err)
- } else if accept == "text/html" {
+ } else if strings.Contains(accept, "text/html") {
w.Header().Set("Content-Type", "text/html")
- // Render success page
var buff bytes.Buffer
if err := server.Templates.ErrorPage.Execute(&buff, map[string]string{
"message": err.Message(),
}); err != nil {
- server.PrintError(&ServerError{err}, r)
+ server.LogError(&ServerError{err}, r)
} else {
response = buff.Bytes()
}
@@ -261,374 +217,145 @@ func (server *Server) HandleError(e error, w http.ResponseWriter, r *http.Reques
w.Write(response)
}
-// Handler function for requesting an api key. Generates a key-token pair and stores them.
-// The token can later be used to activate the api key. An email is sent to the corresponding
-// email address with an activation url. Expects `email` and `device_name` parameters through either
-// multipart/form-data or application/x-www-urlencoded parameters
-func (server *Server) RequestAuthToken(w http.ResponseWriter, r *http.Request, create bool) error {
- email := r.PostFormValue("email")
-
- // Make sure email field is set
- if email == "" {
- return &BadRequest{}
- }
-
- // If the client does not explicitly state that the server should create a new account for this email
- // address in case it does not exist, we have to check if an account exists first
- if !create {
- acc := &Account{Email: email}
- if err := server.Storage.Get(acc); err != nil {
- if err == ErrNotFound {
- // See if there exists a data store for this account
- if err := server.Storage.Get(&DataStore{Account: acc}); err != nil {
- if err == ErrNotFound {
- return &AccountNotFound{email}
- } else {
- return err
- }
- }
- } else {
- return err
- }
- }
- }
-
- authRequest, err := NewAuthRequest(email)
- if err != nil {
- return err
- }
+// Registers handlers mapped by method for a given path
+func (server *Server) WrapEndpoint(endpoint *Endpoint) Handler {
+ var h Handler = endpoint
- // Save key-token pair to database for activating it later in a separate request
- err = server.Storage.Put(authRequest)
- if err != nil {
- return err
+ // If auth type is "web", wrap handler in csrf middleware
+ if endpoint.AuthType != "" {
+ h = (&CSRF{server}).Wrap(h)
}
- // Render activation email
- var buff bytes.Buffer
- err = server.Templates.ActivateAuthTokenEmail.Execute(&buff, map[string]string{
- "email": authRequest.AuthToken.Email,
- "activation_link": fmt.Sprintf("%s://%s/activate/?v=%d&t=%s", schemeFromRequest(r),
- server.GetHost(r), ApiVersion, authRequest.Token),
- "conn_id": authRequest.AuthToken.Id,
- })
- if err != nil {
- return err
- }
- body := buff.String()
+ // Check for correct endpoint version
+ h = (&CheckEndpointVersion{server, endpoint.Version}).Wrap(h)
- // Send email with activation link
- go func() {
- if err := server.Sender.Send(email, "Connect to Padlock Cloud", body); err != nil {
- server.PrintError(&ServerError{err}, r)
- }
- }()
+ // Wrap handler in auth middleware
+ h = (&Authenticate{server, endpoint.AuthType}).Wrap(h)
- resp, err := json.Marshal(map[string]string{
- "id": authRequest.AuthToken.Id,
- "token": authRequest.AuthToken.Token,
- "email": authRequest.AuthToken.Email,
- })
- if err != nil {
- return err
- }
+ // Check if Method is supported
+ h = (&CheckMethod{endpoint.Handlers}).Wrap(h)
- // Return auth token
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusAccepted)
- w.Write(resp)
+ h = (&HandlePanic{}).Wrap(h)
- server.Info.Printf("%s - auth_token:request - %s:%s\n", formatRequest(r), email, authRequest.AuthToken.Id)
+ h = (&HandleError{server}).Wrap(h)
- return nil
+ return h
}
-// Hander function for activating a given api key
-func (server *Server) ActivateAuthToken(w http.ResponseWriter, r *http.Request) error {
- // Extract activation token from url
- token, err := tokenFromRequest(r)
- if err != nil {
- return err
- }
-
- // Let's check if an unactivate api key exists for this token. If not,
- // the token is not valid
- authRequest := &AuthRequest{Token: token}
- err = server.Storage.Get(authRequest)
- if err != nil {
- if err == ErrNotFound {
- return &InvalidToken{token}
- } else {
- return err
- }
- }
-
- // Create account instance with the given email address.
- acc := &Account{Email: authRequest.AuthToken.Email}
-
- // Fetch existing account data. It's fine if no existing data is found. In that case we'll create
- // a new entry in the database
- if err := server.Storage.Get(acc); err != nil && err != ErrNotFound {
- return err
- }
-
- // Add the new key to the account
- acc.AddAuthToken(&authRequest.AuthToken)
-
- // Save the changes
- if err := server.Storage.Put(acc); err != nil {
- return err
- }
-
- // Delete the authentication request from the database
- if err := server.Storage.Delete(authRequest); err != nil {
- return err
+// Registeres http handlers for various routes
+func (server *Server) InitEndpoints() {
+ if server.Endpoints == nil {
+ server.Endpoints = make(map[string]*Endpoint)
}
- // Render success page
- var buff bytes.Buffer
- err = server.Templates.ActivateAuthTokenSuccess.Execute(&buff, map[string]string{
- "email": authRequest.AuthToken.Email,
- })
- if err != nil {
- return err
+ // Endpoint for logging in / requesting api keys
+ server.Endpoints["/auth/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "PUT": &RequestAuthToken{server},
+ "POST": &RequestAuthToken{server},
+ },
+ Version: ApiVersion,
}
- buff.WriteTo(w)
-
- server.Info.Printf("%s - auth_token:activate - %s:%s\n", formatRequest(r), acc.Email, authRequest.AuthToken.Id)
-
- return nil
-}
-
-// Handler function for retrieving the data associated with a given account
-func (server *Server) ReadStore(w http.ResponseWriter, r *http.Request) error {
- // Fetch account based on provided credentials
- acc, err := server.AccountFromRequest(r)
- if err != nil {
- return err
+ // Endpoint for logging in / requesting api keys
+ server.Endpoints["/login/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "GET": &LoginPage{server},
+ "POST": &RequestAuthToken{server},
+ },
}
- // Retrieve data from database. If not database entry is found, the `Content` field simply stays empty.
- // This is not considered an error. Instead we simply return an empty response body. Clients should
- // know how to deal with this.
- data := &DataStore{Account: acc}
- if err := server.Storage.Get(data); err != nil && err != ErrNotFound {
- return err
+ // Endpoint for activating auth tokens
+ server.Endpoints["/activate/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "GET": &ActivateAuthToken{server},
+ },
}
- // Return raw data in response body
- w.Write(data.Content)
-
- server.Info.Printf("%s - data_store:read - %s\n", formatRequest(r), acc.Email)
-
- return nil
-}
-
-// Handler function for updating the data associated with a given account. This does NOT implement a
-// diffing algorith of any kind since Padlock Cloud is completely ignorant of the data structures involved.
-// Instead, clients should retrieve existing data through the `ReadStore` endpoint first, perform any necessary
-// decryption/parsing, consolidate the data with any existing local data and then reupload the full,
-// encrypted data set
-func (server *Server) WriteStore(w http.ResponseWriter, r *http.Request) error {
- // Fetch account based on provided credentials
- acc, err := server.AccountFromRequest(r)
- if err != nil {
- return err
+ // Endpoint for reading / writing and deleting a store
+ server.Endpoints["/store/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "GET": &ReadStore{server},
+ "HEAD": &ReadStore{server},
+ "PUT": &WriteStore{server},
+ "DELETE": &RequestDeleteStore{server},
+ },
+ Version: ApiVersion,
+ AuthType: "api",
}
- // Read data from request body into `DataStore` instance
- data := &DataStore{Account: acc}
- content, err := ioutil.ReadAll(r.Body)
- if err != nil {
- return err
+ server.Endpoints["/deletestore/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "POST": &DeleteStore{server},
+ },
+ AuthType: "web",
}
- data.Content = content
- // Update database entry
- if err := server.Storage.Put(data); err != nil {
- return err
+ // Dashboard for managing data, auth tokens etc.
+ server.Endpoints["/dashboard/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "GET": &Dashboard{server},
+ },
+ AuthType: "web",
}
- // Return with NO CONTENT status code
- w.WriteHeader(http.StatusNoContent)
-
- server.Info.Printf("%s - data_store:write - %s\n", formatRequest(r), acc.Email)
-
- return nil
-}
-
-// Handler function for requesting a data reset for a given account
-func (server *Server) RequestDeleteStore(w http.ResponseWriter, r *http.Request) error {
- // Fetch account based on provided credentials
- acc, err := server.AccountFromRequest(r)
- if err != nil {
- return err
+ // Endpoint for logging out
+ server.Endpoints["/logout/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "GET": &Logout{server},
+ },
+ AuthType: "web",
}
- // Create DeleteStoreRequest
- deleteRequest, err := NewDeleteStoreRequest(acc.Email)
- if err != nil {
- return err
+ // Endpoint for revoking auth tokens
+ server.Endpoints["/revoke/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "POST": &Revoke{server},
+ },
+ AuthType: "web",
}
- // Save token/email pair in database to we can verify it later
- if err := server.Storage.Put(deleteRequest); err != nil {
- return err
+ server.Endpoints["/static/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "GET": NewStaticHandler(
+ filepath.Join(server.Config.AssetsPath, "static"),
+ "/static/",
+ ),
+ },
}
- // Render confirmation email
- var buff bytes.Buffer
- err = server.Templates.DeleteStoreEmail.Execute(&buff, map[string]string{
- "email": acc.Email,
- "delete_link": fmt.Sprintf("%s://%s/deletestore/?v=%d&t=%s", schemeFromRequest(r),
- server.GetHost(r), ApiVersion, deleteRequest.Token),
- })
- if err != nil {
- return err
+ server.Endpoints["/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "GET": &RootHandler{server},
+ // Older clients might still be using this method. Add a void handler so
+ // the request gets past the allowed method check and the request can be handled
+ // as a UnsupportedApiVersion error
+ "PUT": &VoidHandler{},
+ },
}
- body := buff.String()
-
- // Send email with confirmation link
- go func() {
- if err := server.Sender.Send(acc.Email, "Padlock Cloud Delete Request", body); err != nil {
- server.PrintError(&ServerError{err}, r)
- }
- }()
-
- // Send ACCEPTED status code
- w.WriteHeader(http.StatusAccepted)
-
- server.Info.Printf("%s - data_store:request_delete - %s", formatRequest(r), acc.Email)
-
- return nil
}
+func (server *Server) InitHandler() {
+ mux := http.NewServeMux()
-// Handler function for updating the data associated with a given account
-func (server *Server) CompleteDeleteStore(w http.ResponseWriter, r *http.Request) error {
- // Extract confirmation token from url
- token, err := tokenFromRequest(r)
- if err != nil {
- return err
- }
-
- // Fetch reset request from database
- resetRequest := &DeleteStoreRequest{Token: token}
- if err := server.Storage.Get(resetRequest); err != nil {
- if err == ErrNotFound {
- return &InvalidToken{token}
- } else {
- return err
- }
- }
-
- // If the corresponding delete request was found in the database, we consider the data reset request
- // as verified so we can proceed with deleting the data for the corresponding account
- dataStore := &DataStore{Account: &Account{Email: resetRequest.Account}}
- if err := server.Storage.Delete(dataStore); err != nil {
- return err
+ for key, endpoint := range server.Endpoints {
+ mux.Handle(key, HttpHandler(server.WrapEndpoint(endpoint)))
}
- // Render success page
- var buff bytes.Buffer
- err = server.Templates.DeleteStoreSuccess.Execute(&buff, map[string]string{
- "email": string(resetRequest.Account),
- })
- if err != nil {
- return err
- }
-
- buff.WriteTo(w)
-
- // Delete the request token
- if err := server.Storage.Delete(resetRequest); err != nil {
- return err
+ if server.Config.Cors {
+ server.Handler = Cors(mux)
+ } else {
+ server.Handler = mux
}
-
- server.Info.Printf("%s - data_store:confirm_delete - %s", formatRequest(r), resetRequest.Account)
-
- return nil
-}
-
-// Registeres http handlers for various routes
-func (server *Server) SetupRoutes() {
- // Endpoint for requesting api keys, only POST method is supported
- server.mux.HandleFunc("/auth/", func(w http.ResponseWriter, r *http.Request) {
- var err error
- switch r.Method {
- case "PUT":
- err = server.RequestAuthToken(w, r, false)
- case "POST":
- err = server.RequestAuthToken(w, r, true)
- default:
- err = &MethodNotAllowed{r.Method}
- }
-
- if err != nil {
- server.HandleError(err, w, r)
- }
- })
-
- // Endpoint for requesting api keys, only POST method is supported
- server.mux.HandleFunc("/activate/", func(w http.ResponseWriter, r *http.Request) {
- var err error
-
- if r.Method == "GET" {
- err = server.ActivateAuthToken(w, r)
- } else {
- err = &MethodNotAllowed{r.Method}
- }
-
- if err != nil {
- server.HandleError(err, w, r)
- }
- })
-
- // Endpoint for reading, writing and deleting store data
- server.mux.HandleFunc("/store/", func(w http.ResponseWriter, r *http.Request) {
- var err error
-
- switch r.Method {
- case "GET", "HEAD":
- err = server.ReadStore(w, r)
- case "PUT":
- err = server.WriteStore(w, r)
- case "DELETE":
- err = server.RequestDeleteStore(w, r)
- default:
- err = &MethodNotAllowed{r.Method}
- }
-
- if err != nil {
- server.HandleError(err, w, r)
- }
- })
-
- // Endpoint for requesting a data reset. Only GET supported
- server.mux.HandleFunc("/deletestore/", func(w http.ResponseWriter, r *http.Request) {
- var err error
-
- if r.Method == "GET" {
- err = server.CompleteDeleteStore(w, r)
- } else {
- err = &MethodNotAllowed{r.Method}
- }
-
- if err != nil {
- server.HandleError(err, w, r)
- }
- })
-
- // Fall through route
- server.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- server.HandleError(&UnsupportedEndpoint{r.URL.Path}, w, r)
- })
}
func (server *Server) SendDeprecatedVersionEmail(r *http.Request) error {
+ var email string
+
// Try getting email from Authorization header first
- email, _ := credentialsFromRequest(r)
+ if authToken, err := AuthTokenFromRequest(r); err == nil {
+ email = authToken.Email
+ }
// Try to extract email from url if method is DELETE
if email == "" && r.Method == "DELETE" {
@@ -640,7 +367,7 @@ func (server *Server) SendDeprecatedVersionEmail(r *http.Request) error {
email = r.PostFormValue("email")
}
- if email != "" {
+ if email != "" && !server.emailRateLimiter.RateLimit(getIp(r), email) {
var buff bytes.Buffer
if err := server.Templates.DeprecatedVersionEmail.Execute(&buff, nil); err != nil {
return err
@@ -650,7 +377,7 @@ func (server *Server) SendDeprecatedVersionEmail(r *http.Request) error {
// Send email about deprecated api version
go func() {
if err := server.Sender.Send(email, "Please update your version of Padlock", body); err != nil {
- server.PrintError(&ServerError{err}, r)
+ server.LogError(&ServerError{err}, r)
}
}()
}
@@ -658,44 +385,29 @@ func (server *Server) SendDeprecatedVersionEmail(r *http.Request) error {
return nil
}
-func (server *Server) HandlePanic(w http.ResponseWriter, r *http.Request) {
- if e := recover(); e != nil {
- err, ok := e.(error)
- if !ok {
- err = errors.New(fmt.Sprintf("%v", e))
- }
- server.HandleError(err, w, r)
- }
-}
-
-// Implements `http.Handler.ServeHTTP` interface method. Handles panic recovery and TLS checking, Delegates
-// requests to embedded `http.ServeMux`
-func (server *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- defer server.HandlePanic(w, r)
+func (server *Server) Init() error {
+ var err error
- if ok, version := CheckVersion(r); !ok {
- if err := server.SendDeprecatedVersionEmail(r); err != nil {
- server.PrintError(&ServerError{err}, r)
+ if server.Config.Secret != "" {
+ if s, err := base64.StdEncoding.DecodeString(server.Config.Secret); err != nil {
+ server.secret = s
+ } else {
+ return err
+ }
+ } else {
+ if key, err := randomBytes(32); err != nil {
+ return err
+ } else {
+ server.secret = key
}
-
- server.HandleError(&UnsupportedApiVersion{version}, w, r)
- return
}
- // Delegate requests to embedded `http.ServeMux`
- server.mux.ServeHTTP(w, r)
-}
-
-// Initialize Server with dependencies and configuration
-func (server *Server) Init() error {
- var err error
-
- server.SetupRoutes()
+ server.InitEndpoints()
if server.Templates == nil {
+ server.Templates = &Templates{}
// Load templates from assets directory
- server.Templates, err = LoadTemplates(filepath.Join(server.Config.AssetsPath, "templates"))
- if err != nil {
+ if err := LoadTemplates(server.Templates, filepath.Join(server.Config.AssetsPath, "templates")); err != nil {
return err
}
}
@@ -705,32 +417,40 @@ func (server *Server) Init() error {
return err
}
+ if rl, err := NewEmailRateLimiter(
+ RateQuota{PerMin(1), 5},
+ RateQuota{PerMin(1), 5},
+ ); err != nil {
+ return err
+ } else {
+ server.emailRateLimiter = rl
+ }
+
+ // Clean out auth request older than 24hrs once a day
+ if cl, err := NewStorageCleaner(server.Storage, &AuthRequest{}, func(t Storable) bool {
+ return t.(*AuthRequest).Created.Before(time.Now().Add(-24 * time.Hour))
+ }); err != nil {
+ return err
+ } else {
+ server.authRequestCleaner = cl
+ cl.Log = server.Log
+ cl.Start(24 * time.Hour)
+ }
+
return nil
}
func (server *Server) CleanUp() error {
+ if server.authRequestCleaner != nil {
+ server.authRequestCleaner.Stop()
+ }
return server.Storage.Close()
}
func (server *Server) Start() error {
- if err := server.Init(); err != nil {
- return err
- }
defer server.CleanUp()
- // Add rate limiting middleWare
- handler := RateLimit(server, map[Route]RateQuota{
- Route{"POST", "/auth/"}: RateQuota{PerMin(1), 5},
- Route{"PUT", "/auth/"}: RateQuota{PerMin(1), 5},
- Route{"DELETE", "/store/"}: RateQuota{PerMin(1), 5},
- }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- server.HandleError(&TooManyRequests{}, w, r)
- }))
-
- // Add CORS middleware
- handler = Cors(handler)
-
- server.Handler = handler
+ server.InitHandler()
port := server.Config.Port
tlsCert := server.Config.TLSCert
@@ -741,6 +461,7 @@ func (server *Server) Start() error {
// Start server
if tlsCert != "" && tlsKey != "" {
server.Info.Printf("Starting server with TLS on port %v", port)
+ server.Secure = true
return server.ListenAndServeTLS(tlsCert, tlsKey)
} else {
server.Info.Printf("Starting server on port %v", port)
@@ -751,17 +472,14 @@ func (server *Server) Start() error {
// Instantiates and initializes a new Server and returns a reference to it
func NewServer(log *Log, storage Storage, sender Sender, config *ServerConfig) *Server {
server := &Server{
- &graceful.Server{
+ Server: &graceful.Server{
Server: &http.Server{},
Timeout: time.Second * 10,
},
- log,
- http.NewServeMux(),
- nil,
- storage,
- sender,
- nil,
- config,
+ Log: log,
+ Storage: storage,
+ Sender: sender,
+ Config: config,
}
// Hook up logger for http.Server
@@ -774,5 +492,4 @@ func NewServer(log *Log, storage Storage, sender Sender, config *ServerConfig) *
func init() {
RegisterStorable(&DataStore{}, "data-stores")
- RegisterStorable(&DeleteStoreRequest{}, "delete-requests")
}
diff --git a/padlockcloud/server_test.go b/padlockcloud/server_test.go
index ac1c063..6c6cff7 100644
--- a/padlockcloud/server_test.go
+++ b/padlockcloud/server_test.go
@@ -2,9 +2,9 @@ package padlockcloud
import "testing"
import "fmt"
-import "text/template"
-import htmlTemplate "html/template"
+import "html/template"
import "net/http"
+import "net/http/cookiejar"
import "net/http/httptest"
import "net/url"
import "log"
@@ -13,17 +13,70 @@ import "regexp"
import "bytes"
import "encoding/json"
import "errors"
+import "time"
+import "github.com/gorilla/csrf"
const (
testEmail = "martin@padlock.io"
testData = "Hello World!"
)
+func init() {
+ authMaxAge = func(authType string) time.Duration {
+ switch authType {
+ case "web":
+ return time.Millisecond * 10
+ default:
+ return time.Duration(0)
+ }
+ }
+}
+
+type serverTestContext struct {
+ server *Server
+ client *http.Client
+ storage *MemoryStorage
+ sender *RecordSender
+ host string
+ authToken *AuthToken
+ capturedAuthToken *AuthToken
+}
+
+func (ctx *serverTestContext) resetStorage() {
+ ctx.storage.Open()
+}
+
+func (ctx *serverTestContext) resetCookies() {
+ jar, _ := cookiejar.New(nil)
+ ctx.client.Jar = jar
+}
+
+func (ctx *serverTestContext) resetAll() {
+ ctx.resetCookies()
+ ctx.resetStorage()
+ ctx.sender.Reset()
+ ctx.authToken = nil
+ ctx.capturedAuthToken = nil
+}
+
+func (ctx *serverTestContext) followRedirects(follow bool) {
+ if follow {
+ ctx.client.CheckRedirect = nil
+ } else {
+ ctx.client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
+ return http.ErrUseLastResponse
+ }
+ }
+}
+
// Helper function for creating (optionally authenticated) requests
-func request(method string, url string, body string, asForm bool, authToken *AuthToken, version int) (*http.Response, error) {
- req, _ := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
+func (ctx *serverTestContext) request(method string, url string, body string, version int) (*http.Response, error) {
+ req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
+ if err != nil {
+ return nil, err
+ }
- if asForm {
+ if method == "POST" || method == "PUT" {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
@@ -33,10 +86,212 @@ func request(method string, url string, body string, asForm bool, authToken *Aut
req.Header.Add("Accept", "application/json")
}
- if authToken != nil {
- req.Header.Add("Authorization", fmt.Sprintf("AuthToken %s:%s", authToken.Email, authToken.Token))
+ if ctx.authToken != nil && ctx.authToken.Type == "api" {
+ req.Header.Add("Authorization", ctx.authToken.String())
+ }
+
+ return ctx.client.Do(req)
+}
+
+func (ctx *serverTestContext) loginApi(email string) (*http.Response, error) {
+ var res *http.Response
+ var err error
+
+ if res, err = ctx.request("POST", ctx.host+"/auth/", url.Values{
+ "email": {email},
+ "type": {"api"},
+ }.Encode(), ApiVersion); err != nil {
+ return nil, err
+ }
+
+ responseBody, err := validateResponse(res, http.StatusAccepted, "")
+ if err != nil {
+ return res, err
+ }
+
+ ctx.authToken = &AuthToken{}
+ // Response status code should be "ACCEPTED", response body should be the json-encoded auth token
+ if err := json.Unmarshal(responseBody, ctx.authToken); err != nil {
+ return res, fmt.Errorf("Failed to parse api key from response: %s", responseBody)
+ }
+
+ ctx.authToken.Type = "api"
+
+ link, err := ctx.extractActivationLink()
+ if err != nil {
+ return res, err
+ }
+
+ return ctx.request("GET", link, "", 0)
+}
+
+func (ctx *serverTestContext) loginWeb(email string, redirect string) (*http.Response, error) {
+ var res *http.Response
+ var err error
+
+ if res, err = ctx.request("POST", ctx.host+"/auth/", url.Values{
+ "email": {email},
+ "type": {"web"},
+ "redirect": {redirect},
+ }.Encode(), ApiVersion); err != nil {
+ return nil, err
+ }
+
+ if _, err := validateResponse(res, http.StatusAccepted, ""); err != nil {
+ return res, err
+ }
+
+ link, err := ctx.extractActivationLink()
+ if err != nil {
+ return res, err
+ }
+
+ // 'visit' activation link
+ if res, err = ctx.request("GET", link, "", 0); err != nil {
+ return res, err
+ }
+
+ u, _ := url.Parse(ctx.host)
+ var authCookie *http.Cookie
+ for _, c := range ctx.client.Jar.Cookies(u) {
+ if c.Name == "auth" {
+ authCookie = c
+ break
+ }
+ }
+
+ if authCookie == nil {
+ return res, errors.New("Expected cookie of name 'auth' to be set")
+ }
+
+ if ctx.authToken, err = AuthTokenFromString(authCookie.Value); err != nil {
+ return res, fmt.Errorf("Failed to parse auth token from cookie. Error: %v", err)
+ }
+
+ ctx.authToken.Type = "web"
+
+ return res, nil
+}
+
+func (ctx serverTestContext) getCsrfToken() string {
+ res, _ := ctx.request("GET", ctx.host+"/csrftest/", "", 0)
+ csrfToken, _ := validateResponse(res, http.StatusOK, "")
+ return string(csrfToken)
+}
+
+func (ctx *serverTestContext) extractActivationLink() (string, error) {
+ // Activation message should be sent to the correct email
+ if ctx.sender.Recipient != testEmail {
+ return "", fmt.Errorf("Expected activation message to be sent to %s, instead got %s", testEmail, ctx.sender.Recipient)
+ }
+
+ // Activation message should contain a valid activation link
+ linkPattern := fmt.Sprintf("%s/activate/\\?t=%s", ctx.host, tokenPattern)
+ msgPattern := fmt.Sprintf("%s, %s", testEmail, linkPattern)
+ match, _ := regexp.MatchString(msgPattern, ctx.sender.Message)
+ if !match {
+ return "", fmt.Errorf("Expected activation message to match \"%s\", got \"%s\"", msgPattern, ctx.sender.Message)
+ }
+ link := regexp.MustCompile(linkPattern).FindString(ctx.sender.Message)
+
+ return link, nil
+}
+
+func newServerTestContext() *serverTestContext {
+ var context *serverTestContext
+
+ var captureAuthToken = HandlerFunc(func(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ context.capturedAuthToken = auth
+ return nil
+ })
+
+ storage := &MemoryStorage{}
+ sender := &RecordSender{}
+ templates := &Templates{
+ template.New(""),
+ template.New(""),
+ template.Must(template.New("").Parse("{{ .token.Email }}, {{ .activation_link }}")),
+ template.Must(template.New("").Parse("")),
+ template.Must(template.New("").Parse("{{ .message }}")),
+ template.Must(template.New("").Parse("login,{{ .email }},{{ .submitted }}")),
+ template.Must(template.New("").Parse("dashboard")),
+ }
+
+ logger := &Log{Config: &LogConfig{}}
+ logger.Init()
+ logger.Info.SetOutput(ioutil.Discard)
+ logger.Error.SetOutput(ioutil.Discard)
+ server := NewServer(logger, storage, sender, &ServerConfig{})
+ server.Templates = templates
+ server.Init()
+
+ server.Endpoints["/csrftest/"] = &Endpoint{
+ AuthType: "web",
+ Handlers: map[string]Handler{
+ "GET": HandlerFunc(func(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ w.Write([]byte(csrf.Token(r)))
+ return nil
+ }),
+ "POST": HandlerFunc(func(w http.ResponseWriter, r *http.Request, auth *AuthToken) error {
+ return nil
+ }),
+ },
+ }
+
+ server.Endpoints["/authtestnoauth/"] = &Endpoint{
+ AuthType: "",
+ Handlers: map[string]Handler{
+ "GET": captureAuthToken,
+ },
+ }
+
+ server.Endpoints["/authtestapi/"] = &Endpoint{
+ AuthType: "api",
+ Handlers: map[string]Handler{
+ "GET": captureAuthToken,
+ },
+ }
+
+ server.Endpoints["/authtestweb/"] = &Endpoint{
+ AuthType: "web",
+ Handlers: map[string]Handler{
+ "GET": captureAuthToken,
+ },
+ }
+
+ server.Endpoints["/panic/"] = &Endpoint{
+ Handlers: map[string]Handler{
+ "GET": HandlerFunc(func(w http.ResponseWriter, r *http.Request, a *AuthToken) error {
+ panic("Everyone panic!!!")
+ }),
+ "POST": HandlerFunc(func(w http.ResponseWriter, r *http.Request, a *AuthToken) error {
+ panic(errors.New("Everyone panic!!!"))
+ }),
+ },
+ }
+
+ server.InitHandler()
+
+ server.emailRateLimiter = nil
+
+ testServer := httptest.NewServer(server.Handler)
+
+ host := testServer.URL
+
+ jar, _ := cookiejar.New(nil)
+ client := &http.Client{
+ Jar: jar,
+ }
+
+ context = &serverTestContext{
+ server: server,
+ client: client,
+ storage: storage,
+ sender: sender,
+ host: host,
}
- return http.DefaultClient.Do(req)
+
+ return context
}
// Helper function for checking a `http.Response` object for an expected status code and response body
@@ -45,17 +300,17 @@ func request(method string, url string, body string, asForm bool, authToken *Aut
// E.g.:
// ```
// // Response body should be empty
-// testResponse(t, res, 204, "^$")
+// validateResponse(t, res, 204, "^$")
// ```
-func testResponse(t *testing.T, res *http.Response, code int, body string) []byte {
+func validateResponse(res *http.Response, code int, body string) ([]byte, error) {
if res.StatusCode != code {
- t.Errorf("%s %s: Expected status code to be %d, is %d", res.Request.Method, res.Request.URL, code, res.StatusCode)
+ return nil, fmt.Errorf("%s %s: Expected status code to be %d, is %d", res.Request.Method, res.Request.URL, code, res.StatusCode)
}
defer res.Body.Close()
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
- t.Errorf("Error: %v", err)
+ return nil, fmt.Errorf("Error: %v", err)
}
match, err := regexp.Match(body, resBody)
@@ -64,216 +319,506 @@ func testResponse(t *testing.T, res *http.Response, code int, body string) []byt
}
if !match {
- t.Errorf("%s %s: Expected response body to match \"%s\", is \"%s\"", res.Request.Method, res.Request.URL, body, resBody)
+ return nil, fmt.Errorf("%s %s: Expected response body to match \"%s\", is \"%s\"", res.Request.Method, res.Request.URL, body, resBody)
}
- return resBody
+ return resBody, nil
+}
+
+func testResponse(t *testing.T, res *http.Response, code int, body string) {
+ if _, err := validateResponse(res, code, body); err != nil {
+ t.Error(err)
+ }
}
func testError(t *testing.T, res *http.Response, e ErrorResponse) {
testResponse(t, res, e.Status(), regexp.QuoteMeta(string(JsonifyErrorResponse(e))))
}
-func setupServer() (*Server, string) {
- storage := &MemoryStorage{}
- sender := &RecordSender{}
- templates := &Templates{
- template.Must(template.New("").Parse("{{ .email }}, {{ .activation_link }}")),
- template.Must(template.New("").Parse("{{ .email }}, {{ .delete_link }}")),
- htmlTemplate.Must(htmlTemplate.New("").Parse("")),
- htmlTemplate.Must(htmlTemplate.New("").Parse("{{ .email }}")),
- template.Must(template.New("").Parse("")),
- htmlTemplate.Must(htmlTemplate.New("").Parse("{{ .message }}")),
- }
+func TestAuthentication(t *testing.T) {
+ var res *http.Response
+ var err error
- logger := &Log{Config: &LogConfig{}}
- logger.Init()
- logger.Info.SetOutput(ioutil.Discard)
- logger.Error.SetOutput(ioutil.Discard)
- server := NewServer(logger, storage, sender, &ServerConfig{})
- server.Templates = templates
- server.Init()
+ ctx := newServerTestContext()
+ ctx.followRedirects(false)
+
+ t.Run("account not found", func(t *testing.T) {
+ ctx.resetAll()
+
+ // Trying to get an api key for a non-existing account using the PUT method should result in a 404
+ if res, err = ctx.request("PUT", ctx.host+"/auth/", url.Values{
+ "email": {"hello@world.com"},
+ }.Encode(), ApiVersion); err != nil {
+ t.Fatal(err)
+ }
+ // No account with this email exists yet and we have not specified 'create=true' in our request
+ testError(t, res, &AccountNotFound{})
+ })
+
+ t.Run("unauthenticated", func(t *testing.T) {
+ ctx.resetAll()
+
+ // Request should go through for route not requiring authentication
+ if res, err = ctx.request("GET", ctx.host+"/authtestnoauth/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "")
+
+ if ctx.capturedAuthToken != nil {
+ t.Error("Auth token to be passed to handler even though none was expected")
+ }
+
+ // Not logged in so we should be redirected to the login page
+ if res, err = ctx.request("GET", ctx.host+"/authtestweb/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusFound, "")
+ if res.Header.Get("Location") != "/login/" {
+ t.Error("Expected to be redirected to login page")
+ }
+
+ // Not authenticated so we should get a 401
+ if res, err = ctx.request("GET", ctx.host+"/authtestapi/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testError(t, res, &InvalidAuthToken{})
+ })
+
+ t.Run("type=api", func(t *testing.T) {
+ ctx.resetAll()
+
+ if _, err = ctx.loginApi(testEmail); err != nil {
+ t.Fatal(err)
+ }
+
+ // Route without authentication should always go through
+ if res, err = ctx.request("GET", ctx.host+"/authtestnoauth/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "")
+
+ // Even though no authentication is required for this route, an auth token should still be
+ // passed to the handler
+ at := ctx.capturedAuthToken
+ if at == nil {
+ t.Error("No auth token passed to handler")
+ } else {
+ if at.Type != "api" {
+ t.Error("Wrong token type. Expected %s, got %s", "api", at.Type)
+ }
+
+ if at.Email != testEmail {
+ t.Errorf("Wrong account. Expected %s, got %s", testEmail, at.Email)
+ }
+ }
+
+ // We're authenticated but with the wrong token type. Should get a 401
+ if res, err = ctx.request("GET", ctx.host+"/authtestweb/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testError(t, res, &InvalidAuthToken{})
+
+ // We're authenticated so the request should go through
+ if res, err = ctx.request("GET", ctx.host+"/authtestapi/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "")
+ })
+
+ t.Run("type=web", func(t *testing.T) {
+ ctx.resetAll()
+
+ if res, err = ctx.loginWeb(testEmail, ""); err != nil {
+ t.Fatal(err)
+ }
+
+ // By default user should be redirected to dasboard after login
+ testResponse(t, res, http.StatusFound, "")
+ if l := res.Header.Get("Location"); l != "/dashboard/" {
+ t.Errorf("Expected redirect to %s, got %s", "/dashboard/", res.Header.Get("Location"))
+ }
+
+ // Test route without authentication
+ if res, err = ctx.request("GET", ctx.host+"/authtestnoauth/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "")
+
+ at := ctx.capturedAuthToken
+ // Even though no authentication is required for this route, an auth token should still be
+ // passed to the handler
+ if at == nil {
+ t.Error("No auth token passed to handler")
+ } else {
+ if at.Type != "web" {
+ t.Error("Wrong token type. Expected %s, got %s", "web", at.Type)
+ }
+
+ if at.Email != testEmail {
+ t.Errorf("Wrong account. Expected %s, got %s", testEmail, at.Email)
+ }
+ }
+
+ // We're logged in, but with the wrong auth type. should get a 401
+ if res, err = ctx.request("GET", ctx.host+"/authtestapi/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testError(t, res, &InvalidAuthToken{})
+
+ // We're logged in so the request should go through
+ if res, err = ctx.request("GET", ctx.host+"/authtestweb/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "")
+
+ // Make sure auth token expires
+ time.Sleep(authMaxAge("web"))
+ if res, err = ctx.request("GET", ctx.host+"/authtestweb/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusFound, "")
+ if res.Header.Get("Location") != "/login/" {
+ t.Error("Expected to be redirected to login page")
+ }
+
+ // Redirect to other supported endpoints is also allowed
+ if res, err = ctx.loginWeb(testEmail, "/authtestweb/?query"); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusFound, "")
+ if l := res.Header.Get("Location"); l != "/authtestweb/?query" {
+ t.Errorf("Expected redirect to %s, got %s", "/authtestweb/?query", res.Header.Get("Location"))
+ }
+
+ // Using an external url or any unsupported endpoint should be treated as a bad request
+ res, err = ctx.loginWeb(testEmail, "http://attacker.com")
+ testError(t, res, &BadRequest{"invalid redirect path"})
- testServer := httptest.NewServer(server)
+ res, err = ctx.loginWeb(testEmail, "/notsupported/")
+ testError(t, res, &BadRequest{"invalid redirect path"})
+ })
- return server, testServer.URL
+ t.Run("invalid activation token", func(t *testing.T) {
+ // An invalid activation token should result in a bad request response
+ res, _ = ctx.request("GET", ctx.host+"/activate/?t=asdf", "", ApiVersion)
+ testError(t, res, &BadRequest{"invalid activation token"})
+ })
}
-// Full lifecycle test including
-// - Requesting an api key
-// - Activating an api key
-// - Getting data
-// - Putting data
-// - Requesting a data reset
-// - Confirming a data reset
-func TestLifeCycle(t *testing.T) {
- server, testURL := setupServer()
- sender := server.Sender.(*RecordSender)
-
- // Post request for api key
- res, _ := request("POST", testURL+"/auth/", url.Values{
- "email": {testEmail},
- }.Encode(), true, nil, ApiVersion)
+func TestCsrfProtection(t *testing.T) {
+ var res *http.Response
+ var err error
- // Response status code should be "ACCEPTED", response body should be the RFC4122-compliant auth token
- tokenJSON := testResponse(t, res, http.StatusAccepted, "")
+ ctx := newServerTestContext()
+ ctx.followRedirects(true)
- authToken := &AuthToken{}
- err := json.Unmarshal(tokenJSON, authToken)
+ if res, err = ctx.loginWeb(testEmail, "/csrftest/"); err != nil {
+ t.Fatal(err)
+ }
+ csrfToken, err := validateResponse(res, http.StatusOK, "")
if err != nil {
- t.Errorf("Expected response to be JSON representation of api key, got %s", tokenJSON)
+ t.Fatal(err)
}
- // Activation message should be sent to the correct email
- if sender.Recipient != testEmail {
- t.Errorf("Expected activation message to be sent to %s, instead got %s", testEmail, sender.Recipient)
+ if res, err = ctx.request("POST", ctx.host+"/csrftest/", url.Values{
+ "gorilla.csrf.Token": {"asdf"},
+ }.Encode(), ApiVersion); err != nil {
+ t.Fatal(err)
}
+ testError(t, res, &InvalidCsrfToken{})
- // Activation message should contain a valid activation link
- linkPattern := fmt.Sprintf("%s/activate/\\?v=%d&t=%s", testURL, ApiVersion, tokenPattern)
- msgPattern := fmt.Sprintf("%s, %s", testEmail, linkPattern)
- match, _ := regexp.MatchString(msgPattern, sender.Message)
- if !match {
- t.Errorf("Expected activation message to match \"%s\", got \"%s\"", msgPattern, sender.Message)
+ if res, err = ctx.request("POST", ctx.host+"/csrftest/", url.Values{
+ "gorilla.csrf.Token": {string(csrfToken)},
+ }.Encode(), ApiVersion); err != nil {
+ t.Fatal(err)
}
- link := regexp.MustCompile(linkPattern).FindString(sender.Message)
-
- // 'visit' activation link
- res, _ = http.Get(link)
testResponse(t, res, http.StatusOK, "")
+}
- // Get data request authenticated with obtained api key should return with status code 200 - OK and
- // empty response body (since we haven't written any data yet)
- res, _ = request("GET", testURL+"/store/", "", false, authToken, ApiVersion)
- testResponse(t, res, http.StatusOK, "^$")
+func TestStore(t *testing.T) {
+ var res *http.Response
+ var err error
- // Put request should return with status code 204 - NO CONTENT
- res, _ = request("PUT", testURL+"/store/", testData, false, authToken, ApiVersion)
- testResponse(t, res, http.StatusNoContent, "")
+ ctx := newServerTestContext()
+ ctx.followRedirects(true)
- // Now get data request should return the data previously saved through PUT
- res, _ = request("GET", testURL+"/store/", "", false, authToken, ApiVersion)
- testResponse(t, res, http.StatusOK, fmt.Sprintf("^%s$", testData))
+ t.Run("read(unauthenticated)", func(t *testing.T) {
+ // Get data request authenticated with obtained api key should return with status code 200 - OK and
+ // empty response body (since we haven't written any data yet)
+ if res, err = ctx.request("GET", ctx.host+"/store/", "", ApiVersion); err != nil {
+ t.Fatal(err)
+ }
+ testError(t, res, &InvalidAuthToken{})
+ })
- // Send data reset request. Response should have status code 202 - ACCEPTED
- sender.Reset()
- res, _ = request("DELETE", testURL+"/store/", "", false, authToken, ApiVersion)
- testResponse(t, res, http.StatusAccepted, "")
+ if _, err := ctx.loginApi(testEmail); err != nil {
+ t.Fatal(err)
+ }
- // Activation message should be sent to the correct email
- if sender.Recipient != testEmail {
- t.Errorf("Expected confirm delete message to be sent to %s, instead got %s", testEmail, sender.Recipient)
+ t.Run("read(empty)", func(t *testing.T) {
+ // Get data request authenticated with obtained api key should return with status code 200 - OK and
+ // empty response body (since we haven't written any data yet)
+ if res, err = ctx.request("GET", ctx.host+"/store/", "", ApiVersion); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "^$")
+ })
+
+ t.Run("write", func(t *testing.T) {
+ // Put request should return with status code 204 - NO CONTENT
+ if res, err = ctx.request("PUT", ctx.host+"/store/", testData, ApiVersion); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusNoContent, "")
+ })
+
+ t.Run("read(non-empty)", func(t *testing.T) {
+ // Now get data request should return the data previously saved through PUT
+ if res, err = ctx.request("GET", ctx.host+"/store/", "", ApiVersion); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, fmt.Sprintf("^%s$", testData))
+ })
+
+ t.Run("request delete", func(t *testing.T) {
+ // Send data reset request. Response should have status code 202 - ACCEPTED
+ if res, err = ctx.request("DELETE", ctx.host+"/store/", "", ApiVersion); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusAccepted, "")
+
+ // Activation message should be sent to the correct email
+ if ctx.sender.Recipient != testEmail {
+ t.Fatalf("Expected confirm delete message to be sent to %s, instead got %s", testEmail, ctx.sender.Recipient)
+ }
+
+ link, err := ctx.extractActivationLink()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // 'visit' link, should log in and redirect to delete store form
+ if res, err = ctx.request("GET", link, "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, fmt.Sprintf("^dashboard$"))
+ })
+
+ t.Run("reset data", func(t *testing.T) {
+ ctx.loginWeb(testEmail, "")
+
+ // Revoke auth token by id
+ if res, err = ctx.request("POST", ctx.host+"/deletestore/", url.Values{
+ "gorilla.csrf.Token": {ctx.getCsrfToken()},
+ }.Encode(), 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "")
+
+ ctx.loginApi(testEmail)
+ // Store should be empty
+ if res, err = ctx.request("GET", ctx.host+"/store/", "", ApiVersion); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "^$")
+ })
+}
+
+func TestDashboard(t *testing.T) {
+ ctx := newServerTestContext()
+ ctx.followRedirects(true)
+
+ // If not logged in, should redirect to login page
+ res, _ := ctx.request("GET", ctx.host+"/dashboard/", "", 0)
+ testResponse(t, res, http.StatusOK, "^login,,$")
+
+ if _, err := ctx.loginWeb(testEmail, ""); err != nil {
+ t.Fatal(err)
}
- // Confirmation message should contain a valid confirmation link
- linkPattern = fmt.Sprintf("%s/deletestore/\\?v=%d&t=%s", testURL, ApiVersion, tokenPattern)
- msgPattern = fmt.Sprintf("%s, %s", testEmail, linkPattern)
- match, _ = regexp.MatchString(msgPattern, sender.Message)
- if !match {
- t.Errorf("Expected activation message to match \"%s\", got \"%s\"", msgPattern, sender.Message)
+ // We should be logged in now, so dashboard should render
+ res, _ = ctx.request("GET", ctx.host+"/dashboard/", "", 0)
+ testResponse(t, res, http.StatusOK, "^dashboard$")
+}
+
+func TestLogout(t *testing.T) {
+ var res *http.Response
+ var err error
+
+ ctx := newServerTestContext()
+
+ if _, err = ctx.loginWeb(testEmail, ""); err != nil {
+ t.Fatal(err)
}
- link = regexp.MustCompile(linkPattern).FindString(sender.Message)
- // 'visit' confirmation link
- res, _ = http.Get(link)
- testResponse(t, res, http.StatusOK, fmt.Sprintf("^%s$", testEmail))
+ // Log out
+ if res, err = ctx.request("GET", ctx.host+"/logout/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "")
- // After data reset, data should be an empty string
- res, _ = request("GET", testURL+"/store/", "", false, authToken, ApiVersion)
- testResponse(t, res, http.StatusOK, "^$")
+ // If not logged in, should redirect to login page
+ if res, err = ctx.request("GET", ctx.host+"/dashboard/", "", 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "^login,,$")
}
-// Test correct handling of various error conditions
-func TestErrorConditions(t *testing.T) {
- _, testURL := setupServer()
+func TestRevokeAuthToken(t *testing.T) {
+ var res *http.Response
+ var err error
+
+ ctx := newServerTestContext()
+ ctx.followRedirects(true)
+
+ t.Run("unautenticated", func(t *testing.T) {
+ // If not logged in, should redirect to login page
+ if res, err = ctx.request("POST", ctx.host+"/revoke/", "", ApiVersion); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "login,,")
+ })
- // Trying to get an api key for a non-existing account using the PUT method should result in a 404
- res, _ := request("PUT", testURL+"/auth/", url.Values{
- "email": {"hello@world.com"},
- }.Encode(), true, nil, ApiVersion)
+ // Login in
+ if res, err = ctx.loginWeb(testEmail, ""); err != nil {
+ t.Fatal(err)
+ }
- // No account with this email exists yet and we have not specified 'create=true' in our request
- testError(t, res, &AccountNotFound{})
+ t.Run("revoke by token", func(t *testing.T) {
+ // Create and activate new auth token
+ if res, err = ctx.loginApi(testEmail); err != nil {
+ t.Fatal(err)
+ }
+ at := ctx.authToken
+ ctx.authToken = nil
+
+ // Revoke auth token by token
+ if res, err = ctx.request("POST", ctx.host+"/revoke/", url.Values{
+ "gorilla.csrf.Token": {ctx.getCsrfToken()},
+ "token": {at.Token},
+ }.Encode(), 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "")
- // A request without a valid authorization header should return with status code 401 - Unauthorized
- res, _ = request("GET", testURL+"/store/", "", false, nil, ApiVersion)
- testError(t, res, &Unauthorized{})
+ ctx.authToken = at
+ if res, err = ctx.request("GET", ctx.host+"/store/", "", ApiVersion); err != nil {
+ t.Fatal(err)
+ }
+ testError(t, res, &ExpiredAuthToken{})
+ })
- // Requests with unsupported HTTP methods should return with 405 - method not allowed
- res, _ = request("POST", testURL+"/store/", "", false, nil, ApiVersion)
- testError(t, res, &MethodNotAllowed{})
+ t.Run("revoke by id", func(t *testing.T) {
+ // Create and activate new auth token
+ if res, err = ctx.loginApi(testEmail); err != nil {
+ t.Fatal(err)
+ }
+ at := ctx.authToken
+ ctx.authToken = nil
+
+ // Get id
+ acc := &Account{Email: at.Email}
+ ctx.storage.Get(acc)
+ at.Validate(acc)
+
+ // Revoke auth token by id
+ if res, err = ctx.request("POST", ctx.host+"/revoke/", url.Values{
+ "gorilla.csrf.Token": {ctx.getCsrfToken()},
+ "id": {at.Id},
+ }.Encode(), 0); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusOK, "")
- // Requests to unsupported paths should return with 404 - not found
- res, _ = request("GET", testURL+"/invalidpath", "", false, nil, ApiVersion)
- testError(t, res, &UnsupportedEndpoint{})
+ ctx.authToken = at
+ if res, err = ctx.request("GET", ctx.host+"/store/", "", ApiVersion); err != nil {
+ t.Fatal(err)
+ }
+ testError(t, res, &ExpiredAuthToken{})
+ })
+}
- // An invalid activation token should result in a bad request response
- res, _ = request("GET", testURL+"/activate/?t=asdf", "", false, nil, ApiVersion)
- testError(t, res, &InvalidToken{})
+func TestMethodNotAllowed(t *testing.T) {
+ ctx := newServerTestContext()
+ // Requests with unsupported HTTP methods should return with 405 - method not allowed
+ if res, err := ctx.request("POST", ctx.host+"/store/", "", ApiVersion); err != nil {
+ t.Fatal(err)
+ } else {
+ testError(t, res, &MethodNotAllowed{})
+ }
+}
- // An invalid deletion token should result in a bad request response
- res, _ = request("GET", testURL+"/deletestore/?t=asdf", "", false, nil, ApiVersion)
- testError(t, res, &InvalidToken{})
+func TestUnsupportedEndpoint(t *testing.T) {
+ ctx := newServerTestContext()
+ // Requests to unsupported paths should return with 404 - not found
+ if res, err := ctx.request("GET", ctx.host+"/invalidpath", "", ApiVersion); err != nil {
+ t.Fatal(err)
+ } else {
+ testError(t, res, &UnsupportedEndpoint{})
+ }
}
func TestOutdatedVersion(t *testing.T) {
- server, testURL := setupServer()
- sender := server.Sender.(*RecordSender)
+ ctx := newServerTestContext()
- e := &UnsupportedApiVersion{}
-
- sender.Reset()
+ // The root path is a special case in that the only way to figure out if the client is using
+ // and older api version is if the Authorization header is using the 'ApiKey' authentication scheme
token, _ := token()
- res, _ := request("GET", testURL+"/", "", false, &AuthToken{Email: testEmail, Token: token}, 0)
- testError(t, res, e)
- if sender.Recipient != testEmail {
- t.Errorf("Expected outdated message to be sent to %s, instead got %s", testEmail, sender.Recipient)
+ req, _ := http.NewRequest("GET", ctx.host+"/", nil)
+ req.Header.Add("Accept", "application/json")
+ req.Header.Add("Authorization", fmt.Sprintf("ApiKey %s:%s", testEmail, token))
+ res, _ := ctx.client.Do(req)
+ testError(t, res, &UnsupportedApiVersion{})
+ if ctx.sender.Recipient != testEmail {
+ t.Errorf("Expected outdated message to be sent to %s, instead got %s", testEmail, ctx.sender.Recipient)
}
- sender.Reset()
- res, _ = request("POST", testURL+"/auth", url.Values{
+ ctx.resetAll()
+
+ // When doing an auth request, the email form field should be used for sending the notification since
+ // the user is not authenticated
+ res, _ = ctx.request("POST", ctx.host+"/auth/", url.Values{
"email": {testEmail},
- }.Encode(), true, nil, 0)
- testError(t, res, e)
- if sender.Recipient != testEmail {
- t.Errorf("Expected outdated message to be sent to %s, instead got %s", testEmail, sender.Recipient)
+ }.Encode(), 0)
+ testError(t, res, &UnsupportedApiVersion{0, ApiVersion})
+ if ctx.sender.Recipient != testEmail {
+ t.Errorf("Expected outdated message to be sent to %s, instead got %s", testEmail, ctx.sender.Recipient)
}
- sender.Reset()
- res, _ = request("DELETE", testURL+"/"+testEmail, "", false, nil, 0)
- testError(t, res, e)
- if sender.Recipient != testEmail {
- t.Errorf("Expected outdated message to be sent to %s, instead got %s", testEmail, sender.Recipient)
+ ctx.resetAll()
+
+ ctx.loginApi(testEmail)
+
+ // When doing an auth request, the email form field should be used for sending the notification since
+ // the user is not authenticated
+ res, _ = ctx.request("GET", ctx.host+"/store/", url.Values{
+ "email": {testEmail},
+ }.Encode(), 0)
+ testError(t, res, &UnsupportedApiVersion{0, ApiVersion})
+ if ctx.sender.Recipient != testEmail {
+ t.Errorf("Expected outdated message to be sent to %s, instead got %s", testEmail, ctx.sender.Recipient)
}
}
func TestPanicRecovery(t *testing.T) {
- server, testURL := setupServer()
-
- // Make sure the server recovers properly from runtime panics in handler functions
- server.mux.HandleFunc("/panic/", func(w http.ResponseWriter, r *http.Request) {
- panic("Everyone panic!!!")
- })
- res, _ := request("GET", testURL+"/panic/", "", false, nil, 1)
+ ctx := newServerTestContext()
+ res, _ := ctx.request("GET", ctx.host+"/panic/", "", 0)
testError(t, res, &ServerError{})
- server.mux.HandleFunc("/panic2/", func(w http.ResponseWriter, r *http.Request) {
- panic(errors.New("Everyone panic!!!"))
- })
- res, _ = request("GET", testURL+"/panic2/", "", false, nil, 1)
+ res, _ = ctx.request("POST", ctx.host+"/panic/", "", 0)
testError(t, res, &ServerError{})
}
func TestErrorFormat(t *testing.T) {
- _, testURL := setupServer()
+ ctx := newServerTestContext()
e := &UnsupportedEndpoint{}
testErr := func(format string, expected []byte) {
- req, _ := http.NewRequest("GET", fmt.Sprintf("%s/invalidpath/?v=%d", testURL, ApiVersion), nil)
+ req, _ := http.NewRequest("GET", fmt.Sprintf("%s/invalidpath/?v=%d", ctx.host, ApiVersion), nil)
if format != "" {
req.Header.Add("Accept", format)
}
- res, _ := http.DefaultClient.Do(req)
+ res, _ := ctx.client.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
if !bytes.Equal(body, expected) {
@@ -286,3 +831,115 @@ func TestErrorFormat(t *testing.T) {
testErr("text/html", []byte(fmt.Sprintf("%s", e.Message())))
testErr("", []byte(e.Message()))
}
+
+func TestEmailRateLimit(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping test in short mode.")
+ }
+
+ initRL := func(ctx *serverTestContext) {
+ rl, _ := NewEmailRateLimiter(RateQuota{PerSec(1), 1}, RateQuota{PerSec(1), 1})
+ ctx.server.emailRateLimiter = rl
+ }
+
+ request := func(ctx *serverTestContext, ip string, email string) (*http.Response, error) {
+ req, err := http.NewRequest("POST", ctx.host+"/auth/", bytes.NewBuffer([]byte(url.Values{
+ "email": {email},
+ }.Encode())))
+ if err != nil {
+ return nil, err
+ }
+
+ req.RemoteAddr = ip
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Add("Accept", "application/vnd.padlock;version=1")
+
+ w := httptest.NewRecorder()
+
+ ctx.server.Handler.ServeHTTP(w, req)
+
+ res := w.Result()
+ res.Request = req
+
+ return res, nil
+ }
+
+ t.Run("const_ip", func(t *testing.T) {
+ var res *http.Response
+ var err error
+
+ t.Parallel()
+
+ ctx := newServerTestContext()
+ initRL(ctx)
+
+ // One request per second with a burst of 1 additional request is allowed
+ if res, err = request(ctx, "1.2.3.4", "email1"); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusAccepted, "")
+
+ if res, err = request(ctx, "1.2.3.4", "email2"); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusAccepted, "")
+
+ if res, err = request(ctx, "1.2.3.4", "email3"); err != nil {
+ t.Fatal(err)
+ }
+ testError(t, res, &RateLimitExceeded{})
+
+ // Requests with different ip should still go through
+ if res, err = request(ctx, "1.2.3.5", "email4"); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusAccepted, "")
+
+ // After a second of wait, request should go through again
+ time.Sleep(time.Second)
+ if res, err = request(ctx, "1.2.3.4", "email5"); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusAccepted, "")
+ })
+
+ t.Run("const_email", func(t *testing.T) {
+ var res *http.Response
+ var err error
+
+ t.Parallel()
+
+ ctx := newServerTestContext()
+ initRL(ctx)
+
+ // One request per second with a burst of 1 additional request is allowed
+ if res, err = request(ctx, "1.2.3.4", "email1"); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusAccepted, "")
+
+ if res, err = request(ctx, "1.2.3.5", "email1"); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusAccepted, "")
+
+ if res, err = request(ctx, "1.2.3.6", "email1"); err != nil {
+ t.Fatal(err)
+ }
+ testError(t, res, &RateLimitExceeded{})
+
+ // Requests with different email should still go through
+ if res, err = request(ctx, "1.2.3.7", "email2"); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusAccepted, "")
+
+ // After a second of wait, request should go through again
+ time.Sleep(time.Second)
+ if res, err = request(ctx, "1.2.3.8", "email1"); err != nil {
+ t.Fatal(err)
+ }
+ testResponse(t, res, http.StatusAccepted, "")
+ })
+
+}
diff --git a/padlockcloud/storage.go b/padlockcloud/storage.go
index fa2ac59..27275e7 100644
--- a/padlockcloud/storage.go
+++ b/padlockcloud/storage.go
@@ -4,7 +4,9 @@ import "reflect"
import "errors"
import "encoding/json"
import "path/filepath"
+import "time"
import "github.com/syndtr/goleveldb/leveldb"
+import "github.com/syndtr/goleveldb/leveldb/iterator"
// Error singletons
var (
@@ -16,6 +18,10 @@ var (
ErrStorageClosed = errors.New("padlock: storage closed")
)
+func typeFromStorable(t Storable) reflect.Type {
+ return reflect.TypeOf(t).Elem()
+}
+
// Common interface for types that can be stored using the `Storage` interface.
type Storable interface {
// This method is used for retrieving a key hat can be used to identify an object
@@ -28,12 +34,22 @@ type Storable interface {
Deserialize([]byte) error
}
+type StorageIterator interface {
+ Next() bool
+ Get(Storable) error
+ Release()
+}
+
// Common interface for storage implementations
type Storage interface {
// Prepares the database for use
Open() error
// Closes the database and performs cleanup actions
Close() error
+ // Returns readyness of the storage
+ Ready() bool
+ // Whether storage can store a certain storable
+ CanStore(t Storable) bool
// Populates a given `Storable` object with data retrieved from the store
Get(Storable) error
// Updates the store with the data from a given `Storable` object
@@ -41,7 +57,7 @@ type Storage interface {
// Removes a given `Storable` object from the store
Delete(Storable) error
// Lists all keys for a given `Storable` type
- List(Storable) ([]string, error)
+ Iterator(Storable) (StorageIterator, error)
}
// Map of supported `Storable` implementations along with identifier strings that can be used for
@@ -49,7 +65,15 @@ type Storage interface {
var StorableTypes = map[reflect.Type]string{}
func RegisterStorable(t Storable, loc string) {
- StorableTypes[reflect.TypeOf(t).Elem()] = loc
+ StorableTypes[typeFromStorable(t)] = loc
+}
+
+type LevelDBIterator struct {
+ iterator.Iterator
+}
+
+func (iter *LevelDBIterator) Get(t Storable) error {
+ return t.Deserialize(iter.Value())
}
type LevelDBConfig struct {
@@ -95,9 +119,18 @@ func (s *LevelDBStorage) Close() error {
return nil
}
+func (s *LevelDBStorage) Ready() bool {
+ return s.stores != nil
+}
+
+func (s *LevelDBStorage) CanStore(t Storable) bool {
+ _, err := s.getDB(t)
+ return err == nil
+}
+
// Get `leveldb.DB` instance for a given type
func (s *LevelDBStorage) getDB(t Storable) (*leveldb.DB, error) {
- db := s.stores[reflect.TypeOf(t).Elem()]
+ db := s.stores[typeFromStorable(t)]
if db == nil {
return nil, ErrUnregisteredStorable
@@ -172,21 +205,36 @@ func (s *LevelDBStorage) Delete(t Storable) error {
return db.Delete(t.Key(), nil)
}
-func (s *LevelDBStorage) List(t Storable) ([]string, error) {
- var keys []string
-
+func (s *LevelDBStorage) Iterator(t Storable) (StorageIterator, error) {
db, err := s.getDB(t)
if err != nil {
- return keys, err
+ return nil, err
}
iter := db.NewIterator(nil, nil)
- for iter.Next() {
- keys = append(keys, string(iter.Key()))
+ return &LevelDBIterator{iter}, nil
+}
+
+type SliceIterator struct {
+ s [][]byte
+ i int
+}
+
+func (iter *SliceIterator) Next() bool {
+ if iter.i < len(iter.s)-1 {
+ iter.i = iter.i + 1
+ return true
}
- iter.Release()
- return keys, nil
+ return false
+}
+
+func (iter *SliceIterator) Get(t Storable) error {
+ return t.Deserialize(iter.s[iter.i])
+}
+
+func (iter *SliceIterator) Release() {
+ iter.s = nil
}
// In-memory implemenation of the `Storage` interface Mainly used for testing
@@ -261,25 +309,99 @@ func (s *MemoryStorage) Delete(t Storable) error {
return nil
}
-func (s *MemoryStorage) List(t Storable) ([]string, error) {
- var l []string
+func (s *MemoryStorage) Ready() bool {
+ return s.store != nil
+}
+
+func (s *MemoryStorage) CanStore(t Storable) bool {
+ return true
+}
+func (s *MemoryStorage) Iterator(t Storable) (StorageIterator, error) {
if s.store == nil {
- return l, ErrStorageClosed
+ return nil, ErrStorageClosed
}
if t == nil {
- return l, ErrUnregisteredStorable
+ return nil, ErrUnregisteredStorable
}
ts := s.store[reflect.TypeOf(t)]
if ts == nil {
- return l, ErrUnregisteredStorable
+ return nil, ErrUnregisteredStorable
+ }
+
+ var sl [][]byte
+ for _, val := range ts {
+ sl = append(sl, val)
+ }
+
+ return &SliceIterator{
+ s: sl,
+ }, nil
+}
+
+type StorageCleaner struct {
+ storage Storage
+ storable Storable
+ cond func(t Storable) bool
+ stop chan bool
+ Log *Log
+}
+
+func (cl *StorageCleaner) Start(interval time.Duration) {
+ cl.stop = make(chan bool)
+ ticker := time.NewTicker(interval)
+ go func() {
+ for {
+ select {
+ case <-ticker.C:
+ cl.Clean()
+ case <-cl.stop:
+ ticker.Stop()
+ return
+ }
+ }
+ }()
+}
+
+func (cl *StorageCleaner) Stop() {
+ cl.stop <- true
+}
+
+func (cl *StorageCleaner) Clean() error {
+ iter, err := cl.storage.Iterator(cl.storable)
+ if err != nil {
+ return err
+ }
+ defer iter.Release()
+
+ n := 0
+ for iter.Next() {
+ iter.Get(cl.storable)
+ if cl.cond(cl.storable) {
+ cl.storage.Delete(cl.storable)
+ n = n + 1
+ }
}
- for key, _ := range ts {
- l = append(l, key)
+ if n > 0 && cl.Log != nil {
+ cl.Log.Info.Printf("Deleted %d entries of %T\n", n, cl.storable)
}
- return l, nil
+ return nil
+}
+
+func NewStorageCleaner(s Storage, t Storable, cond func(t Storable) bool) (*StorageCleaner, error) {
+ if !s.Ready() {
+ return nil, ErrStorageClosed
+ }
+ if !s.CanStore(t) {
+ return nil, ErrUnregisteredStorable
+ }
+ return &StorageCleaner{
+ storage: s,
+ storable: t,
+ cond: cond,
+ }, nil
}
diff --git a/padlockcloud/storage_test.go b/padlockcloud/storage_test.go
index 6348cce..6848747 100644
--- a/padlockcloud/storage_test.go
+++ b/padlockcloud/storage_test.go
@@ -3,7 +3,6 @@ package padlockcloud
import "testing"
import "io/ioutil"
import "os"
-import "fmt"
type testStrbl string
@@ -56,16 +55,6 @@ func TestLevelDBStorage(t *testing.T) {
storage.Open()
defer storage.Close()
- // Haven't written anything to the storage yet, so `Storage.List()` should give us an empty slice
- list, err := storage.List(&storable)
- if err != nil {
- t.Fatalf("Should return no error, got %v", err)
- }
- listStr := fmt.Sprintf("%s", list)
- if listStr != "[]" {
- t.Fatalf("Expected '%s', got '%s'", "[]", listStr)
- }
-
// Still haven't written anything to storage, so trying to get a specific instace should give us
// ErrNotFound
if err := storage.Get(&storable); err != ErrNotFound {
@@ -87,16 +76,6 @@ func TestLevelDBStorage(t *testing.T) {
t.Fatalf("Expected '%s', got '%s'", storable, storable2)
}
- // Now that we have a database entry we should have something in the list as well
- list, err = storage.List(&storable)
- if err != nil {
- t.Fatalf("Should return no error, got %v", err)
- }
- listStr = fmt.Sprintf("%s", list)
- if listStr != "[somekey]" {
- t.Fatalf("Expected '%s', got '%s'", "[somekey]", listStr)
- }
-
// Lets delete our one entry again. This should work without any incidents
if err := storage.Delete(&storable); err != nil {
t.Fatalf("Should return no error, got %v", err)
diff --git a/padlockcloud/templates.go b/padlockcloud/templates.go
index adeec46..04eae27 100644
--- a/padlockcloud/templates.go
+++ b/padlockcloud/templates.go
@@ -1,52 +1,60 @@
package padlockcloud
-import "path/filepath"
-import t "text/template"
-import ht "html/template"
+import fp "path/filepath"
+import t "html/template"
+import "errors"
// Wrapper for holding references to template instances used for rendering emails, webpages etc.
type Templates struct {
+ BasePage *t.Template
+ BaseEmail *t.Template
// Email template for api key activation email
ActivateAuthTokenEmail *t.Template
- // Email template for deletion confirmation email
- DeleteStoreEmail *t.Template
- // Template for success page for activating an auth token
- ActivateAuthTokenSuccess *ht.Template
- // Template for success page for deleting account data
- DeleteStoreSuccess *ht.Template
// Email template for clients using an outdated api version
DeprecatedVersionEmail *t.Template
- ErrorPage *ht.Template
+ ErrorPage *t.Template
+ LoginPage *t.Template
+ Dashboard *t.Template
+}
+
+func ExtendTemplate(base *t.Template, path string) (*t.Template, error) {
+ if base == nil {
+ return nil, errors.New("Base page is nil")
+ }
+
+ b, err := base.Clone()
+ if err != nil {
+ return nil, err
+ }
+
+ return b.ParseFiles(path)
}
// Loads templates from given directory
-func LoadTemplates(path string) (*Templates, error) {
+func LoadTemplates(tt *Templates, p string) error {
var err error
- tt := &Templates{}
-
- tPath := func(filename string) string {
- return filepath.Join(path, filename)
+ if tt.BaseEmail, err = t.ParseFiles(fp.Join(p, "email/base.txt")); err != nil {
+ return err
}
-
- if tt.ActivateAuthTokenEmail, err = t.ParseFiles(tPath("activate-auth-token-email.txt")); err != nil {
- return nil, err
+ if tt.BasePage, err = t.ParseFiles(fp.Join(p, "page/base.html")); err != nil {
+ return err
}
- if tt.DeleteStoreEmail, err = t.ParseFiles(tPath("delete-store-email.txt")); err != nil {
- return nil, err
+ if tt.ActivateAuthTokenEmail, err = ExtendTemplate(tt.BaseEmail, fp.Join(p, "email/activate-auth-token.txt")); err != nil {
+ return err
}
- if tt.ActivateAuthTokenSuccess, err = ht.ParseFiles(tPath("activate-auth-token-success.html")); err != nil {
- return nil, err
+ if tt.DeprecatedVersionEmail, err = ExtendTemplate(tt.BaseEmail, fp.Join(p, "email/deprecated-version.txt")); err != nil {
+ return err
}
- if tt.DeleteStoreSuccess, err = ht.ParseFiles(tPath("delete-store-success.html")); err != nil {
- return nil, err
+ if tt.ErrorPage, err = ExtendTemplate(tt.BasePage, fp.Join(p, "page/error.html")); err != nil {
+ return err
}
- if tt.DeprecatedVersionEmail, err = t.ParseFiles(tPath("deprecated-version-email.txt")); err != nil {
- return nil, err
+ if tt.LoginPage, err = ExtendTemplate(tt.BasePage, fp.Join(p, "page/login.html")); err != nil {
+ return err
}
- if tt.ErrorPage, err = ht.ParseFiles(tPath("error-page.html")); err != nil {
- return nil, err
+ if tt.Dashboard, err = ExtendTemplate(tt.BasePage, fp.Join(p, "page/dashboard.html")); err != nil {
+ return err
}
- return tt, nil
+ return nil
}
diff --git a/padlockcloud/templates_test.go b/padlockcloud/templates_test.go
index 5c9a983..6cc6b42 100644
--- a/padlockcloud/templates_test.go
+++ b/padlockcloud/templates_test.go
@@ -12,20 +12,23 @@ func TestLoadTemplates(t *testing.T) {
}
defer os.RemoveAll(dir)
- if _, err := LoadTemplates(dir); err == nil {
+ templates := &Templates{}
+
+ if err := LoadTemplates(templates, dir); err == nil {
t.Fatal("Trying to load templates from empty or unexisting directory should return an error")
}
- templates, err := LoadTemplates(filepath.Join(DefaultAssetsPath, "templates"))
- if err != nil {
+ if err := LoadTemplates(templates, filepath.Join(DefaultAssetsPath, "templates")); err != nil {
t.Fatalf("Loading templates from default dir should work without errors, got %v", err)
}
- if templates.ActivateAuthTokenEmail == nil ||
- templates.DeleteStoreEmail == nil ||
- templates.ActivateAuthTokenSuccess == nil ||
- templates.DeleteStoreSuccess == nil ||
- templates.DeprecatedVersionEmail == nil {
+ if templates.BasePage == nil ||
+ templates.BaseEmail == nil ||
+ templates.ActivateAuthTokenEmail == nil ||
+ templates.DeprecatedVersionEmail == nil ||
+ templates.ErrorPage == nil ||
+ templates.LoginPage == nil ||
+ templates.Dashboard == nil {
t.Fatal("All templates should be initialized and not nil")
}
}
diff --git a/padlockcloud/util.go b/padlockcloud/util.go
index ba4745e..837767a 100644
--- a/padlockcloud/util.go
+++ b/padlockcloud/util.go
@@ -10,9 +10,17 @@ const tokenPattern = `[a-zA-Z0-9\-_]{22}`
var gopath = os.Getenv("GOPATH")
var DefaultAssetsPath = filepath.Join(gopath, "src/github.com/maklesoft/padlock-cloud/assets")
+func randomBytes(n int) ([]byte, error) {
+ b := make([]byte, n)
+ if _, err := rand.Read(b); err != nil {
+ return nil, err
+ }
+ return b, nil
+}
+
func randomBase64(nBytes int) (string, error) {
- b := make([]byte, nBytes)
- _, err := rand.Read(b)
+ b, err := randomBytes(nBytes)
+
if err != nil {
return "", err
}
diff --git a/vendor/github.com/Sirupsen/logrus/.gitignore b/vendor/github.com/Sirupsen/logrus/.gitignore
deleted file mode 100644
index 66be63a..0000000
--- a/vendor/github.com/Sirupsen/logrus/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-logrus
diff --git a/vendor/github.com/Sirupsen/logrus/.travis.yml b/vendor/github.com/Sirupsen/logrus/.travis.yml
deleted file mode 100644
index dee4eb2..0000000
--- a/vendor/github.com/Sirupsen/logrus/.travis.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-language: go
-go:
- - 1.3
- - 1.4
- - 1.5
- - 1.6
- - tip
-install:
- - go get -t ./...
-script: GOMAXPROCS=4 GORACE="halt_on_error=1" go test -race -v ./...
diff --git a/vendor/github.com/Sirupsen/logrus/CHANGELOG.md b/vendor/github.com/Sirupsen/logrus/CHANGELOG.md
deleted file mode 100644
index f2c2bc2..0000000
--- a/vendor/github.com/Sirupsen/logrus/CHANGELOG.md
+++ /dev/null
@@ -1,66 +0,0 @@
-# 0.10.0
-
-* feature: Add a test hook (#180)
-* feature: `ParseLevel` is now case-insensitive (#326)
-* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
-* performance: avoid re-allocations on `WithFields` (#335)
-
-# 0.9.0
-
-* 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
-* logrus/core: run tests with `-race`
-* logrus/core: detect TTY based on `stderr`
-* logrus/core: support `WithError` on logger
-* logrus/core: Solaris support
-
-# 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/Sirupsen/logrus/README.md b/vendor/github.com/Sirupsen/logrus/README.md
deleted file mode 100644
index f8302c3..0000000
--- a/vendor/github.com/Sirupsen/logrus/README.md
+++ /dev/null
@@ -1,402 +0,0 @@
-# Logrus [![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/Sirupsen/logrus?status.svg)](https://godoc.org/github.com/Sirupsen/logrus)
-
-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.SetFormatter(&log.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.SetFormatter(&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 |
-| [Influxus] (http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB] (http://influxdata.com/) |
-| [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 |
-| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) |
-| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) |
-| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka |
-| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) |
-| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch|
-| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)|
-| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) |
-
-#### 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.
-
-Third party logging formatters:
-
-* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
-* [`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.|
-
-#### Testing
-
-Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
-
-* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
-* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
-
-```go
-logger, hook := NewNullLogger()
-logger.Error("Hello error")
-
-assert.Equal(1, len(hook.Entries))
-assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
-assert.Equal("Hello error", hook.LastEntry().Message)
-
-hook.Reset()
-assert.Nil(hook.LastEntry())
-```
-
-#### Fatal handlers
-
-Logrus can register one or more functions that will be called when any `fatal`
-level message is logged. The registered handlers will be executed before
-logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
-to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
-
-```
-...
-handler := func() {
- // gracefully shutdown something...
-}
-logrus.RegisterExitHandler(handler)
-...
-```
diff --git a/vendor/github.com/Sirupsen/logrus/alt_exit.go b/vendor/github.com/Sirupsen/logrus/alt_exit.go
deleted file mode 100644
index b4c9e84..0000000
--- a/vendor/github.com/Sirupsen/logrus/alt_exit.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package logrus
-
-// The following code was sourced and modified from the
-// https://bitbucket.org/tebeka/atexit package governed by the following license:
-//
-// Copyright (c) 2012 Miki Tebeka .
-//
-// 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.
-
-import (
- "fmt"
- "os"
-)
-
-var handlers = []func(){}
-
-func runHandler(handler func()) {
- defer func() {
- if err := recover(); err != nil {
- fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
- }
- }()
-
- handler()
-}
-
-func runHandlers() {
- for _, handler := range handlers {
- runHandler(handler)
- }
-}
-
-// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
-func Exit(code int) {
- runHandlers()
- os.Exit(code)
-}
-
-// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
-// all handlers. The handlers will also be invoked when any Fatal log entry is
-// made.
-//
-// This method is useful when a caller wishes to use logrus to log a fatal
-// message but also needs to gracefully shutdown. An example usecase could be
-// closing database connections, or sending a alert that the application is
-// closing.
-func RegisterExitHandler(handler func()) {
- handlers = append(handlers, handler)
-}
diff --git a/vendor/github.com/Sirupsen/logrus/doc.go b/vendor/github.com/Sirupsen/logrus/doc.go
deleted file mode 100644
index dddd5f8..0000000
--- a/vendor/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/Sirupsen/logrus/entry.go b/vendor/github.com/Sirupsen/logrus/entry.go
deleted file mode 100644
index 54bfc57..0000000
--- a/vendor/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 := make(Fields, len(entry.Data)+len(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...))
- }
- 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...))
- }
- 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...))
- }
- 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/Sirupsen/logrus/exported.go b/vendor/github.com/Sirupsen/logrus/exported.go
deleted file mode 100644
index 9a0120a..0000000
--- a/vendor/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/Sirupsen/logrus/formatter.go b/vendor/github.com/Sirupsen/logrus/formatter.go
deleted file mode 100644
index b5fbe93..0000000
--- a/vendor/github.com/Sirupsen/logrus/formatter.go
+++ /dev/null
@@ -1,45 +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) {
- if t, ok := data["time"]; ok {
- data["fields.time"] = t
- }
-
- if m, ok := data["msg"]; ok {
- data["fields.msg"] = m
- }
-
- if l, ok := data["level"]; ok {
- data["fields.level"] = l
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/Sirupsen/logrus/hooks.go
deleted file mode 100644
index 3f151cd..0000000
--- a/vendor/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/Sirupsen/logrus/json_formatter.go b/vendor/github.com/Sirupsen/logrus/json_formatter.go
deleted file mode 100644
index 2ad6dc5..0000000
--- a/vendor/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/Sirupsen/logrus/logger.go b/vendor/github.com/Sirupsen/logrus/logger.go
deleted file mode 100644
index 9052a80..0000000
--- a/vendor/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 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...)
- }
- 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...)
- }
- 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...)
- }
- Exit(1)
-}
-
-func (logger *Logger) Panicln(args ...interface{}) {
- if logger.Level >= PanicLevel {
- NewEntry(logger).Panicln(args...)
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/Sirupsen/logrus/logrus.go
deleted file mode 100644
index e596691..0000000
--- a/vendor/github.com/Sirupsen/logrus/logrus.go
+++ /dev/null
@@ -1,143 +0,0 @@
-package logrus
-
-import (
- "fmt"
- "log"
- "strings"
-)
-
-// 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 strings.ToLower(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)
-}
-
-// A constant exposing all logging levels
-var AllLevels = []Level{
- PanicLevel,
- FatalLevel,
- ErrorLevel,
- WarnLevel,
- InfoLevel,
- DebugLevel,
-}
-
-// 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{})
-}
-
-// The FieldLogger interface generalizes the Entry and Logger types
-type FieldLogger interface {
- WithField(key string, value interface{}) *Entry
- WithFields(fields Fields) *Entry
- WithError(err error) *Entry
-
- Debugf(format string, args ...interface{})
- Infof(format string, args ...interface{})
- Printf(format string, args ...interface{})
- Warnf(format string, args ...interface{})
- Warningf(format string, args ...interface{})
- Errorf(format string, args ...interface{})
- Fatalf(format string, args ...interface{})
- Panicf(format string, args ...interface{})
-
- Debug(args ...interface{})
- Info(args ...interface{})
- Print(args ...interface{})
- Warn(args ...interface{})
- Warning(args ...interface{})
- Error(args ...interface{})
- Fatal(args ...interface{})
- Panic(args ...interface{})
-
- Debugln(args ...interface{})
- Infoln(args ...interface{})
- Println(args ...interface{})
- Warnln(args ...interface{})
- Warningln(args ...interface{})
- Errorln(args ...interface{})
- Fatalln(args ...interface{})
- Panicln(args ...interface{})
-}
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go b/vendor/github.com/Sirupsen/logrus/terminal_bsd.go
deleted file mode 100644
index 71f8d67..0000000
--- a/vendor/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/Sirupsen/logrus/terminal_linux.go b/vendor/github.com/Sirupsen/logrus/terminal_linux.go
deleted file mode 100644
index a2c0b40..0000000
--- a/vendor/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/Sirupsen/logrus/terminal_notwindows.go b/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
deleted file mode 100644
index b343b3a..0000000
--- a/vendor/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/Sirupsen/logrus/terminal_solaris.go b/vendor/github.com/Sirupsen/logrus/terminal_solaris.go
deleted file mode 100644
index 3e70bf7..0000000
--- a/vendor/github.com/Sirupsen/logrus/terminal_solaris.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// +build solaris
-
-package logrus
-
-import (
- "os"
-
- "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/Sirupsen/logrus/terminal_windows.go b/vendor/github.com/Sirupsen/logrus/terminal_windows.go
deleted file mode 100644
index 0146845..0000000
--- a/vendor/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/Sirupsen/logrus/text_formatter.go b/vendor/github.com/Sirupsen/logrus/text_formatter.go
deleted file mode 100644
index 6afd0e0..0000000
--- a/vendor/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 true
- }
- }
- return false
-}
-
-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/Sirupsen/logrus/writer.go b/vendor/github.com/Sirupsen/logrus/writer.go
deleted file mode 100644
index f74d2aa..0000000
--- a/vendor/github.com/Sirupsen/logrus/writer.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package logrus
-
-import (
- "bufio"
- "io"
- "runtime"
-)
-
-func (logger *Logger) Writer() *io.PipeWriter {
- return logger.WriterLevel(InfoLevel)
-}
-
-func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
- reader, writer := io.Pipe()
-
- var printFunc func(args ...interface{})
- switch level {
- case DebugLevel:
- printFunc = logger.Debug
- case InfoLevel:
- printFunc = logger.Info
- case WarnLevel:
- printFunc = logger.Warn
- case ErrorLevel:
- printFunc = logger.Error
- case FatalLevel:
- printFunc = logger.Fatal
- case PanicLevel:
- printFunc = logger.Panic
- default:
- printFunc = logger.Print
- }
-
- go logger.writerScanner(reader, printFunc)
- runtime.SetFinalizer(writer, writerFinalizer)
-
- return writer
-}
-
-func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
- scanner := bufio.NewScanner(reader)
- for scanner.Scan() {
- printFunc(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/alecthomas/template/README.md b/vendor/github.com/alecthomas/template/README.md
deleted file mode 100644
index ef6a8ee..0000000
--- a/vendor/github.com/alecthomas/template/README.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# Go's `text/template` package with newline elision
-
-This is a fork of Go 1.4's [text/template](http://golang.org/pkg/text/template/) package with one addition: a backslash immediately after a closing delimiter will delete all subsequent newlines until a non-newline.
-
-eg.
-
-```
-{{if true}}\
-hello
-{{end}}\
-```
-
-Will result in:
-
-```
-hello\n
-```
-
-Rather than:
-
-```
-\n
-hello\n
-\n
-```
diff --git a/vendor/github.com/alecthomas/template/doc.go b/vendor/github.com/alecthomas/template/doc.go
deleted file mode 100644
index 223c595..0000000
--- a/vendor/github.com/alecthomas/template/doc.go
+++ /dev/null
@@ -1,406 +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 template implements data-driven templates for generating textual output.
-
-To generate HTML output, see package html/template, which has the same interface
-as this package but automatically secures HTML output against certain attacks.
-
-Templates are executed by applying them to a data structure. Annotations in the
-template refer to elements of the data structure (typically a field of a struct
-or a key in a map) to control execution and derive values to be displayed.
-Execution of the template walks the structure and sets the cursor, represented
-by a period '.' and called "dot", to the value at the current location in the
-structure as execution proceeds.
-
-The input text for a template is UTF-8-encoded text in any format.
-"Actions"--data evaluations or control structures--are delimited by
-"{{" and "}}"; all text outside actions is copied to the output unchanged.
-Actions may not span newlines, although comments can.
-
-Once parsed, a template may be executed safely in parallel.
-
-Here is a trivial example that prints "17 items are made of wool".
-
- type Inventory struct {
- Material string
- Count uint
- }
- sweaters := Inventory{"wool", 17}
- tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
- if err != nil { panic(err) }
- err = tmpl.Execute(os.Stdout, sweaters)
- if err != nil { panic(err) }
-
-More intricate examples appear below.
-
-Actions
-
-Here is the list of actions. "Arguments" and "pipelines" are evaluations of
-data, defined in detail below.
-
-*/
-// {{/* a comment */}}
-// A comment; discarded. May contain newlines.
-// Comments do not nest and must start and end at the
-// delimiters, as shown here.
-/*
-
- {{pipeline}}
- The default textual representation of the value of the pipeline
- is copied to the output.
-
- {{if pipeline}} T1 {{end}}
- If the value of the pipeline is empty, no output is generated;
- otherwise, T1 is executed. The empty values are false, 0, any
- nil pointer or interface value, and any array, slice, map, or
- string of length zero.
- Dot is unaffected.
-
- {{if pipeline}} T1 {{else}} T0 {{end}}
- If the value of the pipeline is empty, T0 is executed;
- otherwise, T1 is executed. Dot is unaffected.
-
- {{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
- To simplify the appearance of if-else chains, the else action
- of an if may include another if directly; the effect is exactly
- the same as writing
- {{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}
-
- {{range pipeline}} T1 {{end}}
- The value of the pipeline must be an array, slice, map, or channel.
- If the value of the pipeline has length zero, nothing is output;
- otherwise, dot is set to the successive elements of the array,
- slice, or map and T1 is executed. If the value is a map and the
- keys are of basic type with a defined order ("comparable"), the
- elements will be visited in sorted key order.
-
- {{range pipeline}} T1 {{else}} T0 {{end}}
- The value of the pipeline must be an array, slice, map, or channel.
- If the value of the pipeline has length zero, dot is unaffected and
- T0 is executed; otherwise, dot is set to the successive elements
- of the array, slice, or map and T1 is executed.
-
- {{template "name"}}
- The template with the specified name is executed with nil data.
-
- {{template "name" pipeline}}
- The template with the specified name is executed with dot set
- to the value of the pipeline.
-
- {{with pipeline}} T1 {{end}}
- If the value of the pipeline is empty, no output is generated;
- otherwise, dot is set to the value of the pipeline and T1 is
- executed.
-
- {{with pipeline}} T1 {{else}} T0 {{end}}
- If the value of the pipeline is empty, dot is unaffected and T0
- is executed; otherwise, dot is set to the value of the pipeline
- and T1 is executed.
-
-Arguments
-
-An argument is a simple value, denoted by one of the following.
-
- - A boolean, string, character, integer, floating-point, imaginary
- or complex constant in Go syntax. These behave like Go's untyped
- constants, although raw strings may not span newlines.
- - The keyword nil, representing an untyped Go nil.
- - The character '.' (period):
- .
- The result is the value of dot.
- - A variable name, which is a (possibly empty) alphanumeric string
- preceded by a dollar sign, such as
- $piOver2
- or
- $
- The result is the value of the variable.
- Variables are described below.
- - The name of a field of the data, which must be a struct, preceded
- by a period, such as
- .Field
- The result is the value of the field. Field invocations may be
- chained:
- .Field1.Field2
- Fields can also be evaluated on variables, including chaining:
- $x.Field1.Field2
- - The name of a key of the data, which must be a map, preceded
- by a period, such as
- .Key
- The result is the map element value indexed by the key.
- Key invocations may be chained and combined with fields to any
- depth:
- .Field1.Key1.Field2.Key2
- Although the key must be an alphanumeric identifier, unlike with
- field names they do not need to start with an upper case letter.
- Keys can also be evaluated on variables, including chaining:
- $x.key1.key2
- - The name of a niladic method of the data, preceded by a period,
- such as
- .Method
- The result is the value of invoking the method with dot as the
- receiver, dot.Method(). Such a method must have one return value (of
- any type) or two return values, the second of which is an error.
- If it has two and the returned error is non-nil, execution terminates
- and an error is returned to the caller as the value of Execute.
- Method invocations may be chained and combined with fields and keys
- to any depth:
- .Field1.Key1.Method1.Field2.Key2.Method2
- Methods can also be evaluated on variables, including chaining:
- $x.Method1.Field
- - The name of a niladic function, such as
- fun
- The result is the value of invoking the function, fun(). The return
- types and values behave as in methods. Functions and function
- names are described below.
- - A parenthesized instance of one the above, for grouping. The result
- may be accessed by a field or map key invocation.
- print (.F1 arg1) (.F2 arg2)
- (.StructValuedMethod "arg").Field
-
-Arguments may evaluate to any type; if they are pointers the implementation
-automatically indirects to the base type when required.
-If an evaluation yields a function value, such as a function-valued
-field of a struct, the function is not invoked automatically, but it
-can be used as a truth value for an if action and the like. To invoke
-it, use the call function, defined below.
-
-A pipeline is a possibly chained sequence of "commands". A command is a simple
-value (argument) or a function or method call, possibly with multiple arguments:
-
- Argument
- The result is the value of evaluating the argument.
- .Method [Argument...]
- The method can be alone or the last element of a chain but,
- unlike methods in the middle of a chain, it can take arguments.
- The result is the value of calling the method with the
- arguments:
- dot.Method(Argument1, etc.)
- functionName [Argument...]
- The result is the value of calling the function associated
- with the name:
- function(Argument1, etc.)
- Functions and function names are described below.
-
-Pipelines
-
-A pipeline may be "chained" by separating a sequence of commands with pipeline
-characters '|'. In a chained pipeline, the result of the each command is
-passed as the last argument of the following command. The output of the final
-command in the pipeline is the value of the pipeline.
-
-The output of a command will be either one value or two values, the second of
-which has type error. If that second value is present and evaluates to
-non-nil, execution terminates and the error is returned to the caller of
-Execute.
-
-Variables
-
-A pipeline inside an action may initialize a variable to capture the result.
-The initialization has syntax
-
- $variable := pipeline
-
-where $variable is the name of the variable. An action that declares a
-variable produces no output.
-
-If a "range" action initializes a variable, the variable is set to the
-successive elements of the iteration. Also, a "range" may declare two
-variables, separated by a comma:
-
- range $index, $element := pipeline
-
-in which case $index and $element are set to the successive values of the
-array/slice index or map key and element, respectively. Note that if there is
-only one variable, it is assigned the element; this is opposite to the
-convention in Go range clauses.
-
-A variable's scope extends to the "end" action of the control structure ("if",
-"with", or "range") in which it is declared, or to the end of the template if
-there is no such control structure. A template invocation does not inherit
-variables from the point of its invocation.
-
-When execution begins, $ is set to the data argument passed to Execute, that is,
-to the starting value of dot.
-
-Examples
-
-Here are some example one-line templates demonstrating pipelines and variables.
-All produce the quoted word "output":
-
- {{"\"output\""}}
- A string constant.
- {{`"output"`}}
- A raw string constant.
- {{printf "%q" "output"}}
- A function call.
- {{"output" | printf "%q"}}
- A function call whose final argument comes from the previous
- command.
- {{printf "%q" (print "out" "put")}}
- A parenthesized argument.
- {{"put" | printf "%s%s" "out" | printf "%q"}}
- A more elaborate call.
- {{"output" | printf "%s" | printf "%q"}}
- A longer chain.
- {{with "output"}}{{printf "%q" .}}{{end}}
- A with action using dot.
- {{with $x := "output" | printf "%q"}}{{$x}}{{end}}
- A with action that creates and uses a variable.
- {{with $x := "output"}}{{printf "%q" $x}}{{end}}
- A with action that uses the variable in another action.
- {{with $x := "output"}}{{$x | printf "%q"}}{{end}}
- The same, but pipelined.
-
-Functions
-
-During execution functions are found in two function maps: first in the
-template, then in the global function map. By default, no functions are defined
-in the template but the Funcs method can be used to add them.
-
-Predefined global functions are named as follows.
-
- and
- Returns the boolean AND of its arguments by returning the
- first empty argument or the last argument, that is,
- "and x y" behaves as "if x then y else x". All the
- arguments are evaluated.
- call
- Returns the result of calling the first argument, which
- must be a function, with the remaining arguments as parameters.
- Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where
- Y is a func-valued field, map entry, or the like.
- The first argument must be the result of an evaluation
- that yields a value of function type (as distinct from
- a predefined function such as print). The function must
- return either one or two result values, the second of which
- is of type error. If the arguments don't match the function
- or the returned error value is non-nil, execution stops.
- html
- Returns the escaped HTML equivalent of the textual
- representation of its arguments.
- index
- Returns the result of indexing its first argument by the
- following arguments. Thus "index x 1 2 3" is, in Go syntax,
- x[1][2][3]. Each indexed item must be a map, slice, or array.
- js
- Returns the escaped JavaScript equivalent of the textual
- representation of its arguments.
- len
- Returns the integer length of its argument.
- not
- Returns the boolean negation of its single argument.
- or
- Returns the boolean OR of its arguments by returning the
- first non-empty argument or the last argument, that is,
- "or x y" behaves as "if x then x else y". All the
- arguments are evaluated.
- print
- An alias for fmt.Sprint
- printf
- An alias for fmt.Sprintf
- println
- An alias for fmt.Sprintln
- urlquery
- Returns the escaped value of the textual representation of
- its arguments in a form suitable for embedding in a URL query.
-
-The boolean functions take any zero value to be false and a non-zero
-value to be true.
-
-There is also a set of binary comparison operators defined as
-functions:
-
- eq
- Returns the boolean truth of arg1 == arg2
- ne
- Returns the boolean truth of arg1 != arg2
- lt
- Returns the boolean truth of arg1 < arg2
- le
- Returns the boolean truth of arg1 <= arg2
- gt
- Returns the boolean truth of arg1 > arg2
- ge
- Returns the boolean truth of arg1 >= arg2
-
-For simpler multi-way equality tests, eq (only) accepts two or more
-arguments and compares the second and subsequent to the first,
-returning in effect
-
- arg1==arg2 || arg1==arg3 || arg1==arg4 ...
-
-(Unlike with || in Go, however, eq is a function call and all the
-arguments will be evaluated.)
-
-The comparison functions work on basic types only (or named basic
-types, such as "type Celsius float32"). They implement the Go rules
-for comparison of values, except that size and exact type are
-ignored, so any integer value, signed or unsigned, may be compared
-with any other integer value. (The arithmetic value is compared,
-not the bit pattern, so all negative integers are less than all
-unsigned integers.) However, as usual, one may not compare an int
-with a float32 and so on.
-
-Associated templates
-
-Each template is named by a string specified when it is created. Also, each
-template is associated with zero or more other templates that it may invoke by
-name; such associations are transitive and form a name space of templates.
-
-A template may use a template invocation to instantiate another associated
-template; see the explanation of the "template" action above. The name must be
-that of a template associated with the template that contains the invocation.
-
-Nested template definitions
-
-When parsing a template, another template may be defined and associated with the
-template being parsed. Template definitions must appear at the top level of the
-template, much like global variables in a Go program.
-
-The syntax of such definitions is to surround each template declaration with a
-"define" and "end" action.
-
-The define action names the template being created by providing a string
-constant. Here is a simple example:
-
- `{{define "T1"}}ONE{{end}}
- {{define "T2"}}TWO{{end}}
- {{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
- {{template "T3"}}`
-
-This defines two templates, T1 and T2, and a third T3 that invokes the other two
-when it is executed. Finally it invokes T3. If executed this template will
-produce the text
-
- ONE TWO
-
-By construction, a template may reside in only one association. If it's
-necessary to have a template addressable from multiple associations, the
-template definition must be parsed multiple times to create distinct *Template
-values, or must be copied with the Clone or AddParseTree method.
-
-Parse may be called multiple times to assemble the various associated templates;
-see the ParseFiles and ParseGlob functions and methods for simple ways to parse
-related templates stored in files.
-
-A template may be executed directly or through ExecuteTemplate, which executes
-an associated template identified by name. To invoke our example above, we
-might write,
-
- err := tmpl.Execute(os.Stdout, "no data needed")
- if err != nil {
- log.Fatalf("execution failed: %s", err)
- }
-
-or to invoke a particular template explicitly by name,
-
- err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed")
- if err != nil {
- log.Fatalf("execution failed: %s", err)
- }
-
-*/
-package template
diff --git a/vendor/github.com/alecthomas/template/exec.go b/vendor/github.com/alecthomas/template/exec.go
deleted file mode 100644
index c3078e5..0000000
--- a/vendor/github.com/alecthomas/template/exec.go
+++ /dev/null
@@ -1,845 +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 template
-
-import (
- "bytes"
- "fmt"
- "io"
- "reflect"
- "runtime"
- "sort"
- "strings"
-
- "github.com/alecthomas/template/parse"
-)
-
-// state represents the state of an execution. It's not part of the
-// template so that multiple executions of the same template
-// can execute in parallel.
-type state struct {
- tmpl *Template
- wr io.Writer
- node parse.Node // current node, for errors
- vars []variable // push-down stack of variable values.
-}
-
-// variable holds the dynamic value of a variable such as $, $x etc.
-type variable struct {
- name string
- value reflect.Value
-}
-
-// push pushes a new variable on the stack.
-func (s *state) push(name string, value reflect.Value) {
- s.vars = append(s.vars, variable{name, value})
-}
-
-// mark returns the length of the variable stack.
-func (s *state) mark() int {
- return len(s.vars)
-}
-
-// pop pops the variable stack up to the mark.
-func (s *state) pop(mark int) {
- s.vars = s.vars[0:mark]
-}
-
-// setVar overwrites the top-nth variable on the stack. Used by range iterations.
-func (s *state) setVar(n int, value reflect.Value) {
- s.vars[len(s.vars)-n].value = value
-}
-
-// varValue returns the value of the named variable.
-func (s *state) varValue(name string) reflect.Value {
- for i := s.mark() - 1; i >= 0; i-- {
- if s.vars[i].name == name {
- return s.vars[i].value
- }
- }
- s.errorf("undefined variable: %s", name)
- return zero
-}
-
-var zero reflect.Value
-
-// at marks the state to be on node n, for error reporting.
-func (s *state) at(node parse.Node) {
- s.node = node
-}
-
-// doublePercent returns the string with %'s replaced by %%, if necessary,
-// so it can be used safely inside a Printf format string.
-func doublePercent(str string) string {
- if strings.Contains(str, "%") {
- str = strings.Replace(str, "%", "%%", -1)
- }
- return str
-}
-
-// errorf formats the error and terminates processing.
-func (s *state) errorf(format string, args ...interface{}) {
- name := doublePercent(s.tmpl.Name())
- if s.node == nil {
- format = fmt.Sprintf("template: %s: %s", name, format)
- } else {
- location, context := s.tmpl.ErrorContext(s.node)
- format = fmt.Sprintf("template: %s: executing %q at <%s>: %s", location, name, doublePercent(context), format)
- }
- panic(fmt.Errorf(format, args...))
-}
-
-// errRecover is the handler that turns panics into returns from the top
-// level of Parse.
-func errRecover(errp *error) {
- e := recover()
- if e != nil {
- switch err := e.(type) {
- case runtime.Error:
- panic(e)
- case error:
- *errp = err
- default:
- panic(e)
- }
- }
-}
-
-// ExecuteTemplate applies the template associated with t that has the given name
-// to the specified data object and writes the output to wr.
-// If an error occurs executing the template or writing its output,
-// execution stops, but partial results may already have been written to
-// the output writer.
-// A template may be executed safely in parallel.
-func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
- tmpl := t.tmpl[name]
- if tmpl == nil {
- return fmt.Errorf("template: no template %q associated with template %q", name, t.name)
- }
- return tmpl.Execute(wr, data)
-}
-
-// Execute applies a parsed template to the specified data object,
-// and writes the output to wr.
-// If an error occurs executing the template or writing its output,
-// execution stops, but partial results may already have been written to
-// the output writer.
-// A template may be executed safely in parallel.
-func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
- defer errRecover(&err)
- value := reflect.ValueOf(data)
- state := &state{
- tmpl: t,
- wr: wr,
- vars: []variable{{"$", value}},
- }
- t.init()
- if t.Tree == nil || t.Root == nil {
- var b bytes.Buffer
- for name, tmpl := range t.tmpl {
- if tmpl.Tree == nil || tmpl.Root == nil {
- continue
- }
- if b.Len() > 0 {
- b.WriteString(", ")
- }
- fmt.Fprintf(&b, "%q", name)
- }
- var s string
- if b.Len() > 0 {
- s = "; defined templates are: " + b.String()
- }
- state.errorf("%q is an incomplete or empty template%s", t.Name(), s)
- }
- state.walk(value, t.Root)
- return
-}
-
-// Walk functions step through the major pieces of the template structure,
-// generating output as they go.
-func (s *state) walk(dot reflect.Value, node parse.Node) {
- s.at(node)
- switch node := node.(type) {
- case *parse.ActionNode:
- // Do not pop variables so they persist until next end.
- // Also, if the action declares variables, don't print the result.
- val := s.evalPipeline(dot, node.Pipe)
- if len(node.Pipe.Decl) == 0 {
- s.printValue(node, val)
- }
- case *parse.IfNode:
- s.walkIfOrWith(parse.NodeIf, dot, node.Pipe, node.List, node.ElseList)
- case *parse.ListNode:
- for _, node := range node.Nodes {
- s.walk(dot, node)
- }
- case *parse.RangeNode:
- s.walkRange(dot, node)
- case *parse.TemplateNode:
- s.walkTemplate(dot, node)
- case *parse.TextNode:
- if _, err := s.wr.Write(node.Text); err != nil {
- s.errorf("%s", err)
- }
- case *parse.WithNode:
- s.walkIfOrWith(parse.NodeWith, dot, node.Pipe, node.List, node.ElseList)
- default:
- s.errorf("unknown node: %s", node)
- }
-}
-
-// walkIfOrWith walks an 'if' or 'with' node. The two control structures
-// are identical in behavior except that 'with' sets dot.
-func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
- defer s.pop(s.mark())
- val := s.evalPipeline(dot, pipe)
- truth, ok := isTrue(val)
- if !ok {
- s.errorf("if/with can't use %v", val)
- }
- if truth {
- if typ == parse.NodeWith {
- s.walk(val, list)
- } else {
- s.walk(dot, list)
- }
- } else if elseList != nil {
- s.walk(dot, elseList)
- }
-}
-
-// isTrue reports whether the value is 'true', in the sense of not the zero of its type,
-// and whether the value has a meaningful truth value.
-func isTrue(val reflect.Value) (truth, ok bool) {
- if !val.IsValid() {
- // Something like var x interface{}, never set. It's a form of nil.
- return false, true
- }
- switch val.Kind() {
- case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
- truth = val.Len() > 0
- case reflect.Bool:
- truth = val.Bool()
- case reflect.Complex64, reflect.Complex128:
- truth = val.Complex() != 0
- case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:
- truth = !val.IsNil()
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- truth = val.Int() != 0
- case reflect.Float32, reflect.Float64:
- truth = val.Float() != 0
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- truth = val.Uint() != 0
- case reflect.Struct:
- truth = true // Struct values are always true.
- default:
- return
- }
- return truth, true
-}
-
-func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
- s.at(r)
- defer s.pop(s.mark())
- val, _ := indirect(s.evalPipeline(dot, r.Pipe))
- // mark top of stack before any variables in the body are pushed.
- mark := s.mark()
- oneIteration := func(index, elem reflect.Value) {
- // Set top var (lexically the second if there are two) to the element.
- if len(r.Pipe.Decl) > 0 {
- s.setVar(1, elem)
- }
- // Set next var (lexically the first if there are two) to the index.
- if len(r.Pipe.Decl) > 1 {
- s.setVar(2, index)
- }
- s.walk(elem, r.List)
- s.pop(mark)
- }
- switch val.Kind() {
- case reflect.Array, reflect.Slice:
- if val.Len() == 0 {
- break
- }
- for i := 0; i < val.Len(); i++ {
- oneIteration(reflect.ValueOf(i), val.Index(i))
- }
- return
- case reflect.Map:
- if val.Len() == 0 {
- break
- }
- for _, key := range sortKeys(val.MapKeys()) {
- oneIteration(key, val.MapIndex(key))
- }
- return
- case reflect.Chan:
- if val.IsNil() {
- break
- }
- i := 0
- for ; ; i++ {
- elem, ok := val.Recv()
- if !ok {
- break
- }
- oneIteration(reflect.ValueOf(i), elem)
- }
- if i == 0 {
- break
- }
- return
- case reflect.Invalid:
- break // An invalid value is likely a nil map, etc. and acts like an empty map.
- default:
- s.errorf("range can't iterate over %v", val)
- }
- if r.ElseList != nil {
- s.walk(dot, r.ElseList)
- }
-}
-
-func (s *state) walkTemplate(dot reflect.Value, t *parse.TemplateNode) {
- s.at(t)
- tmpl := s.tmpl.tmpl[t.Name]
- if tmpl == nil {
- s.errorf("template %q not defined", t.Name)
- }
- // Variables declared by the pipeline persist.
- dot = s.evalPipeline(dot, t.Pipe)
- newState := *s
- newState.tmpl = tmpl
- // No dynamic scoping: template invocations inherit no variables.
- newState.vars = []variable{{"$", dot}}
- newState.walk(dot, tmpl.Root)
-}
-
-// Eval functions evaluate pipelines, commands, and their elements and extract
-// values from the data structure by examining fields, calling methods, and so on.
-// The printing of those values happens only through walk functions.
-
-// evalPipeline returns the value acquired by evaluating a pipeline. If the
-// pipeline has a variable declaration, the variable will be pushed on the
-// stack. Callers should therefore pop the stack after they are finished
-// executing commands depending on the pipeline value.
-func (s *state) evalPipeline(dot reflect.Value, pipe *parse.PipeNode) (value reflect.Value) {
- if pipe == nil {
- return
- }
- s.at(pipe)
- for _, cmd := range pipe.Cmds {
- value = s.evalCommand(dot, cmd, value) // previous value is this one's final arg.
- // If the object has type interface{}, dig down one level to the thing inside.
- if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 {
- value = reflect.ValueOf(value.Interface()) // lovely!
- }
- }
- for _, variable := range pipe.Decl {
- s.push(variable.Ident[0], value)
- }
- return value
-}
-
-func (s *state) notAFunction(args []parse.Node, final reflect.Value) {
- if len(args) > 1 || final.IsValid() {
- s.errorf("can't give argument to non-function %s", args[0])
- }
-}
-
-func (s *state) evalCommand(dot reflect.Value, cmd *parse.CommandNode, final reflect.Value) reflect.Value {
- firstWord := cmd.Args[0]
- switch n := firstWord.(type) {
- case *parse.FieldNode:
- return s.evalFieldNode(dot, n, cmd.Args, final)
- case *parse.ChainNode:
- return s.evalChainNode(dot, n, cmd.Args, final)
- case *parse.IdentifierNode:
- // Must be a function.
- return s.evalFunction(dot, n, cmd, cmd.Args, final)
- case *parse.PipeNode:
- // Parenthesized pipeline. The arguments are all inside the pipeline; final is ignored.
- return s.evalPipeline(dot, n)
- case *parse.VariableNode:
- return s.evalVariableNode(dot, n, cmd.Args, final)
- }
- s.at(firstWord)
- s.notAFunction(cmd.Args, final)
- switch word := firstWord.(type) {
- case *parse.BoolNode:
- return reflect.ValueOf(word.True)
- case *parse.DotNode:
- return dot
- case *parse.NilNode:
- s.errorf("nil is not a command")
- case *parse.NumberNode:
- return s.idealConstant(word)
- case *parse.StringNode:
- return reflect.ValueOf(word.Text)
- }
- s.errorf("can't evaluate command %q", firstWord)
- panic("not reached")
-}
-
-// idealConstant is called to return the value of a number in a context where
-// we don't know the type. In that case, the syntax of the number tells us
-// its type, and we use Go rules to resolve. Note there is no such thing as
-// a uint ideal constant in this situation - the value must be of int type.
-func (s *state) idealConstant(constant *parse.NumberNode) reflect.Value {
- // These are ideal constants but we don't know the type
- // and we have no context. (If it was a method argument,
- // we'd know what we need.) The syntax guides us to some extent.
- s.at(constant)
- switch {
- case constant.IsComplex:
- return reflect.ValueOf(constant.Complex128) // incontrovertible.
- case constant.IsFloat && !isHexConstant(constant.Text) && strings.IndexAny(constant.Text, ".eE") >= 0:
- return reflect.ValueOf(constant.Float64)
- case constant.IsInt:
- n := int(constant.Int64)
- if int64(n) != constant.Int64 {
- s.errorf("%s overflows int", constant.Text)
- }
- return reflect.ValueOf(n)
- case constant.IsUint:
- s.errorf("%s overflows int", constant.Text)
- }
- return zero
-}
-
-func isHexConstant(s string) bool {
- return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')
-}
-
-func (s *state) evalFieldNode(dot reflect.Value, field *parse.FieldNode, args []parse.Node, final reflect.Value) reflect.Value {
- s.at(field)
- return s.evalFieldChain(dot, dot, field, field.Ident, args, final)
-}
-
-func (s *state) evalChainNode(dot reflect.Value, chain *parse.ChainNode, args []parse.Node, final reflect.Value) reflect.Value {
- s.at(chain)
- // (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields.
- pipe := s.evalArg(dot, nil, chain.Node)
- if len(chain.Field) == 0 {
- s.errorf("internal error: no fields in evalChainNode")
- }
- return s.evalFieldChain(dot, pipe, chain, chain.Field, args, final)
-}
-
-func (s *state) evalVariableNode(dot reflect.Value, variable *parse.VariableNode, args []parse.Node, final reflect.Value) reflect.Value {
- // $x.Field has $x as the first ident, Field as the second. Eval the var, then the fields.
- s.at(variable)
- value := s.varValue(variable.Ident[0])
- if len(variable.Ident) == 1 {
- s.notAFunction(args, final)
- return value
- }
- return s.evalFieldChain(dot, value, variable, variable.Ident[1:], args, final)
-}
-
-// evalFieldChain evaluates .X.Y.Z possibly followed by arguments.
-// dot is the environment in which to evaluate arguments, while
-// receiver is the value being walked along the chain.
-func (s *state) evalFieldChain(dot, receiver reflect.Value, node parse.Node, ident []string, args []parse.Node, final reflect.Value) reflect.Value {
- n := len(ident)
- for i := 0; i < n-1; i++ {
- receiver = s.evalField(dot, ident[i], node, nil, zero, receiver)
- }
- // Now if it's a method, it gets the arguments.
- return s.evalField(dot, ident[n-1], node, args, final, receiver)
-}
-
-func (s *state) evalFunction(dot reflect.Value, node *parse.IdentifierNode, cmd parse.Node, args []parse.Node, final reflect.Value) reflect.Value {
- s.at(node)
- name := node.Ident
- function, ok := findFunction(name, s.tmpl)
- if !ok {
- s.errorf("%q is not a defined function", name)
- }
- return s.evalCall(dot, function, cmd, name, args, final)
-}
-
-// evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
-// The 'final' argument represents the return value from the preceding
-// value of the pipeline, if any.
-func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
- if !receiver.IsValid() {
- return zero
- }
- typ := receiver.Type()
- receiver, _ = indirect(receiver)
- // Unless it's an interface, need to get to a value of type *T to guarantee
- // we see all methods of T and *T.
- ptr := receiver
- if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
- ptr = ptr.Addr()
- }
- if method := ptr.MethodByName(fieldName); method.IsValid() {
- return s.evalCall(dot, method, node, fieldName, args, final)
- }
- hasArgs := len(args) > 1 || final.IsValid()
- // It's not a method; must be a field of a struct or an element of a map. The receiver must not be nil.
- receiver, isNil := indirect(receiver)
- if isNil {
- s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
- }
- switch receiver.Kind() {
- case reflect.Struct:
- tField, ok := receiver.Type().FieldByName(fieldName)
- if ok {
- field := receiver.FieldByIndex(tField.Index)
- if tField.PkgPath != "" { // field is unexported
- s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
- }
- // If it's a function, we must call it.
- if hasArgs {
- s.errorf("%s has arguments but cannot be invoked as function", fieldName)
- }
- return field
- }
- s.errorf("%s is not a field of struct type %s", fieldName, typ)
- case reflect.Map:
- // If it's a map, attempt to use the field name as a key.
- nameVal := reflect.ValueOf(fieldName)
- if nameVal.Type().AssignableTo(receiver.Type().Key()) {
- if hasArgs {
- s.errorf("%s is not a method but has arguments", fieldName)
- }
- return receiver.MapIndex(nameVal)
- }
- }
- s.errorf("can't evaluate field %s in type %s", fieldName, typ)
- panic("not reached")
-}
-
-var (
- errorType = reflect.TypeOf((*error)(nil)).Elem()
- fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
-)
-
-// evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so
-// it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0]
-// as the function itself.
-func (s *state) evalCall(dot, fun reflect.Value, node parse.Node, name string, args []parse.Node, final reflect.Value) reflect.Value {
- if args != nil {
- args = args[1:] // Zeroth arg is function name/node; not passed to function.
- }
- typ := fun.Type()
- numIn := len(args)
- if final.IsValid() {
- numIn++
- }
- numFixed := len(args)
- if typ.IsVariadic() {
- numFixed = typ.NumIn() - 1 // last arg is the variadic one.
- if numIn < numFixed {
- s.errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args))
- }
- } else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() {
- s.errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args))
- }
- if !goodFunc(typ) {
- // TODO: This could still be a confusing error; maybe goodFunc should provide info.
- s.errorf("can't call method/function %q with %d results", name, typ.NumOut())
- }
- // Build the arg list.
- argv := make([]reflect.Value, numIn)
- // Args must be evaluated. Fixed args first.
- i := 0
- for ; i < numFixed && i < len(args); i++ {
- argv[i] = s.evalArg(dot, typ.In(i), args[i])
- }
- // Now the ... args.
- if typ.IsVariadic() {
- argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice.
- for ; i < len(args); i++ {
- argv[i] = s.evalArg(dot, argType, args[i])
- }
- }
- // Add final value if necessary.
- if final.IsValid() {
- t := typ.In(typ.NumIn() - 1)
- if typ.IsVariadic() {
- t = t.Elem()
- }
- argv[i] = s.validateType(final, t)
- }
- result := fun.Call(argv)
- // If we have an error that is not nil, stop execution and return that error to the caller.
- if len(result) == 2 && !result[1].IsNil() {
- s.at(node)
- s.errorf("error calling %s: %s", name, result[1].Interface().(error))
- }
- return result[0]
-}
-
-// canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero.
-func canBeNil(typ reflect.Type) bool {
- switch typ.Kind() {
- case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
- return true
- }
- return false
-}
-
-// validateType guarantees that the value is valid and assignable to the type.
-func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
- if !value.IsValid() {
- if typ == nil || canBeNil(typ) {
- // An untyped nil interface{}. Accept as a proper nil value.
- return reflect.Zero(typ)
- }
- s.errorf("invalid value; expected %s", typ)
- }
- if typ != nil && !value.Type().AssignableTo(typ) {
- if value.Kind() == reflect.Interface && !value.IsNil() {
- value = value.Elem()
- if value.Type().AssignableTo(typ) {
- return value
- }
- // fallthrough
- }
- // Does one dereference or indirection work? We could do more, as we
- // do with method receivers, but that gets messy and method receivers
- // are much more constrained, so it makes more sense there than here.
- // Besides, one is almost always all you need.
- switch {
- case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
- value = value.Elem()
- if !value.IsValid() {
- s.errorf("dereference of nil pointer of type %s", typ)
- }
- case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
- value = value.Addr()
- default:
- s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
- }
- }
- return value
-}
-
-func (s *state) evalArg(dot reflect.Value, typ reflect.Type, n parse.Node) reflect.Value {
- s.at(n)
- switch arg := n.(type) {
- case *parse.DotNode:
- return s.validateType(dot, typ)
- case *parse.NilNode:
- if canBeNil(typ) {
- return reflect.Zero(typ)
- }
- s.errorf("cannot assign nil to %s", typ)
- case *parse.FieldNode:
- return s.validateType(s.evalFieldNode(dot, arg, []parse.Node{n}, zero), typ)
- case *parse.VariableNode:
- return s.validateType(s.evalVariableNode(dot, arg, nil, zero), typ)
- case *parse.PipeNode:
- return s.validateType(s.evalPipeline(dot, arg), typ)
- case *parse.IdentifierNode:
- return s.evalFunction(dot, arg, arg, nil, zero)
- case *parse.ChainNode:
- return s.validateType(s.evalChainNode(dot, arg, nil, zero), typ)
- }
- switch typ.Kind() {
- case reflect.Bool:
- return s.evalBool(typ, n)
- case reflect.Complex64, reflect.Complex128:
- return s.evalComplex(typ, n)
- case reflect.Float32, reflect.Float64:
- return s.evalFloat(typ, n)
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return s.evalInteger(typ, n)
- case reflect.Interface:
- if typ.NumMethod() == 0 {
- return s.evalEmptyInterface(dot, n)
- }
- case reflect.String:
- return s.evalString(typ, n)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return s.evalUnsignedInteger(typ, n)
- }
- s.errorf("can't handle %s for arg of type %s", n, typ)
- panic("not reached")
-}
-
-func (s *state) evalBool(typ reflect.Type, n parse.Node) reflect.Value {
- s.at(n)
- if n, ok := n.(*parse.BoolNode); ok {
- value := reflect.New(typ).Elem()
- value.SetBool(n.True)
- return value
- }
- s.errorf("expected bool; found %s", n)
- panic("not reached")
-}
-
-func (s *state) evalString(typ reflect.Type, n parse.Node) reflect.Value {
- s.at(n)
- if n, ok := n.(*parse.StringNode); ok {
- value := reflect.New(typ).Elem()
- value.SetString(n.Text)
- return value
- }
- s.errorf("expected string; found %s", n)
- panic("not reached")
-}
-
-func (s *state) evalInteger(typ reflect.Type, n parse.Node) reflect.Value {
- s.at(n)
- if n, ok := n.(*parse.NumberNode); ok && n.IsInt {
- value := reflect.New(typ).Elem()
- value.SetInt(n.Int64)
- return value
- }
- s.errorf("expected integer; found %s", n)
- panic("not reached")
-}
-
-func (s *state) evalUnsignedInteger(typ reflect.Type, n parse.Node) reflect.Value {
- s.at(n)
- if n, ok := n.(*parse.NumberNode); ok && n.IsUint {
- value := reflect.New(typ).Elem()
- value.SetUint(n.Uint64)
- return value
- }
- s.errorf("expected unsigned integer; found %s", n)
- panic("not reached")
-}
-
-func (s *state) evalFloat(typ reflect.Type, n parse.Node) reflect.Value {
- s.at(n)
- if n, ok := n.(*parse.NumberNode); ok && n.IsFloat {
- value := reflect.New(typ).Elem()
- value.SetFloat(n.Float64)
- return value
- }
- s.errorf("expected float; found %s", n)
- panic("not reached")
-}
-
-func (s *state) evalComplex(typ reflect.Type, n parse.Node) reflect.Value {
- if n, ok := n.(*parse.NumberNode); ok && n.IsComplex {
- value := reflect.New(typ).Elem()
- value.SetComplex(n.Complex128)
- return value
- }
- s.errorf("expected complex; found %s", n)
- panic("not reached")
-}
-
-func (s *state) evalEmptyInterface(dot reflect.Value, n parse.Node) reflect.Value {
- s.at(n)
- switch n := n.(type) {
- case *parse.BoolNode:
- return reflect.ValueOf(n.True)
- case *parse.DotNode:
- return dot
- case *parse.FieldNode:
- return s.evalFieldNode(dot, n, nil, zero)
- case *parse.IdentifierNode:
- return s.evalFunction(dot, n, n, nil, zero)
- case *parse.NilNode:
- // NilNode is handled in evalArg, the only place that calls here.
- s.errorf("evalEmptyInterface: nil (can't happen)")
- case *parse.NumberNode:
- return s.idealConstant(n)
- case *parse.StringNode:
- return reflect.ValueOf(n.Text)
- case *parse.VariableNode:
- return s.evalVariableNode(dot, n, nil, zero)
- case *parse.PipeNode:
- return s.evalPipeline(dot, n)
- }
- s.errorf("can't handle assignment of %s to empty interface argument", n)
- panic("not reached")
-}
-
-// indirect returns the item at the end of indirection, and a bool to indicate if it's nil.
-// We indirect through pointers and empty interfaces (only) because
-// non-empty interfaces have methods we might need.
-func indirect(v reflect.Value) (rv reflect.Value, isNil bool) {
- for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() {
- if v.IsNil() {
- return v, true
- }
- if v.Kind() == reflect.Interface && v.NumMethod() > 0 {
- break
- }
- }
- return v, false
-}
-
-// printValue writes the textual representation of the value to the output of
-// the template.
-func (s *state) printValue(n parse.Node, v reflect.Value) {
- s.at(n)
- iface, ok := printableValue(v)
- if !ok {
- s.errorf("can't print %s of type %s", n, v.Type())
- }
- fmt.Fprint(s.wr, iface)
-}
-
-// printableValue returns the, possibly indirected, interface value inside v that
-// is best for a call to formatted printer.
-func printableValue(v reflect.Value) (interface{}, bool) {
- if v.Kind() == reflect.Ptr {
- v, _ = indirect(v) // fmt.Fprint handles nil.
- }
- if !v.IsValid() {
- return "", true
- }
-
- if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) {
- if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) {
- v = v.Addr()
- } else {
- switch v.Kind() {
- case reflect.Chan, reflect.Func:
- return nil, false
- }
- }
- }
- return v.Interface(), true
-}
-
-// Types to help sort the keys in a map for reproducible output.
-
-type rvs []reflect.Value
-
-func (x rvs) Len() int { return len(x) }
-func (x rvs) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
-
-type rvInts struct{ rvs }
-
-func (x rvInts) Less(i, j int) bool { return x.rvs[i].Int() < x.rvs[j].Int() }
-
-type rvUints struct{ rvs }
-
-func (x rvUints) Less(i, j int) bool { return x.rvs[i].Uint() < x.rvs[j].Uint() }
-
-type rvFloats struct{ rvs }
-
-func (x rvFloats) Less(i, j int) bool { return x.rvs[i].Float() < x.rvs[j].Float() }
-
-type rvStrings struct{ rvs }
-
-func (x rvStrings) Less(i, j int) bool { return x.rvs[i].String() < x.rvs[j].String() }
-
-// sortKeys sorts (if it can) the slice of reflect.Values, which is a slice of map keys.
-func sortKeys(v []reflect.Value) []reflect.Value {
- if len(v) <= 1 {
- return v
- }
- switch v[0].Kind() {
- case reflect.Float32, reflect.Float64:
- sort.Sort(rvFloats{v})
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- sort.Sort(rvInts{v})
- case reflect.String:
- sort.Sort(rvStrings{v})
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- sort.Sort(rvUints{v})
- }
- return v
-}
diff --git a/vendor/github.com/alecthomas/template/funcs.go b/vendor/github.com/alecthomas/template/funcs.go
deleted file mode 100644
index 39ee5ed..0000000
--- a/vendor/github.com/alecthomas/template/funcs.go
+++ /dev/null
@@ -1,598 +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 template
-
-import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "net/url"
- "reflect"
- "strings"
- "unicode"
- "unicode/utf8"
-)
-
-// FuncMap is the type of the map defining the mapping from names to functions.
-// Each function must have either a single return value, or two return values of
-// which the second has type error. In that case, if the second (error)
-// return value evaluates to non-nil during execution, execution terminates and
-// Execute returns that error.
-type FuncMap map[string]interface{}
-
-var builtins = FuncMap{
- "and": and,
- "call": call,
- "html": HTMLEscaper,
- "index": index,
- "js": JSEscaper,
- "len": length,
- "not": not,
- "or": or,
- "print": fmt.Sprint,
- "printf": fmt.Sprintf,
- "println": fmt.Sprintln,
- "urlquery": URLQueryEscaper,
-
- // Comparisons
- "eq": eq, // ==
- "ge": ge, // >=
- "gt": gt, // >
- "le": le, // <=
- "lt": lt, // <
- "ne": ne, // !=
-}
-
-var builtinFuncs = createValueFuncs(builtins)
-
-// createValueFuncs turns a FuncMap into a map[string]reflect.Value
-func createValueFuncs(funcMap FuncMap) map[string]reflect.Value {
- m := make(map[string]reflect.Value)
- addValueFuncs(m, funcMap)
- return m
-}
-
-// addValueFuncs adds to values the functions in funcs, converting them to reflect.Values.
-func addValueFuncs(out map[string]reflect.Value, in FuncMap) {
- for name, fn := range in {
- v := reflect.ValueOf(fn)
- if v.Kind() != reflect.Func {
- panic("value for " + name + " not a function")
- }
- if !goodFunc(v.Type()) {
- panic(fmt.Errorf("can't install method/function %q with %d results", name, v.Type().NumOut()))
- }
- out[name] = v
- }
-}
-
-// addFuncs adds to values the functions in funcs. It does no checking of the input -
-// call addValueFuncs first.
-func addFuncs(out, in FuncMap) {
- for name, fn := range in {
- out[name] = fn
- }
-}
-
-// goodFunc checks that the function or method has the right result signature.
-func goodFunc(typ reflect.Type) bool {
- // We allow functions with 1 result or 2 results where the second is an error.
- switch {
- case typ.NumOut() == 1:
- return true
- case typ.NumOut() == 2 && typ.Out(1) == errorType:
- return true
- }
- return false
-}
-
-// findFunction looks for a function in the template, and global map.
-func findFunction(name string, tmpl *Template) (reflect.Value, bool) {
- if tmpl != nil && tmpl.common != nil {
- if fn := tmpl.execFuncs[name]; fn.IsValid() {
- return fn, true
- }
- }
- if fn := builtinFuncs[name]; fn.IsValid() {
- return fn, true
- }
- return reflect.Value{}, false
-}
-
-// Indexing.
-
-// index returns the result of indexing its first argument by the following
-// arguments. Thus "index x 1 2 3" is, in Go syntax, x[1][2][3]. Each
-// indexed item must be a map, slice, or array.
-func index(item interface{}, indices ...interface{}) (interface{}, error) {
- v := reflect.ValueOf(item)
- for _, i := range indices {
- index := reflect.ValueOf(i)
- var isNil bool
- if v, isNil = indirect(v); isNil {
- return nil, fmt.Errorf("index of nil pointer")
- }
- switch v.Kind() {
- case reflect.Array, reflect.Slice, reflect.String:
- var x int64
- switch index.Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- x = index.Int()
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- x = int64(index.Uint())
- default:
- return nil, fmt.Errorf("cannot index slice/array with type %s", index.Type())
- }
- if x < 0 || x >= int64(v.Len()) {
- return nil, fmt.Errorf("index out of range: %d", x)
- }
- v = v.Index(int(x))
- case reflect.Map:
- if !index.IsValid() {
- index = reflect.Zero(v.Type().Key())
- }
- if !index.Type().AssignableTo(v.Type().Key()) {
- return nil, fmt.Errorf("%s is not index type for %s", index.Type(), v.Type())
- }
- if x := v.MapIndex(index); x.IsValid() {
- v = x
- } else {
- v = reflect.Zero(v.Type().Elem())
- }
- default:
- return nil, fmt.Errorf("can't index item of type %s", v.Type())
- }
- }
- return v.Interface(), nil
-}
-
-// Length
-
-// length returns the length of the item, with an error if it has no defined length.
-func length(item interface{}) (int, error) {
- v, isNil := indirect(reflect.ValueOf(item))
- if isNil {
- return 0, fmt.Errorf("len of nil pointer")
- }
- switch v.Kind() {
- case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
- return v.Len(), nil
- }
- return 0, fmt.Errorf("len of type %s", v.Type())
-}
-
-// Function invocation
-
-// call returns the result of evaluating the first argument as a function.
-// The function must return 1 result, or 2 results, the second of which is an error.
-func call(fn interface{}, args ...interface{}) (interface{}, error) {
- v := reflect.ValueOf(fn)
- typ := v.Type()
- if typ.Kind() != reflect.Func {
- return nil, fmt.Errorf("non-function of type %s", typ)
- }
- if !goodFunc(typ) {
- return nil, fmt.Errorf("function called with %d args; should be 1 or 2", typ.NumOut())
- }
- numIn := typ.NumIn()
- var dddType reflect.Type
- if typ.IsVariadic() {
- if len(args) < numIn-1 {
- return nil, fmt.Errorf("wrong number of args: got %d want at least %d", len(args), numIn-1)
- }
- dddType = typ.In(numIn - 1).Elem()
- } else {
- if len(args) != numIn {
- return nil, fmt.Errorf("wrong number of args: got %d want %d", len(args), numIn)
- }
- }
- argv := make([]reflect.Value, len(args))
- for i, arg := range args {
- value := reflect.ValueOf(arg)
- // Compute the expected type. Clumsy because of variadics.
- var argType reflect.Type
- if !typ.IsVariadic() || i < numIn-1 {
- argType = typ.In(i)
- } else {
- argType = dddType
- }
- if !value.IsValid() && canBeNil(argType) {
- value = reflect.Zero(argType)
- }
- if !value.Type().AssignableTo(argType) {
- return nil, fmt.Errorf("arg %d has type %s; should be %s", i, value.Type(), argType)
- }
- argv[i] = value
- }
- result := v.Call(argv)
- if len(result) == 2 && !result[1].IsNil() {
- return result[0].Interface(), result[1].Interface().(error)
- }
- return result[0].Interface(), nil
-}
-
-// Boolean logic.
-
-func truth(a interface{}) bool {
- t, _ := isTrue(reflect.ValueOf(a))
- return t
-}
-
-// and computes the Boolean AND of its arguments, returning
-// the first false argument it encounters, or the last argument.
-func and(arg0 interface{}, args ...interface{}) interface{} {
- if !truth(arg0) {
- return arg0
- }
- for i := range args {
- arg0 = args[i]
- if !truth(arg0) {
- break
- }
- }
- return arg0
-}
-
-// or computes the Boolean OR of its arguments, returning
-// the first true argument it encounters, or the last argument.
-func or(arg0 interface{}, args ...interface{}) interface{} {
- if truth(arg0) {
- return arg0
- }
- for i := range args {
- arg0 = args[i]
- if truth(arg0) {
- break
- }
- }
- return arg0
-}
-
-// not returns the Boolean negation of its argument.
-func not(arg interface{}) (truth bool) {
- truth, _ = isTrue(reflect.ValueOf(arg))
- return !truth
-}
-
-// Comparison.
-
-// TODO: Perhaps allow comparison between signed and unsigned integers.
-
-var (
- errBadComparisonType = errors.New("invalid type for comparison")
- errBadComparison = errors.New("incompatible types for comparison")
- errNoComparison = errors.New("missing argument for comparison")
-)
-
-type kind int
-
-const (
- invalidKind kind = iota
- boolKind
- complexKind
- intKind
- floatKind
- integerKind
- stringKind
- uintKind
-)
-
-func basicKind(v reflect.Value) (kind, error) {
- switch v.Kind() {
- case reflect.Bool:
- return boolKind, nil
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return intKind, nil
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
- return uintKind, nil
- case reflect.Float32, reflect.Float64:
- return floatKind, nil
- case reflect.Complex64, reflect.Complex128:
- return complexKind, nil
- case reflect.String:
- return stringKind, nil
- }
- return invalidKind, errBadComparisonType
-}
-
-// eq evaluates the comparison a == b || a == c || ...
-func eq(arg1 interface{}, arg2 ...interface{}) (bool, error) {
- v1 := reflect.ValueOf(arg1)
- k1, err := basicKind(v1)
- if err != nil {
- return false, err
- }
- if len(arg2) == 0 {
- return false, errNoComparison
- }
- for _, arg := range arg2 {
- v2 := reflect.ValueOf(arg)
- k2, err := basicKind(v2)
- if err != nil {
- return false, err
- }
- truth := false
- if k1 != k2 {
- // Special case: Can compare integer values regardless of type's sign.
- switch {
- case k1 == intKind && k2 == uintKind:
- truth = v1.Int() >= 0 && uint64(v1.Int()) == v2.Uint()
- case k1 == uintKind && k2 == intKind:
- truth = v2.Int() >= 0 && v1.Uint() == uint64(v2.Int())
- default:
- return false, errBadComparison
- }
- } else {
- switch k1 {
- case boolKind:
- truth = v1.Bool() == v2.Bool()
- case complexKind:
- truth = v1.Complex() == v2.Complex()
- case floatKind:
- truth = v1.Float() == v2.Float()
- case intKind:
- truth = v1.Int() == v2.Int()
- case stringKind:
- truth = v1.String() == v2.String()
- case uintKind:
- truth = v1.Uint() == v2.Uint()
- default:
- panic("invalid kind")
- }
- }
- if truth {
- return true, nil
- }
- }
- return false, nil
-}
-
-// ne evaluates the comparison a != b.
-func ne(arg1, arg2 interface{}) (bool, error) {
- // != is the inverse of ==.
- equal, err := eq(arg1, arg2)
- return !equal, err
-}
-
-// lt evaluates the comparison a < b.
-func lt(arg1, arg2 interface{}) (bool, error) {
- v1 := reflect.ValueOf(arg1)
- k1, err := basicKind(v1)
- if err != nil {
- return false, err
- }
- v2 := reflect.ValueOf(arg2)
- k2, err := basicKind(v2)
- if err != nil {
- return false, err
- }
- truth := false
- if k1 != k2 {
- // Special case: Can compare integer values regardless of type's sign.
- switch {
- case k1 == intKind && k2 == uintKind:
- truth = v1.Int() < 0 || uint64(v1.Int()) < v2.Uint()
- case k1 == uintKind && k2 == intKind:
- truth = v2.Int() >= 0 && v1.Uint() < uint64(v2.Int())
- default:
- return false, errBadComparison
- }
- } else {
- switch k1 {
- case boolKind, complexKind:
- return false, errBadComparisonType
- case floatKind:
- truth = v1.Float() < v2.Float()
- case intKind:
- truth = v1.Int() < v2.Int()
- case stringKind:
- truth = v1.String() < v2.String()
- case uintKind:
- truth = v1.Uint() < v2.Uint()
- default:
- panic("invalid kind")
- }
- }
- return truth, nil
-}
-
-// le evaluates the comparison <= b.
-func le(arg1, arg2 interface{}) (bool, error) {
- // <= is < or ==.
- lessThan, err := lt(arg1, arg2)
- if lessThan || err != nil {
- return lessThan, err
- }
- return eq(arg1, arg2)
-}
-
-// gt evaluates the comparison a > b.
-func gt(arg1, arg2 interface{}) (bool, error) {
- // > is the inverse of <=.
- lessOrEqual, err := le(arg1, arg2)
- if err != nil {
- return false, err
- }
- return !lessOrEqual, nil
-}
-
-// ge evaluates the comparison a >= b.
-func ge(arg1, arg2 interface{}) (bool, error) {
- // >= is the inverse of <.
- lessThan, err := lt(arg1, arg2)
- if err != nil {
- return false, err
- }
- return !lessThan, nil
-}
-
-// HTML escaping.
-
-var (
- htmlQuot = []byte(""") // shorter than """
- htmlApos = []byte("'") // shorter than "'" and apos was not in HTML until HTML5
- htmlAmp = []byte("&")
- htmlLt = []byte("<")
- htmlGt = []byte(">")
-)
-
-// HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
-func HTMLEscape(w io.Writer, b []byte) {
- last := 0
- for i, c := range b {
- var html []byte
- switch c {
- case '"':
- html = htmlQuot
- case '\'':
- html = htmlApos
- case '&':
- html = htmlAmp
- case '<':
- html = htmlLt
- case '>':
- html = htmlGt
- default:
- continue
- }
- w.Write(b[last:i])
- w.Write(html)
- last = i + 1
- }
- w.Write(b[last:])
-}
-
-// HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
-func HTMLEscapeString(s string) string {
- // Avoid allocation if we can.
- if strings.IndexAny(s, `'"&<>`) < 0 {
- return s
- }
- var b bytes.Buffer
- HTMLEscape(&b, []byte(s))
- return b.String()
-}
-
-// HTMLEscaper returns the escaped HTML equivalent of the textual
-// representation of its arguments.
-func HTMLEscaper(args ...interface{}) string {
- return HTMLEscapeString(evalArgs(args))
-}
-
-// JavaScript escaping.
-
-var (
- jsLowUni = []byte(`\u00`)
- hex = []byte("0123456789ABCDEF")
-
- jsBackslash = []byte(`\\`)
- jsApos = []byte(`\'`)
- jsQuot = []byte(`\"`)
- jsLt = []byte(`\x3C`)
- jsGt = []byte(`\x3E`)
-)
-
-// JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
-func JSEscape(w io.Writer, b []byte) {
- last := 0
- for i := 0; i < len(b); i++ {
- c := b[i]
-
- if !jsIsSpecial(rune(c)) {
- // fast path: nothing to do
- continue
- }
- w.Write(b[last:i])
-
- if c < utf8.RuneSelf {
- // Quotes, slashes and angle brackets get quoted.
- // Control characters get written as \u00XX.
- switch c {
- case '\\':
- w.Write(jsBackslash)
- case '\'':
- w.Write(jsApos)
- case '"':
- w.Write(jsQuot)
- case '<':
- w.Write(jsLt)
- case '>':
- w.Write(jsGt)
- default:
- w.Write(jsLowUni)
- t, b := c>>4, c&0x0f
- w.Write(hex[t : t+1])
- w.Write(hex[b : b+1])
- }
- } else {
- // Unicode rune.
- r, size := utf8.DecodeRune(b[i:])
- if unicode.IsPrint(r) {
- w.Write(b[i : i+size])
- } else {
- fmt.Fprintf(w, "\\u%04X", r)
- }
- i += size - 1
- }
- last = i + 1
- }
- w.Write(b[last:])
-}
-
-// JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
-func JSEscapeString(s string) string {
- // Avoid allocation if we can.
- if strings.IndexFunc(s, jsIsSpecial) < 0 {
- return s
- }
- var b bytes.Buffer
- JSEscape(&b, []byte(s))
- return b.String()
-}
-
-func jsIsSpecial(r rune) bool {
- switch r {
- case '\\', '\'', '"', '<', '>':
- return true
- }
- return r < ' ' || utf8.RuneSelf <= r
-}
-
-// JSEscaper returns the escaped JavaScript equivalent of the textual
-// representation of its arguments.
-func JSEscaper(args ...interface{}) string {
- return JSEscapeString(evalArgs(args))
-}
-
-// URLQueryEscaper returns the escaped value of the textual representation of
-// its arguments in a form suitable for embedding in a URL query.
-func URLQueryEscaper(args ...interface{}) string {
- return url.QueryEscape(evalArgs(args))
-}
-
-// evalArgs formats the list of arguments into a string. It is therefore equivalent to
-// fmt.Sprint(args...)
-// except that each argument is indirected (if a pointer), as required,
-// using the same rules as the default string evaluation during template
-// execution.
-func evalArgs(args []interface{}) string {
- ok := false
- var s string
- // Fast path for simple common case.
- if len(args) == 1 {
- s, ok = args[0].(string)
- }
- if !ok {
- for i, arg := range args {
- a, ok := printableValue(reflect.ValueOf(arg))
- if ok {
- args[i] = a
- } // else left fmt do its thing
- }
- s = fmt.Sprint(args...)
- }
- return s
-}
diff --git a/vendor/github.com/alecthomas/template/helper.go b/vendor/github.com/alecthomas/template/helper.go
deleted file mode 100644
index 3636fb5..0000000
--- a/vendor/github.com/alecthomas/template/helper.go
+++ /dev/null
@@ -1,108 +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.
-
-// Helper functions to make constructing templates easier.
-
-package template
-
-import (
- "fmt"
- "io/ioutil"
- "path/filepath"
-)
-
-// Functions and methods to parse templates.
-
-// Must is a helper that wraps a call to a function returning (*Template, error)
-// and panics if the error is non-nil. It is intended for use in variable
-// initializations such as
-// var t = template.Must(template.New("name").Parse("text"))
-func Must(t *Template, err error) *Template {
- if err != nil {
- panic(err)
- }
- return t
-}
-
-// ParseFiles creates a new Template and parses the template definitions from
-// the named files. The returned template's name will have the (base) name and
-// (parsed) contents of the first file. There must be at least one file.
-// If an error occurs, parsing stops and the returned *Template is nil.
-func ParseFiles(filenames ...string) (*Template, error) {
- return parseFiles(nil, filenames...)
-}
-
-// ParseFiles parses the named files and associates the resulting templates with
-// t. If an error occurs, parsing stops and the returned template is nil;
-// otherwise it is t. There must be at least one file.
-func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
- return parseFiles(t, filenames...)
-}
-
-// parseFiles is the helper for the method and function. If the argument
-// template is nil, it is created from the first file.
-func parseFiles(t *Template, filenames ...string) (*Template, error) {
- if len(filenames) == 0 {
- // Not really a problem, but be consistent.
- return nil, fmt.Errorf("template: no files named in call to ParseFiles")
- }
- for _, filename := range filenames {
- b, err := ioutil.ReadFile(filename)
- if err != nil {
- return nil, err
- }
- s := string(b)
- name := filepath.Base(filename)
- // First template becomes return value if not already defined,
- // and we use that one for subsequent New calls to associate
- // all the templates together. Also, if this file has the same name
- // as t, this file becomes the contents of t, so
- // t, err := New(name).Funcs(xxx).ParseFiles(name)
- // works. Otherwise we create a new template associated with t.
- var tmpl *Template
- if t == nil {
- t = New(name)
- }
- if name == t.Name() {
- tmpl = t
- } else {
- tmpl = t.New(name)
- }
- _, err = tmpl.Parse(s)
- if err != nil {
- return nil, err
- }
- }
- return t, nil
-}
-
-// ParseGlob creates a new Template and parses the template definitions from the
-// files identified by the pattern, which must match at least one file. The
-// returned template will have the (base) name and (parsed) contents of the
-// first file matched by the pattern. ParseGlob is equivalent to calling
-// ParseFiles with the list of files matched by the pattern.
-func ParseGlob(pattern string) (*Template, error) {
- return parseGlob(nil, pattern)
-}
-
-// ParseGlob parses the template definitions in the files identified by the
-// pattern and associates the resulting templates with t. The pattern is
-// processed by filepath.Glob and must match at least one file. ParseGlob is
-// equivalent to calling t.ParseFiles with the list of files matched by the
-// pattern.
-func (t *Template) ParseGlob(pattern string) (*Template, error) {
- return parseGlob(t, pattern)
-}
-
-// parseGlob is the implementation of the function and method ParseGlob.
-func parseGlob(t *Template, pattern string) (*Template, error) {
- filenames, err := filepath.Glob(pattern)
- if err != nil {
- return nil, err
- }
- if len(filenames) == 0 {
- return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern)
- }
- return parseFiles(t, filenames...)
-}
diff --git a/vendor/github.com/alecthomas/template/parse/lex.go b/vendor/github.com/alecthomas/template/parse/lex.go
deleted file mode 100644
index 55f1c05..0000000
--- a/vendor/github.com/alecthomas/template/parse/lex.go
+++ /dev/null
@@ -1,556 +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 parse
-
-import (
- "fmt"
- "strings"
- "unicode"
- "unicode/utf8"
-)
-
-// item represents a token or text string returned from the scanner.
-type item struct {
- typ itemType // The type of this item.
- pos Pos // The starting position, in bytes, of this item in the input string.
- val string // The value of this item.
-}
-
-func (i item) String() string {
- switch {
- case i.typ == itemEOF:
- return "EOF"
- case i.typ == itemError:
- return i.val
- case i.typ > itemKeyword:
- return fmt.Sprintf("<%s>", i.val)
- case len(i.val) > 10:
- return fmt.Sprintf("%.10q...", i.val)
- }
- return fmt.Sprintf("%q", i.val)
-}
-
-// itemType identifies the type of lex items.
-type itemType int
-
-const (
- itemError itemType = iota // error occurred; value is text of error
- itemBool // boolean constant
- itemChar // printable ASCII character; grab bag for comma etc.
- itemCharConstant // character constant
- itemComplex // complex constant (1+2i); imaginary is just a number
- itemColonEquals // colon-equals (':=') introducing a declaration
- itemEOF
- itemField // alphanumeric identifier starting with '.'
- itemIdentifier // alphanumeric identifier not starting with '.'
- itemLeftDelim // left action delimiter
- itemLeftParen // '(' inside action
- itemNumber // simple number, including imaginary
- itemPipe // pipe symbol
- itemRawString // raw quoted string (includes quotes)
- itemRightDelim // right action delimiter
- itemElideNewline // elide newline after right delim
- itemRightParen // ')' inside action
- itemSpace // run of spaces separating arguments
- itemString // quoted string (includes quotes)
- itemText // plain text
- itemVariable // variable starting with '$', such as '$' or '$1' or '$hello'
- // Keywords appear after all the rest.
- itemKeyword // used only to delimit the keywords
- itemDot // the cursor, spelled '.'
- itemDefine // define keyword
- itemElse // else keyword
- itemEnd // end keyword
- itemIf // if keyword
- itemNil // the untyped nil constant, easiest to treat as a keyword
- itemRange // range keyword
- itemTemplate // template keyword
- itemWith // with keyword
-)
-
-var key = map[string]itemType{
- ".": itemDot,
- "define": itemDefine,
- "else": itemElse,
- "end": itemEnd,
- "if": itemIf,
- "range": itemRange,
- "nil": itemNil,
- "template": itemTemplate,
- "with": itemWith,
-}
-
-const eof = -1
-
-// stateFn represents the state of the scanner as a function that returns the next state.
-type stateFn func(*lexer) stateFn
-
-// lexer holds the state of the scanner.
-type lexer struct {
- name string // the name of the input; used only for error reports
- input string // the string being scanned
- leftDelim string // start of action
- rightDelim string // end of action
- state stateFn // the next lexing function to enter
- pos Pos // current position in the input
- start Pos // start position of this item
- width Pos // width of last rune read from input
- lastPos Pos // position of most recent item returned by nextItem
- items chan item // channel of scanned items
- parenDepth int // nesting depth of ( ) exprs
-}
-
-// next returns the next rune in the input.
-func (l *lexer) next() rune {
- if int(l.pos) >= len(l.input) {
- l.width = 0
- return eof
- }
- r, w := utf8.DecodeRuneInString(l.input[l.pos:])
- l.width = Pos(w)
- l.pos += l.width
- return r
-}
-
-// peek returns but does not consume the next rune in the input.
-func (l *lexer) peek() rune {
- r := l.next()
- l.backup()
- return r
-}
-
-// backup steps back one rune. Can only be called once per call of next.
-func (l *lexer) backup() {
- l.pos -= l.width
-}
-
-// emit passes an item back to the client.
-func (l *lexer) emit(t itemType) {
- l.items <- item{t, l.start, l.input[l.start:l.pos]}
- l.start = l.pos
-}
-
-// ignore skips over the pending input before this point.
-func (l *lexer) ignore() {
- l.start = l.pos
-}
-
-// accept consumes the next rune if it's from the valid set.
-func (l *lexer) accept(valid string) bool {
- if strings.IndexRune(valid, l.next()) >= 0 {
- return true
- }
- l.backup()
- return false
-}
-
-// acceptRun consumes a run of runes from the valid set.
-func (l *lexer) acceptRun(valid string) {
- for strings.IndexRune(valid, l.next()) >= 0 {
- }
- l.backup()
-}
-
-// lineNumber reports which line we're on, based on the position of
-// the previous item returned by nextItem. Doing it this way
-// means we don't have to worry about peek double counting.
-func (l *lexer) lineNumber() int {
- return 1 + strings.Count(l.input[:l.lastPos], "\n")
-}
-
-// errorf returns an error token and terminates the scan by passing
-// back a nil pointer that will be the next state, terminating l.nextItem.
-func (l *lexer) errorf(format string, args ...interface{}) stateFn {
- l.items <- item{itemError, l.start, fmt.Sprintf(format, args...)}
- return nil
-}
-
-// nextItem returns the next item from the input.
-func (l *lexer) nextItem() item {
- item := <-l.items
- l.lastPos = item.pos
- return item
-}
-
-// lex creates a new scanner for the input string.
-func lex(name, input, left, right string) *lexer {
- if left == "" {
- left = leftDelim
- }
- if right == "" {
- right = rightDelim
- }
- l := &lexer{
- name: name,
- input: input,
- leftDelim: left,
- rightDelim: right,
- items: make(chan item),
- }
- go l.run()
- return l
-}
-
-// run runs the state machine for the lexer.
-func (l *lexer) run() {
- for l.state = lexText; l.state != nil; {
- l.state = l.state(l)
- }
-}
-
-// state functions
-
-const (
- leftDelim = "{{"
- rightDelim = "}}"
- leftComment = "/*"
- rightComment = "*/"
-)
-
-// lexText scans until an opening action delimiter, "{{".
-func lexText(l *lexer) stateFn {
- for {
- if strings.HasPrefix(l.input[l.pos:], l.leftDelim) {
- if l.pos > l.start {
- l.emit(itemText)
- }
- return lexLeftDelim
- }
- if l.next() == eof {
- break
- }
- }
- // Correctly reached EOF.
- if l.pos > l.start {
- l.emit(itemText)
- }
- l.emit(itemEOF)
- return nil
-}
-
-// lexLeftDelim scans the left delimiter, which is known to be present.
-func lexLeftDelim(l *lexer) stateFn {
- l.pos += Pos(len(l.leftDelim))
- if strings.HasPrefix(l.input[l.pos:], leftComment) {
- return lexComment
- }
- l.emit(itemLeftDelim)
- l.parenDepth = 0
- return lexInsideAction
-}
-
-// lexComment scans a comment. The left comment marker is known to be present.
-func lexComment(l *lexer) stateFn {
- l.pos += Pos(len(leftComment))
- i := strings.Index(l.input[l.pos:], rightComment)
- if i < 0 {
- return l.errorf("unclosed comment")
- }
- l.pos += Pos(i + len(rightComment))
- if !strings.HasPrefix(l.input[l.pos:], l.rightDelim) {
- return l.errorf("comment ends before closing delimiter")
-
- }
- l.pos += Pos(len(l.rightDelim))
- l.ignore()
- return lexText
-}
-
-// lexRightDelim scans the right delimiter, which is known to be present.
-func lexRightDelim(l *lexer) stateFn {
- l.pos += Pos(len(l.rightDelim))
- l.emit(itemRightDelim)
- if l.peek() == '\\' {
- l.pos++
- l.emit(itemElideNewline)
- }
- return lexText
-}
-
-// lexInsideAction scans the elements inside action delimiters.
-func lexInsideAction(l *lexer) stateFn {
- // Either number, quoted string, or identifier.
- // Spaces separate arguments; runs of spaces turn into itemSpace.
- // Pipe symbols separate and are emitted.
- if strings.HasPrefix(l.input[l.pos:], l.rightDelim+"\\") || strings.HasPrefix(l.input[l.pos:], l.rightDelim) {
- if l.parenDepth == 0 {
- return lexRightDelim
- }
- return l.errorf("unclosed left paren")
- }
- switch r := l.next(); {
- case r == eof || isEndOfLine(r):
- return l.errorf("unclosed action")
- case isSpace(r):
- return lexSpace
- case r == ':':
- if l.next() != '=' {
- return l.errorf("expected :=")
- }
- l.emit(itemColonEquals)
- case r == '|':
- l.emit(itemPipe)
- case r == '"':
- return lexQuote
- case r == '`':
- return lexRawQuote
- case r == '$':
- return lexVariable
- case r == '\'':
- return lexChar
- case r == '.':
- // special look-ahead for ".field" so we don't break l.backup().
- if l.pos < Pos(len(l.input)) {
- r := l.input[l.pos]
- if r < '0' || '9' < r {
- return lexField
- }
- }
- fallthrough // '.' can start a number.
- case r == '+' || r == '-' || ('0' <= r && r <= '9'):
- l.backup()
- return lexNumber
- case isAlphaNumeric(r):
- l.backup()
- return lexIdentifier
- case r == '(':
- l.emit(itemLeftParen)
- l.parenDepth++
- return lexInsideAction
- case r == ')':
- l.emit(itemRightParen)
- l.parenDepth--
- if l.parenDepth < 0 {
- return l.errorf("unexpected right paren %#U", r)
- }
- return lexInsideAction
- case r <= unicode.MaxASCII && unicode.IsPrint(r):
- l.emit(itemChar)
- return lexInsideAction
- default:
- return l.errorf("unrecognized character in action: %#U", r)
- }
- return lexInsideAction
-}
-
-// lexSpace scans a run of space characters.
-// One space has already been seen.
-func lexSpace(l *lexer) stateFn {
- for isSpace(l.peek()) {
- l.next()
- }
- l.emit(itemSpace)
- return lexInsideAction
-}
-
-// lexIdentifier scans an alphanumeric.
-func lexIdentifier(l *lexer) stateFn {
-Loop:
- for {
- switch r := l.next(); {
- case isAlphaNumeric(r):
- // absorb.
- default:
- l.backup()
- word := l.input[l.start:l.pos]
- if !l.atTerminator() {
- return l.errorf("bad character %#U", r)
- }
- switch {
- case key[word] > itemKeyword:
- l.emit(key[word])
- case word[0] == '.':
- l.emit(itemField)
- case word == "true", word == "false":
- l.emit(itemBool)
- default:
- l.emit(itemIdentifier)
- }
- break Loop
- }
- }
- return lexInsideAction
-}
-
-// lexField scans a field: .Alphanumeric.
-// The . has been scanned.
-func lexField(l *lexer) stateFn {
- return lexFieldOrVariable(l, itemField)
-}
-
-// lexVariable scans a Variable: $Alphanumeric.
-// The $ has been scanned.
-func lexVariable(l *lexer) stateFn {
- if l.atTerminator() { // Nothing interesting follows -> "$".
- l.emit(itemVariable)
- return lexInsideAction
- }
- return lexFieldOrVariable(l, itemVariable)
-}
-
-// lexVariable scans a field or variable: [.$]Alphanumeric.
-// The . or $ has been scanned.
-func lexFieldOrVariable(l *lexer, typ itemType) stateFn {
- if l.atTerminator() { // Nothing interesting follows -> "." or "$".
- if typ == itemVariable {
- l.emit(itemVariable)
- } else {
- l.emit(itemDot)
- }
- return lexInsideAction
- }
- var r rune
- for {
- r = l.next()
- if !isAlphaNumeric(r) {
- l.backup()
- break
- }
- }
- if !l.atTerminator() {
- return l.errorf("bad character %#U", r)
- }
- l.emit(typ)
- return lexInsideAction
-}
-
-// atTerminator reports whether the input is at valid termination character to
-// appear after an identifier. Breaks .X.Y into two pieces. Also catches cases
-// like "$x+2" not being acceptable without a space, in case we decide one
-// day to implement arithmetic.
-func (l *lexer) atTerminator() bool {
- r := l.peek()
- if isSpace(r) || isEndOfLine(r) {
- return true
- }
- switch r {
- case eof, '.', ',', '|', ':', ')', '(':
- return true
- }
- // Does r start the delimiter? This can be ambiguous (with delim=="//", $x/2 will
- // succeed but should fail) but only in extremely rare cases caused by willfully
- // bad choice of delimiter.
- if rd, _ := utf8.DecodeRuneInString(l.rightDelim); rd == r {
- return true
- }
- return false
-}
-
-// lexChar scans a character constant. The initial quote is already
-// scanned. Syntax checking is done by the parser.
-func lexChar(l *lexer) stateFn {
-Loop:
- for {
- switch l.next() {
- case '\\':
- if r := l.next(); r != eof && r != '\n' {
- break
- }
- fallthrough
- case eof, '\n':
- return l.errorf("unterminated character constant")
- case '\'':
- break Loop
- }
- }
- l.emit(itemCharConstant)
- return lexInsideAction
-}
-
-// lexNumber scans a number: decimal, octal, hex, float, or imaginary. This
-// isn't a perfect number scanner - for instance it accepts "." and "0x0.2"
-// and "089" - but when it's wrong the input is invalid and the parser (via
-// strconv) will notice.
-func lexNumber(l *lexer) stateFn {
- if !l.scanNumber() {
- return l.errorf("bad number syntax: %q", l.input[l.start:l.pos])
- }
- if sign := l.peek(); sign == '+' || sign == '-' {
- // Complex: 1+2i. No spaces, must end in 'i'.
- if !l.scanNumber() || l.input[l.pos-1] != 'i' {
- return l.errorf("bad number syntax: %q", l.input[l.start:l.pos])
- }
- l.emit(itemComplex)
- } else {
- l.emit(itemNumber)
- }
- return lexInsideAction
-}
-
-func (l *lexer) scanNumber() bool {
- // Optional leading sign.
- l.accept("+-")
- // Is it hex?
- digits := "0123456789"
- if l.accept("0") && l.accept("xX") {
- digits = "0123456789abcdefABCDEF"
- }
- l.acceptRun(digits)
- if l.accept(".") {
- l.acceptRun(digits)
- }
- if l.accept("eE") {
- l.accept("+-")
- l.acceptRun("0123456789")
- }
- // Is it imaginary?
- l.accept("i")
- // Next thing mustn't be alphanumeric.
- if isAlphaNumeric(l.peek()) {
- l.next()
- return false
- }
- return true
-}
-
-// lexQuote scans a quoted string.
-func lexQuote(l *lexer) stateFn {
-Loop:
- for {
- switch l.next() {
- case '\\':
- if r := l.next(); r != eof && r != '\n' {
- break
- }
- fallthrough
- case eof, '\n':
- return l.errorf("unterminated quoted string")
- case '"':
- break Loop
- }
- }
- l.emit(itemString)
- return lexInsideAction
-}
-
-// lexRawQuote scans a raw quoted string.
-func lexRawQuote(l *lexer) stateFn {
-Loop:
- for {
- switch l.next() {
- case eof, '\n':
- return l.errorf("unterminated raw quoted string")
- case '`':
- break Loop
- }
- }
- l.emit(itemRawString)
- return lexInsideAction
-}
-
-// isSpace reports whether r is a space character.
-func isSpace(r rune) bool {
- return r == ' ' || r == '\t'
-}
-
-// isEndOfLine reports whether r is an end-of-line character.
-func isEndOfLine(r rune) bool {
- return r == '\r' || r == '\n'
-}
-
-// isAlphaNumeric reports whether r is an alphabetic, digit, or underscore.
-func isAlphaNumeric(r rune) bool {
- return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
-}
diff --git a/vendor/github.com/alecthomas/template/parse/node.go b/vendor/github.com/alecthomas/template/parse/node.go
deleted file mode 100644
index 55c37f6..0000000
--- a/vendor/github.com/alecthomas/template/parse/node.go
+++ /dev/null
@@ -1,834 +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.
-
-// Parse nodes.
-
-package parse
-
-import (
- "bytes"
- "fmt"
- "strconv"
- "strings"
-)
-
-var textFormat = "%s" // Changed to "%q" in tests for better error messages.
-
-// A Node is an element in the parse tree. The interface is trivial.
-// The interface contains an unexported method so that only
-// types local to this package can satisfy it.
-type Node interface {
- Type() NodeType
- String() string
- // Copy does a deep copy of the Node and all its components.
- // To avoid type assertions, some XxxNodes also have specialized
- // CopyXxx methods that return *XxxNode.
- Copy() Node
- Position() Pos // byte position of start of node in full original input string
- // tree returns the containing *Tree.
- // It is unexported so all implementations of Node are in this package.
- tree() *Tree
-}
-
-// NodeType identifies the type of a parse tree node.
-type NodeType int
-
-// Pos represents a byte position in the original input text from which
-// this template was parsed.
-type Pos int
-
-func (p Pos) Position() Pos {
- return p
-}
-
-// Type returns itself and provides an easy default implementation
-// for embedding in a Node. Embedded in all non-trivial Nodes.
-func (t NodeType) Type() NodeType {
- return t
-}
-
-const (
- NodeText NodeType = iota // Plain text.
- NodeAction // A non-control action such as a field evaluation.
- NodeBool // A boolean constant.
- NodeChain // A sequence of field accesses.
- NodeCommand // An element of a pipeline.
- NodeDot // The cursor, dot.
- nodeElse // An else action. Not added to tree.
- nodeEnd // An end action. Not added to tree.
- NodeField // A field or method name.
- NodeIdentifier // An identifier; always a function name.
- NodeIf // An if action.
- NodeList // A list of Nodes.
- NodeNil // An untyped nil constant.
- NodeNumber // A numerical constant.
- NodePipe // A pipeline of commands.
- NodeRange // A range action.
- NodeString // A string constant.
- NodeTemplate // A template invocation action.
- NodeVariable // A $ variable.
- NodeWith // A with action.
-)
-
-// Nodes.
-
-// ListNode holds a sequence of nodes.
-type ListNode struct {
- NodeType
- Pos
- tr *Tree
- Nodes []Node // The element nodes in lexical order.
-}
-
-func (t *Tree) newList(pos Pos) *ListNode {
- return &ListNode{tr: t, NodeType: NodeList, Pos: pos}
-}
-
-func (l *ListNode) append(n Node) {
- l.Nodes = append(l.Nodes, n)
-}
-
-func (l *ListNode) tree() *Tree {
- return l.tr
-}
-
-func (l *ListNode) String() string {
- b := new(bytes.Buffer)
- for _, n := range l.Nodes {
- fmt.Fprint(b, n)
- }
- return b.String()
-}
-
-func (l *ListNode) CopyList() *ListNode {
- if l == nil {
- return l
- }
- n := l.tr.newList(l.Pos)
- for _, elem := range l.Nodes {
- n.append(elem.Copy())
- }
- return n
-}
-
-func (l *ListNode) Copy() Node {
- return l.CopyList()
-}
-
-// TextNode holds plain text.
-type TextNode struct {
- NodeType
- Pos
- tr *Tree
- Text []byte // The text; may span newlines.
-}
-
-func (t *Tree) newText(pos Pos, text string) *TextNode {
- return &TextNode{tr: t, NodeType: NodeText, Pos: pos, Text: []byte(text)}
-}
-
-func (t *TextNode) String() string {
- return fmt.Sprintf(textFormat, t.Text)
-}
-
-func (t *TextNode) tree() *Tree {
- return t.tr
-}
-
-func (t *TextNode) Copy() Node {
- return &TextNode{tr: t.tr, NodeType: NodeText, Pos: t.Pos, Text: append([]byte{}, t.Text...)}
-}
-
-// PipeNode holds a pipeline with optional declaration
-type PipeNode struct {
- NodeType
- Pos
- tr *Tree
- Line int // The line number in the input (deprecated; kept for compatibility)
- Decl []*VariableNode // Variable declarations in lexical order.
- Cmds []*CommandNode // The commands in lexical order.
-}
-
-func (t *Tree) newPipeline(pos Pos, line int, decl []*VariableNode) *PipeNode {
- return &PipeNode{tr: t, NodeType: NodePipe, Pos: pos, Line: line, Decl: decl}
-}
-
-func (p *PipeNode) append(command *CommandNode) {
- p.Cmds = append(p.Cmds, command)
-}
-
-func (p *PipeNode) String() string {
- s := ""
- if len(p.Decl) > 0 {
- for i, v := range p.Decl {
- if i > 0 {
- s += ", "
- }
- s += v.String()
- }
- s += " := "
- }
- for i, c := range p.Cmds {
- if i > 0 {
- s += " | "
- }
- s += c.String()
- }
- return s
-}
-
-func (p *PipeNode) tree() *Tree {
- return p.tr
-}
-
-func (p *PipeNode) CopyPipe() *PipeNode {
- if p == nil {
- return p
- }
- var decl []*VariableNode
- for _, d := range p.Decl {
- decl = append(decl, d.Copy().(*VariableNode))
- }
- n := p.tr.newPipeline(p.Pos, p.Line, decl)
- for _, c := range p.Cmds {
- n.append(c.Copy().(*CommandNode))
- }
- return n
-}
-
-func (p *PipeNode) Copy() Node {
- return p.CopyPipe()
-}
-
-// ActionNode holds an action (something bounded by delimiters).
-// Control actions have their own nodes; ActionNode represents simple
-// ones such as field evaluations and parenthesized pipelines.
-type ActionNode struct {
- NodeType
- Pos
- tr *Tree
- Line int // The line number in the input (deprecated; kept for compatibility)
- Pipe *PipeNode // The pipeline in the action.
-}
-
-func (t *Tree) newAction(pos Pos, line int, pipe *PipeNode) *ActionNode {
- return &ActionNode{tr: t, NodeType: NodeAction, Pos: pos, Line: line, Pipe: pipe}
-}
-
-func (a *ActionNode) String() string {
- return fmt.Sprintf("{{%s}}", a.Pipe)
-
-}
-
-func (a *ActionNode) tree() *Tree {
- return a.tr
-}
-
-func (a *ActionNode) Copy() Node {
- return a.tr.newAction(a.Pos, a.Line, a.Pipe.CopyPipe())
-
-}
-
-// CommandNode holds a command (a pipeline inside an evaluating action).
-type CommandNode struct {
- NodeType
- Pos
- tr *Tree
- Args []Node // Arguments in lexical order: Identifier, field, or constant.
-}
-
-func (t *Tree) newCommand(pos Pos) *CommandNode {
- return &CommandNode{tr: t, NodeType: NodeCommand, Pos: pos}
-}
-
-func (c *CommandNode) append(arg Node) {
- c.Args = append(c.Args, arg)
-}
-
-func (c *CommandNode) String() string {
- s := ""
- for i, arg := range c.Args {
- if i > 0 {
- s += " "
- }
- if arg, ok := arg.(*PipeNode); ok {
- s += "(" + arg.String() + ")"
- continue
- }
- s += arg.String()
- }
- return s
-}
-
-func (c *CommandNode) tree() *Tree {
- return c.tr
-}
-
-func (c *CommandNode) Copy() Node {
- if c == nil {
- return c
- }
- n := c.tr.newCommand(c.Pos)
- for _, c := range c.Args {
- n.append(c.Copy())
- }
- return n
-}
-
-// IdentifierNode holds an identifier.
-type IdentifierNode struct {
- NodeType
- Pos
- tr *Tree
- Ident string // The identifier's name.
-}
-
-// NewIdentifier returns a new IdentifierNode with the given identifier name.
-func NewIdentifier(ident string) *IdentifierNode {
- return &IdentifierNode{NodeType: NodeIdentifier, Ident: ident}
-}
-
-// SetPos sets the position. NewIdentifier is a public method so we can't modify its signature.
-// Chained for convenience.
-// TODO: fix one day?
-func (i *IdentifierNode) SetPos(pos Pos) *IdentifierNode {
- i.Pos = pos
- return i
-}
-
-// SetTree sets the parent tree for the node. NewIdentifier is a public method so we can't modify its signature.
-// Chained for convenience.
-// TODO: fix one day?
-func (i *IdentifierNode) SetTree(t *Tree) *IdentifierNode {
- i.tr = t
- return i
-}
-
-func (i *IdentifierNode) String() string {
- return i.Ident
-}
-
-func (i *IdentifierNode) tree() *Tree {
- return i.tr
-}
-
-func (i *IdentifierNode) Copy() Node {
- return NewIdentifier(i.Ident).SetTree(i.tr).SetPos(i.Pos)
-}
-
-// VariableNode holds a list of variable names, possibly with chained field
-// accesses. The dollar sign is part of the (first) name.
-type VariableNode struct {
- NodeType
- Pos
- tr *Tree
- Ident []string // Variable name and fields in lexical order.
-}
-
-func (t *Tree) newVariable(pos Pos, ident string) *VariableNode {
- return &VariableNode{tr: t, NodeType: NodeVariable, Pos: pos, Ident: strings.Split(ident, ".")}
-}
-
-func (v *VariableNode) String() string {
- s := ""
- for i, id := range v.Ident {
- if i > 0 {
- s += "."
- }
- s += id
- }
- return s
-}
-
-func (v *VariableNode) tree() *Tree {
- return v.tr
-}
-
-func (v *VariableNode) Copy() Node {
- return &VariableNode{tr: v.tr, NodeType: NodeVariable, Pos: v.Pos, Ident: append([]string{}, v.Ident...)}
-}
-
-// DotNode holds the special identifier '.'.
-type DotNode struct {
- NodeType
- Pos
- tr *Tree
-}
-
-func (t *Tree) newDot(pos Pos) *DotNode {
- return &DotNode{tr: t, NodeType: NodeDot, Pos: pos}
-}
-
-func (d *DotNode) Type() NodeType {
- // Override method on embedded NodeType for API compatibility.
- // TODO: Not really a problem; could change API without effect but
- // api tool complains.
- return NodeDot
-}
-
-func (d *DotNode) String() string {
- return "."
-}
-
-func (d *DotNode) tree() *Tree {
- return d.tr
-}
-
-func (d *DotNode) Copy() Node {
- return d.tr.newDot(d.Pos)
-}
-
-// NilNode holds the special identifier 'nil' representing an untyped nil constant.
-type NilNode struct {
- NodeType
- Pos
- tr *Tree
-}
-
-func (t *Tree) newNil(pos Pos) *NilNode {
- return &NilNode{tr: t, NodeType: NodeNil, Pos: pos}
-}
-
-func (n *NilNode) Type() NodeType {
- // Override method on embedded NodeType for API compatibility.
- // TODO: Not really a problem; could change API without effect but
- // api tool complains.
- return NodeNil
-}
-
-func (n *NilNode) String() string {
- return "nil"
-}
-
-func (n *NilNode) tree() *Tree {
- return n.tr
-}
-
-func (n *NilNode) Copy() Node {
- return n.tr.newNil(n.Pos)
-}
-
-// FieldNode holds a field (identifier starting with '.').
-// The names may be chained ('.x.y').
-// The period is dropped from each ident.
-type FieldNode struct {
- NodeType
- Pos
- tr *Tree
- Ident []string // The identifiers in lexical order.
-}
-
-func (t *Tree) newField(pos Pos, ident string) *FieldNode {
- return &FieldNode{tr: t, NodeType: NodeField, Pos: pos, Ident: strings.Split(ident[1:], ".")} // [1:] to drop leading period
-}
-
-func (f *FieldNode) String() string {
- s := ""
- for _, id := range f.Ident {
- s += "." + id
- }
- return s
-}
-
-func (f *FieldNode) tree() *Tree {
- return f.tr
-}
-
-func (f *FieldNode) Copy() Node {
- return &FieldNode{tr: f.tr, NodeType: NodeField, Pos: f.Pos, Ident: append([]string{}, f.Ident...)}
-}
-
-// ChainNode holds a term followed by a chain of field accesses (identifier starting with '.').
-// The names may be chained ('.x.y').
-// The periods are dropped from each ident.
-type ChainNode struct {
- NodeType
- Pos
- tr *Tree
- Node Node
- Field []string // The identifiers in lexical order.
-}
-
-func (t *Tree) newChain(pos Pos, node Node) *ChainNode {
- return &ChainNode{tr: t, NodeType: NodeChain, Pos: pos, Node: node}
-}
-
-// Add adds the named field (which should start with a period) to the end of the chain.
-func (c *ChainNode) Add(field string) {
- if len(field) == 0 || field[0] != '.' {
- panic("no dot in field")
- }
- field = field[1:] // Remove leading dot.
- if field == "" {
- panic("empty field")
- }
- c.Field = append(c.Field, field)
-}
-
-func (c *ChainNode) String() string {
- s := c.Node.String()
- if _, ok := c.Node.(*PipeNode); ok {
- s = "(" + s + ")"
- }
- for _, field := range c.Field {
- s += "." + field
- }
- return s
-}
-
-func (c *ChainNode) tree() *Tree {
- return c.tr
-}
-
-func (c *ChainNode) Copy() Node {
- return &ChainNode{tr: c.tr, NodeType: NodeChain, Pos: c.Pos, Node: c.Node, Field: append([]string{}, c.Field...)}
-}
-
-// BoolNode holds a boolean constant.
-type BoolNode struct {
- NodeType
- Pos
- tr *Tree
- True bool // The value of the boolean constant.
-}
-
-func (t *Tree) newBool(pos Pos, true bool) *BoolNode {
- return &BoolNode{tr: t, NodeType: NodeBool, Pos: pos, True: true}
-}
-
-func (b *BoolNode) String() string {
- if b.True {
- return "true"
- }
- return "false"
-}
-
-func (b *BoolNode) tree() *Tree {
- return b.tr
-}
-
-func (b *BoolNode) Copy() Node {
- return b.tr.newBool(b.Pos, b.True)
-}
-
-// NumberNode holds a number: signed or unsigned integer, float, or complex.
-// The value is parsed and stored under all the types that can represent the value.
-// This simulates in a small amount of code the behavior of Go's ideal constants.
-type NumberNode struct {
- NodeType
- Pos
- tr *Tree
- IsInt bool // Number has an integral value.
- IsUint bool // Number has an unsigned integral value.
- IsFloat bool // Number has a floating-point value.
- IsComplex bool // Number is complex.
- Int64 int64 // The signed integer value.
- Uint64 uint64 // The unsigned integer value.
- Float64 float64 // The floating-point value.
- Complex128 complex128 // The complex value.
- Text string // The original textual representation from the input.
-}
-
-func (t *Tree) newNumber(pos Pos, text string, typ itemType) (*NumberNode, error) {
- n := &NumberNode{tr: t, NodeType: NodeNumber, Pos: pos, Text: text}
- switch typ {
- case itemCharConstant:
- rune, _, tail, err := strconv.UnquoteChar(text[1:], text[0])
- if err != nil {
- return nil, err
- }
- if tail != "'" {
- return nil, fmt.Errorf("malformed character constant: %s", text)
- }
- n.Int64 = int64(rune)
- n.IsInt = true
- n.Uint64 = uint64(rune)
- n.IsUint = true
- n.Float64 = float64(rune) // odd but those are the rules.
- n.IsFloat = true
- return n, nil
- case itemComplex:
- // fmt.Sscan can parse the pair, so let it do the work.
- if _, err := fmt.Sscan(text, &n.Complex128); err != nil {
- return nil, err
- }
- n.IsComplex = true
- n.simplifyComplex()
- return n, nil
- }
- // Imaginary constants can only be complex unless they are zero.
- if len(text) > 0 && text[len(text)-1] == 'i' {
- f, err := strconv.ParseFloat(text[:len(text)-1], 64)
- if err == nil {
- n.IsComplex = true
- n.Complex128 = complex(0, f)
- n.simplifyComplex()
- return n, nil
- }
- }
- // Do integer test first so we get 0x123 etc.
- u, err := strconv.ParseUint(text, 0, 64) // will fail for -0; fixed below.
- if err == nil {
- n.IsUint = true
- n.Uint64 = u
- }
- i, err := strconv.ParseInt(text, 0, 64)
- if err == nil {
- n.IsInt = true
- n.Int64 = i
- if i == 0 {
- n.IsUint = true // in case of -0.
- n.Uint64 = u
- }
- }
- // If an integer extraction succeeded, promote the float.
- if n.IsInt {
- n.IsFloat = true
- n.Float64 = float64(n.Int64)
- } else if n.IsUint {
- n.IsFloat = true
- n.Float64 = float64(n.Uint64)
- } else {
- f, err := strconv.ParseFloat(text, 64)
- if err == nil {
- n.IsFloat = true
- n.Float64 = f
- // If a floating-point extraction succeeded, extract the int if needed.
- if !n.IsInt && float64(int64(f)) == f {
- n.IsInt = true
- n.Int64 = int64(f)
- }
- if !n.IsUint && float64(uint64(f)) == f {
- n.IsUint = true
- n.Uint64 = uint64(f)
- }
- }
- }
- if !n.IsInt && !n.IsUint && !n.IsFloat {
- return nil, fmt.Errorf("illegal number syntax: %q", text)
- }
- return n, nil
-}
-
-// simplifyComplex pulls out any other types that are represented by the complex number.
-// These all require that the imaginary part be zero.
-func (n *NumberNode) simplifyComplex() {
- n.IsFloat = imag(n.Complex128) == 0
- if n.IsFloat {
- n.Float64 = real(n.Complex128)
- n.IsInt = float64(int64(n.Float64)) == n.Float64
- if n.IsInt {
- n.Int64 = int64(n.Float64)
- }
- n.IsUint = float64(uint64(n.Float64)) == n.Float64
- if n.IsUint {
- n.Uint64 = uint64(n.Float64)
- }
- }
-}
-
-func (n *NumberNode) String() string {
- return n.Text
-}
-
-func (n *NumberNode) tree() *Tree {
- return n.tr
-}
-
-func (n *NumberNode) Copy() Node {
- nn := new(NumberNode)
- *nn = *n // Easy, fast, correct.
- return nn
-}
-
-// StringNode holds a string constant. The value has been "unquoted".
-type StringNode struct {
- NodeType
- Pos
- tr *Tree
- Quoted string // The original text of the string, with quotes.
- Text string // The string, after quote processing.
-}
-
-func (t *Tree) newString(pos Pos, orig, text string) *StringNode {
- return &StringNode{tr: t, NodeType: NodeString, Pos: pos, Quoted: orig, Text: text}
-}
-
-func (s *StringNode) String() string {
- return s.Quoted
-}
-
-func (s *StringNode) tree() *Tree {
- return s.tr
-}
-
-func (s *StringNode) Copy() Node {
- return s.tr.newString(s.Pos, s.Quoted, s.Text)
-}
-
-// endNode represents an {{end}} action.
-// It does not appear in the final parse tree.
-type endNode struct {
- NodeType
- Pos
- tr *Tree
-}
-
-func (t *Tree) newEnd(pos Pos) *endNode {
- return &endNode{tr: t, NodeType: nodeEnd, Pos: pos}
-}
-
-func (e *endNode) String() string {
- return "{{end}}"
-}
-
-func (e *endNode) tree() *Tree {
- return e.tr
-}
-
-func (e *endNode) Copy() Node {
- return e.tr.newEnd(e.Pos)
-}
-
-// elseNode represents an {{else}} action. Does not appear in the final tree.
-type elseNode struct {
- NodeType
- Pos
- tr *Tree
- Line int // The line number in the input (deprecated; kept for compatibility)
-}
-
-func (t *Tree) newElse(pos Pos, line int) *elseNode {
- return &elseNode{tr: t, NodeType: nodeElse, Pos: pos, Line: line}
-}
-
-func (e *elseNode) Type() NodeType {
- return nodeElse
-}
-
-func (e *elseNode) String() string {
- return "{{else}}"
-}
-
-func (e *elseNode) tree() *Tree {
- return e.tr
-}
-
-func (e *elseNode) Copy() Node {
- return e.tr.newElse(e.Pos, e.Line)
-}
-
-// BranchNode is the common representation of if, range, and with.
-type BranchNode struct {
- NodeType
- Pos
- tr *Tree
- Line int // The line number in the input (deprecated; kept for compatibility)
- Pipe *PipeNode // The pipeline to be evaluated.
- List *ListNode // What to execute if the value is non-empty.
- ElseList *ListNode // What to execute if the value is empty (nil if absent).
-}
-
-func (b *BranchNode) String() string {
- name := ""
- switch b.NodeType {
- case NodeIf:
- name = "if"
- case NodeRange:
- name = "range"
- case NodeWith:
- name = "with"
- default:
- panic("unknown branch type")
- }
- if b.ElseList != nil {
- return fmt.Sprintf("{{%s %s}}%s{{else}}%s{{end}}", name, b.Pipe, b.List, b.ElseList)
- }
- return fmt.Sprintf("{{%s %s}}%s{{end}}", name, b.Pipe, b.List)
-}
-
-func (b *BranchNode) tree() *Tree {
- return b.tr
-}
-
-func (b *BranchNode) Copy() Node {
- switch b.NodeType {
- case NodeIf:
- return b.tr.newIf(b.Pos, b.Line, b.Pipe, b.List, b.ElseList)
- case NodeRange:
- return b.tr.newRange(b.Pos, b.Line, b.Pipe, b.List, b.ElseList)
- case NodeWith:
- return b.tr.newWith(b.Pos, b.Line, b.Pipe, b.List, b.ElseList)
- default:
- panic("unknown branch type")
- }
-}
-
-// IfNode represents an {{if}} action and its commands.
-type IfNode struct {
- BranchNode
-}
-
-func (t *Tree) newIf(pos Pos, line int, pipe *PipeNode, list, elseList *ListNode) *IfNode {
- return &IfNode{BranchNode{tr: t, NodeType: NodeIf, Pos: pos, Line: line, Pipe: pipe, List: list, ElseList: elseList}}
-}
-
-func (i *IfNode) Copy() Node {
- return i.tr.newIf(i.Pos, i.Line, i.Pipe.CopyPipe(), i.List.CopyList(), i.ElseList.CopyList())
-}
-
-// RangeNode represents a {{range}} action and its commands.
-type RangeNode struct {
- BranchNode
-}
-
-func (t *Tree) newRange(pos Pos, line int, pipe *PipeNode, list, elseList *ListNode) *RangeNode {
- return &RangeNode{BranchNode{tr: t, NodeType: NodeRange, Pos: pos, Line: line, Pipe: pipe, List: list, ElseList: elseList}}
-}
-
-func (r *RangeNode) Copy() Node {
- return r.tr.newRange(r.Pos, r.Line, r.Pipe.CopyPipe(), r.List.CopyList(), r.ElseList.CopyList())
-}
-
-// WithNode represents a {{with}} action and its commands.
-type WithNode struct {
- BranchNode
-}
-
-func (t *Tree) newWith(pos Pos, line int, pipe *PipeNode, list, elseList *ListNode) *WithNode {
- return &WithNode{BranchNode{tr: t, NodeType: NodeWith, Pos: pos, Line: line, Pipe: pipe, List: list, ElseList: elseList}}
-}
-
-func (w *WithNode) Copy() Node {
- return w.tr.newWith(w.Pos, w.Line, w.Pipe.CopyPipe(), w.List.CopyList(), w.ElseList.CopyList())
-}
-
-// TemplateNode represents a {{template}} action.
-type TemplateNode struct {
- NodeType
- Pos
- tr *Tree
- Line int // The line number in the input (deprecated; kept for compatibility)
- Name string // The name of the template (unquoted).
- Pipe *PipeNode // The command to evaluate as dot for the template.
-}
-
-func (t *Tree) newTemplate(pos Pos, line int, name string, pipe *PipeNode) *TemplateNode {
- return &TemplateNode{tr: t, NodeType: NodeTemplate, Pos: pos, Line: line, Name: name, Pipe: pipe}
-}
-
-func (t *TemplateNode) String() string {
- if t.Pipe == nil {
- return fmt.Sprintf("{{template %q}}", t.Name)
- }
- return fmt.Sprintf("{{template %q %s}}", t.Name, t.Pipe)
-}
-
-func (t *TemplateNode) tree() *Tree {
- return t.tr
-}
-
-func (t *TemplateNode) Copy() Node {
- return t.tr.newTemplate(t.Pos, t.Line, t.Name, t.Pipe.CopyPipe())
-}
diff --git a/vendor/github.com/alecthomas/template/parse/parse.go b/vendor/github.com/alecthomas/template/parse/parse.go
deleted file mode 100644
index 0d77ade..0000000
--- a/vendor/github.com/alecthomas/template/parse/parse.go
+++ /dev/null
@@ -1,700 +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 parse builds parse trees for templates as defined by text/template
-// and html/template. Clients should use those packages to construct templates
-// rather than this one, which provides shared internal data structures not
-// intended for general use.
-package parse
-
-import (
- "bytes"
- "fmt"
- "runtime"
- "strconv"
- "strings"
-)
-
-// Tree is the representation of a single parsed template.
-type Tree struct {
- Name string // name of the template represented by the tree.
- ParseName string // name of the top-level template during parsing, for error messages.
- Root *ListNode // top-level root of the tree.
- text string // text parsed to create the template (or its parent)
- // Parsing only; cleared after parse.
- funcs []map[string]interface{}
- lex *lexer
- token [3]item // three-token lookahead for parser.
- peekCount int
- vars []string // variables defined at the moment.
-}
-
-// Copy returns a copy of the Tree. Any parsing state is discarded.
-func (t *Tree) Copy() *Tree {
- if t == nil {
- return nil
- }
- return &Tree{
- Name: t.Name,
- ParseName: t.ParseName,
- Root: t.Root.CopyList(),
- text: t.text,
- }
-}
-
-// Parse returns a map from template name to parse.Tree, created by parsing the
-// templates described in the argument string. The top-level template will be
-// given the specified name. If an error is encountered, parsing stops and an
-// empty map is returned with the error.
-func Parse(name, text, leftDelim, rightDelim string, funcs ...map[string]interface{}) (treeSet map[string]*Tree, err error) {
- treeSet = make(map[string]*Tree)
- t := New(name)
- t.text = text
- _, err = t.Parse(text, leftDelim, rightDelim, treeSet, funcs...)
- return
-}
-
-// next returns the next token.
-func (t *Tree) next() item {
- if t.peekCount > 0 {
- t.peekCount--
- } else {
- t.token[0] = t.lex.nextItem()
- }
- return t.token[t.peekCount]
-}
-
-// backup backs the input stream up one token.
-func (t *Tree) backup() {
- t.peekCount++
-}
-
-// backup2 backs the input stream up two tokens.
-// The zeroth token is already there.
-func (t *Tree) backup2(t1 item) {
- t.token[1] = t1
- t.peekCount = 2
-}
-
-// backup3 backs the input stream up three tokens
-// The zeroth token is already there.
-func (t *Tree) backup3(t2, t1 item) { // Reverse order: we're pushing back.
- t.token[1] = t1
- t.token[2] = t2
- t.peekCount = 3
-}
-
-// peek returns but does not consume the next token.
-func (t *Tree) peek() item {
- if t.peekCount > 0 {
- return t.token[t.peekCount-1]
- }
- t.peekCount = 1
- t.token[0] = t.lex.nextItem()
- return t.token[0]
-}
-
-// nextNonSpace returns the next non-space token.
-func (t *Tree) nextNonSpace() (token item) {
- for {
- token = t.next()
- if token.typ != itemSpace {
- break
- }
- }
- return token
-}
-
-// peekNonSpace returns but does not consume the next non-space token.
-func (t *Tree) peekNonSpace() (token item) {
- for {
- token = t.next()
- if token.typ != itemSpace {
- break
- }
- }
- t.backup()
- return token
-}
-
-// Parsing.
-
-// New allocates a new parse tree with the given name.
-func New(name string, funcs ...map[string]interface{}) *Tree {
- return &Tree{
- Name: name,
- funcs: funcs,
- }
-}
-
-// ErrorContext returns a textual representation of the location of the node in the input text.
-// The receiver is only used when the node does not have a pointer to the tree inside,
-// which can occur in old code.
-func (t *Tree) ErrorContext(n Node) (location, context string) {
- pos := int(n.Position())
- tree := n.tree()
- if tree == nil {
- tree = t
- }
- text := tree.text[:pos]
- byteNum := strings.LastIndex(text, "\n")
- if byteNum == -1 {
- byteNum = pos // On first line.
- } else {
- byteNum++ // After the newline.
- byteNum = pos - byteNum
- }
- lineNum := 1 + strings.Count(text, "\n")
- context = n.String()
- if len(context) > 20 {
- context = fmt.Sprintf("%.20s...", context)
- }
- return fmt.Sprintf("%s:%d:%d", tree.ParseName, lineNum, byteNum), context
-}
-
-// errorf formats the error and terminates processing.
-func (t *Tree) errorf(format string, args ...interface{}) {
- t.Root = nil
- format = fmt.Sprintf("template: %s:%d: %s", t.ParseName, t.lex.lineNumber(), format)
- panic(fmt.Errorf(format, args...))
-}
-
-// error terminates processing.
-func (t *Tree) error(err error) {
- t.errorf("%s", err)
-}
-
-// expect consumes the next token and guarantees it has the required type.
-func (t *Tree) expect(expected itemType, context string) item {
- token := t.nextNonSpace()
- if token.typ != expected {
- t.unexpected(token, context)
- }
- return token
-}
-
-// expectOneOf consumes the next token and guarantees it has one of the required types.
-func (t *Tree) expectOneOf(expected1, expected2 itemType, context string) item {
- token := t.nextNonSpace()
- if token.typ != expected1 && token.typ != expected2 {
- t.unexpected(token, context)
- }
- return token
-}
-
-// unexpected complains about the token and terminates processing.
-func (t *Tree) unexpected(token item, context string) {
- t.errorf("unexpected %s in %s", token, context)
-}
-
-// recover is the handler that turns panics into returns from the top level of Parse.
-func (t *Tree) recover(errp *error) {
- e := recover()
- if e != nil {
- if _, ok := e.(runtime.Error); ok {
- panic(e)
- }
- if t != nil {
- t.stopParse()
- }
- *errp = e.(error)
- }
- return
-}
-
-// startParse initializes the parser, using the lexer.
-func (t *Tree) startParse(funcs []map[string]interface{}, lex *lexer) {
- t.Root = nil
- t.lex = lex
- t.vars = []string{"$"}
- t.funcs = funcs
-}
-
-// stopParse terminates parsing.
-func (t *Tree) stopParse() {
- t.lex = nil
- t.vars = nil
- t.funcs = nil
-}
-
-// Parse parses the template definition string to construct a representation of
-// the template for execution. If either action delimiter string is empty, the
-// default ("{{" or "}}") is used. Embedded template definitions are added to
-// the treeSet map.
-func (t *Tree) Parse(text, leftDelim, rightDelim string, treeSet map[string]*Tree, funcs ...map[string]interface{}) (tree *Tree, err error) {
- defer t.recover(&err)
- t.ParseName = t.Name
- t.startParse(funcs, lex(t.Name, text, leftDelim, rightDelim))
- t.text = text
- t.parse(treeSet)
- t.add(treeSet)
- t.stopParse()
- return t, nil
-}
-
-// add adds tree to the treeSet.
-func (t *Tree) add(treeSet map[string]*Tree) {
- tree := treeSet[t.Name]
- if tree == nil || IsEmptyTree(tree.Root) {
- treeSet[t.Name] = t
- return
- }
- if !IsEmptyTree(t.Root) {
- t.errorf("template: multiple definition of template %q", t.Name)
- }
-}
-
-// IsEmptyTree reports whether this tree (node) is empty of everything but space.
-func IsEmptyTree(n Node) bool {
- switch n := n.(type) {
- case nil:
- return true
- case *ActionNode:
- case *IfNode:
- case *ListNode:
- for _, node := range n.Nodes {
- if !IsEmptyTree(node) {
- return false
- }
- }
- return true
- case *RangeNode:
- case *TemplateNode:
- case *TextNode:
- return len(bytes.TrimSpace(n.Text)) == 0
- case *WithNode:
- default:
- panic("unknown node: " + n.String())
- }
- return false
-}
-
-// parse is the top-level parser for a template, essentially the same
-// as itemList except it also parses {{define}} actions.
-// It runs to EOF.
-func (t *Tree) parse(treeSet map[string]*Tree) (next Node) {
- t.Root = t.newList(t.peek().pos)
- for t.peek().typ != itemEOF {
- if t.peek().typ == itemLeftDelim {
- delim := t.next()
- if t.nextNonSpace().typ == itemDefine {
- newT := New("definition") // name will be updated once we know it.
- newT.text = t.text
- newT.ParseName = t.ParseName
- newT.startParse(t.funcs, t.lex)
- newT.parseDefinition(treeSet)
- continue
- }
- t.backup2(delim)
- }
- n := t.textOrAction()
- if n.Type() == nodeEnd {
- t.errorf("unexpected %s", n)
- }
- t.Root.append(n)
- }
- return nil
-}
-
-// parseDefinition parses a {{define}} ... {{end}} template definition and
-// installs the definition in the treeSet map. The "define" keyword has already
-// been scanned.
-func (t *Tree) parseDefinition(treeSet map[string]*Tree) {
- const context = "define clause"
- name := t.expectOneOf(itemString, itemRawString, context)
- var err error
- t.Name, err = strconv.Unquote(name.val)
- if err != nil {
- t.error(err)
- }
- t.expect(itemRightDelim, context)
- var end Node
- t.Root, end = t.itemList()
- if end.Type() != nodeEnd {
- t.errorf("unexpected %s in %s", end, context)
- }
- t.add(treeSet)
- t.stopParse()
-}
-
-// itemList:
-// textOrAction*
-// Terminates at {{end}} or {{else}}, returned separately.
-func (t *Tree) itemList() (list *ListNode, next Node) {
- list = t.newList(t.peekNonSpace().pos)
- for t.peekNonSpace().typ != itemEOF {
- n := t.textOrAction()
- switch n.Type() {
- case nodeEnd, nodeElse:
- return list, n
- }
- list.append(n)
- }
- t.errorf("unexpected EOF")
- return
-}
-
-// textOrAction:
-// text | action
-func (t *Tree) textOrAction() Node {
- switch token := t.nextNonSpace(); token.typ {
- case itemElideNewline:
- return t.elideNewline()
- case itemText:
- return t.newText(token.pos, token.val)
- case itemLeftDelim:
- return t.action()
- default:
- t.unexpected(token, "input")
- }
- return nil
-}
-
-// elideNewline:
-// Remove newlines trailing rightDelim if \\ is present.
-func (t *Tree) elideNewline() Node {
- token := t.peek()
- if token.typ != itemText {
- t.unexpected(token, "input")
- return nil
- }
-
- t.next()
- stripped := strings.TrimLeft(token.val, "\n\r")
- diff := len(token.val) - len(stripped)
- if diff > 0 {
- // This is a bit nasty. We mutate the token in-place to remove
- // preceding newlines.
- token.pos += Pos(diff)
- token.val = stripped
- }
- return t.newText(token.pos, token.val)
-}
-
-// Action:
-// control
-// command ("|" command)*
-// Left delim is past. Now get actions.
-// First word could be a keyword such as range.
-func (t *Tree) action() (n Node) {
- switch token := t.nextNonSpace(); token.typ {
- case itemElse:
- return t.elseControl()
- case itemEnd:
- return t.endControl()
- case itemIf:
- return t.ifControl()
- case itemRange:
- return t.rangeControl()
- case itemTemplate:
- return t.templateControl()
- case itemWith:
- return t.withControl()
- }
- t.backup()
- // Do not pop variables; they persist until "end".
- return t.newAction(t.peek().pos, t.lex.lineNumber(), t.pipeline("command"))
-}
-
-// Pipeline:
-// declarations? command ('|' command)*
-func (t *Tree) pipeline(context string) (pipe *PipeNode) {
- var decl []*VariableNode
- pos := t.peekNonSpace().pos
- // Are there declarations?
- for {
- if v := t.peekNonSpace(); v.typ == itemVariable {
- t.next()
- // Since space is a token, we need 3-token look-ahead here in the worst case:
- // in "$x foo" we need to read "foo" (as opposed to ":=") to know that $x is an
- // argument variable rather than a declaration. So remember the token
- // adjacent to the variable so we can push it back if necessary.
- tokenAfterVariable := t.peek()
- if next := t.peekNonSpace(); next.typ == itemColonEquals || (next.typ == itemChar && next.val == ",") {
- t.nextNonSpace()
- variable := t.newVariable(v.pos, v.val)
- decl = append(decl, variable)
- t.vars = append(t.vars, v.val)
- if next.typ == itemChar && next.val == "," {
- if context == "range" && len(decl) < 2 {
- continue
- }
- t.errorf("too many declarations in %s", context)
- }
- } else if tokenAfterVariable.typ == itemSpace {
- t.backup3(v, tokenAfterVariable)
- } else {
- t.backup2(v)
- }
- }
- break
- }
- pipe = t.newPipeline(pos, t.lex.lineNumber(), decl)
- for {
- switch token := t.nextNonSpace(); token.typ {
- case itemRightDelim, itemRightParen:
- if len(pipe.Cmds) == 0 {
- t.errorf("missing value for %s", context)
- }
- if token.typ == itemRightParen {
- t.backup()
- }
- return
- case itemBool, itemCharConstant, itemComplex, itemDot, itemField, itemIdentifier,
- itemNumber, itemNil, itemRawString, itemString, itemVariable, itemLeftParen:
- t.backup()
- pipe.append(t.command())
- default:
- t.unexpected(token, context)
- }
- }
-}
-
-func (t *Tree) parseControl(allowElseIf bool, context string) (pos Pos, line int, pipe *PipeNode, list, elseList *ListNode) {
- defer t.popVars(len(t.vars))
- line = t.lex.lineNumber()
- pipe = t.pipeline(context)
- var next Node
- list, next = t.itemList()
- switch next.Type() {
- case nodeEnd: //done
- case nodeElse:
- if allowElseIf {
- // Special case for "else if". If the "else" is followed immediately by an "if",
- // the elseControl will have left the "if" token pending. Treat
- // {{if a}}_{{else if b}}_{{end}}
- // as
- // {{if a}}_{{else}}{{if b}}_{{end}}{{end}}.
- // To do this, parse the if as usual and stop at it {{end}}; the subsequent{{end}}
- // is assumed. This technique works even for long if-else-if chains.
- // TODO: Should we allow else-if in with and range?
- if t.peek().typ == itemIf {
- t.next() // Consume the "if" token.
- elseList = t.newList(next.Position())
- elseList.append(t.ifControl())
- // Do not consume the next item - only one {{end}} required.
- break
- }
- }
- elseList, next = t.itemList()
- if next.Type() != nodeEnd {
- t.errorf("expected end; found %s", next)
- }
- }
- return pipe.Position(), line, pipe, list, elseList
-}
-
-// If:
-// {{if pipeline}} itemList {{end}}
-// {{if pipeline}} itemList {{else}} itemList {{end}}
-// If keyword is past.
-func (t *Tree) ifControl() Node {
- return t.newIf(t.parseControl(true, "if"))
-}
-
-// Range:
-// {{range pipeline}} itemList {{end}}
-// {{range pipeline}} itemList {{else}} itemList {{end}}
-// Range keyword is past.
-func (t *Tree) rangeControl() Node {
- return t.newRange(t.parseControl(false, "range"))
-}
-
-// With:
-// {{with pipeline}} itemList {{end}}
-// {{with pipeline}} itemList {{else}} itemList {{end}}
-// If keyword is past.
-func (t *Tree) withControl() Node {
- return t.newWith(t.parseControl(false, "with"))
-}
-
-// End:
-// {{end}}
-// End keyword is past.
-func (t *Tree) endControl() Node {
- return t.newEnd(t.expect(itemRightDelim, "end").pos)
-}
-
-// Else:
-// {{else}}
-// Else keyword is past.
-func (t *Tree) elseControl() Node {
- // Special case for "else if".
- peek := t.peekNonSpace()
- if peek.typ == itemIf {
- // We see "{{else if ... " but in effect rewrite it to {{else}}{{if ... ".
- return t.newElse(peek.pos, t.lex.lineNumber())
- }
- return t.newElse(t.expect(itemRightDelim, "else").pos, t.lex.lineNumber())
-}
-
-// Template:
-// {{template stringValue pipeline}}
-// Template keyword is past. The name must be something that can evaluate
-// to a string.
-func (t *Tree) templateControl() Node {
- var name string
- token := t.nextNonSpace()
- switch token.typ {
- case itemString, itemRawString:
- s, err := strconv.Unquote(token.val)
- if err != nil {
- t.error(err)
- }
- name = s
- default:
- t.unexpected(token, "template invocation")
- }
- var pipe *PipeNode
- if t.nextNonSpace().typ != itemRightDelim {
- t.backup()
- // Do not pop variables; they persist until "end".
- pipe = t.pipeline("template")
- }
- return t.newTemplate(token.pos, t.lex.lineNumber(), name, pipe)
-}
-
-// command:
-// operand (space operand)*
-// space-separated arguments up to a pipeline character or right delimiter.
-// we consume the pipe character but leave the right delim to terminate the action.
-func (t *Tree) command() *CommandNode {
- cmd := t.newCommand(t.peekNonSpace().pos)
- for {
- t.peekNonSpace() // skip leading spaces.
- operand := t.operand()
- if operand != nil {
- cmd.append(operand)
- }
- switch token := t.next(); token.typ {
- case itemSpace:
- continue
- case itemError:
- t.errorf("%s", token.val)
- case itemRightDelim, itemRightParen:
- t.backup()
- case itemPipe:
- default:
- t.errorf("unexpected %s in operand; missing space?", token)
- }
- break
- }
- if len(cmd.Args) == 0 {
- t.errorf("empty command")
- }
- return cmd
-}
-
-// operand:
-// term .Field*
-// An operand is a space-separated component of a command,
-// a term possibly followed by field accesses.
-// A nil return means the next item is not an operand.
-func (t *Tree) operand() Node {
- node := t.term()
- if node == nil {
- return nil
- }
- if t.peek().typ == itemField {
- chain := t.newChain(t.peek().pos, node)
- for t.peek().typ == itemField {
- chain.Add(t.next().val)
- }
- // Compatibility with original API: If the term is of type NodeField
- // or NodeVariable, just put more fields on the original.
- // Otherwise, keep the Chain node.
- // TODO: Switch to Chains always when we can.
- switch node.Type() {
- case NodeField:
- node = t.newField(chain.Position(), chain.String())
- case NodeVariable:
- node = t.newVariable(chain.Position(), chain.String())
- default:
- node = chain
- }
- }
- return node
-}
-
-// term:
-// literal (number, string, nil, boolean)
-// function (identifier)
-// .
-// .Field
-// $
-// '(' pipeline ')'
-// A term is a simple "expression".
-// A nil return means the next item is not a term.
-func (t *Tree) term() Node {
- switch token := t.nextNonSpace(); token.typ {
- case itemError:
- t.errorf("%s", token.val)
- case itemIdentifier:
- if !t.hasFunction(token.val) {
- t.errorf("function %q not defined", token.val)
- }
- return NewIdentifier(token.val).SetTree(t).SetPos(token.pos)
- case itemDot:
- return t.newDot(token.pos)
- case itemNil:
- return t.newNil(token.pos)
- case itemVariable:
- return t.useVar(token.pos, token.val)
- case itemField:
- return t.newField(token.pos, token.val)
- case itemBool:
- return t.newBool(token.pos, token.val == "true")
- case itemCharConstant, itemComplex, itemNumber:
- number, err := t.newNumber(token.pos, token.val, token.typ)
- if err != nil {
- t.error(err)
- }
- return number
- case itemLeftParen:
- pipe := t.pipeline("parenthesized pipeline")
- if token := t.next(); token.typ != itemRightParen {
- t.errorf("unclosed right paren: unexpected %s", token)
- }
- return pipe
- case itemString, itemRawString:
- s, err := strconv.Unquote(token.val)
- if err != nil {
- t.error(err)
- }
- return t.newString(token.pos, token.val, s)
- }
- t.backup()
- return nil
-}
-
-// hasFunction reports if a function name exists in the Tree's maps.
-func (t *Tree) hasFunction(name string) bool {
- for _, funcMap := range t.funcs {
- if funcMap == nil {
- continue
- }
- if funcMap[name] != nil {
- return true
- }
- }
- return false
-}
-
-// popVars trims the variable list to the specified length
-func (t *Tree) popVars(n int) {
- t.vars = t.vars[:n]
-}
-
-// useVar returns a node for a variable reference. It errors if the
-// variable is not defined.
-func (t *Tree) useVar(pos Pos, name string) Node {
- v := t.newVariable(pos, name)
- for _, varName := range t.vars {
- if varName == v.Ident[0] {
- return v
- }
- }
- t.errorf("undefined variable %q", v.Ident[0])
- return nil
-}
diff --git a/vendor/github.com/alecthomas/template/template.go b/vendor/github.com/alecthomas/template/template.go
deleted file mode 100644
index 447ed2a..0000000
--- a/vendor/github.com/alecthomas/template/template.go
+++ /dev/null
@@ -1,218 +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 template
-
-import (
- "fmt"
- "reflect"
-
- "github.com/alecthomas/template/parse"
-)
-
-// common holds the information shared by related templates.
-type common struct {
- tmpl map[string]*Template
- // We use two maps, one for parsing and one for execution.
- // This separation makes the API cleaner since it doesn't
- // expose reflection to the client.
- parseFuncs FuncMap
- execFuncs map[string]reflect.Value
-}
-
-// Template is the representation of a parsed template. The *parse.Tree
-// field is exported only for use by html/template and should be treated
-// as unexported by all other clients.
-type Template struct {
- name string
- *parse.Tree
- *common
- leftDelim string
- rightDelim string
-}
-
-// New allocates a new template with the given name.
-func New(name string) *Template {
- return &Template{
- name: name,
- }
-}
-
-// Name returns the name of the template.
-func (t *Template) Name() string {
- return t.name
-}
-
-// New allocates a new template associated with the given one and with the same
-// delimiters. The association, which is transitive, allows one template to
-// invoke another with a {{template}} action.
-func (t *Template) New(name string) *Template {
- t.init()
- return &Template{
- name: name,
- common: t.common,
- leftDelim: t.leftDelim,
- rightDelim: t.rightDelim,
- }
-}
-
-func (t *Template) init() {
- if t.common == nil {
- t.common = new(common)
- t.tmpl = make(map[string]*Template)
- t.parseFuncs = make(FuncMap)
- t.execFuncs = make(map[string]reflect.Value)
- }
-}
-
-// Clone returns a duplicate of the template, including all associated
-// templates. The actual representation is not copied, but the name space of
-// associated templates is, so further calls to Parse in the copy will add
-// templates to the copy but not to the original. Clone can be used to prepare
-// common templates and use them with variant definitions for other templates
-// by adding the variants after the clone is made.
-func (t *Template) Clone() (*Template, error) {
- nt := t.copy(nil)
- nt.init()
- nt.tmpl[t.name] = nt
- for k, v := range t.tmpl {
- if k == t.name { // Already installed.
- continue
- }
- // The associated templates share nt's common structure.
- tmpl := v.copy(nt.common)
- nt.tmpl[k] = tmpl
- }
- for k, v := range t.parseFuncs {
- nt.parseFuncs[k] = v
- }
- for k, v := range t.execFuncs {
- nt.execFuncs[k] = v
- }
- return nt, nil
-}
-
-// copy returns a shallow copy of t, with common set to the argument.
-func (t *Template) copy(c *common) *Template {
- nt := New(t.name)
- nt.Tree = t.Tree
- nt.common = c
- nt.leftDelim = t.leftDelim
- nt.rightDelim = t.rightDelim
- return nt
-}
-
-// AddParseTree creates a new template with the name and parse tree
-// and associates it with t.
-func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) {
- if t.common != nil && t.tmpl[name] != nil {
- return nil, fmt.Errorf("template: redefinition of template %q", name)
- }
- nt := t.New(name)
- nt.Tree = tree
- t.tmpl[name] = nt
- return nt, nil
-}
-
-// Templates returns a slice of the templates associated with t, including t
-// itself.
-func (t *Template) Templates() []*Template {
- if t.common == nil {
- return nil
- }
- // Return a slice so we don't expose the map.
- m := make([]*Template, 0, len(t.tmpl))
- for _, v := range t.tmpl {
- m = append(m, v)
- }
- return m
-}
-
-// Delims sets the action delimiters to the specified strings, to be used in
-// subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template
-// definitions will inherit the settings. An empty delimiter stands for the
-// corresponding default: {{ or }}.
-// The return value is the template, so calls can be chained.
-func (t *Template) Delims(left, right string) *Template {
- t.leftDelim = left
- t.rightDelim = right
- return t
-}
-
-// Funcs adds the elements of the argument map to the template's function map.
-// It panics if a value in the map is not a function with appropriate return
-// type. However, it is legal to overwrite elements of the map. The return
-// value is the template, so calls can be chained.
-func (t *Template) Funcs(funcMap FuncMap) *Template {
- t.init()
- addValueFuncs(t.execFuncs, funcMap)
- addFuncs(t.parseFuncs, funcMap)
- return t
-}
-
-// Lookup returns the template with the given name that is associated with t,
-// or nil if there is no such template.
-func (t *Template) Lookup(name string) *Template {
- if t.common == nil {
- return nil
- }
- return t.tmpl[name]
-}
-
-// Parse parses a string into a template. Nested template definitions will be
-// associated with the top-level template t. Parse may be called multiple times
-// to parse definitions of templates to associate with t. It is an error if a
-// resulting template is non-empty (contains content other than template
-// definitions) and would replace a non-empty template with the same name.
-// (In multiple calls to Parse with the same receiver template, only one call
-// can contain text other than space, comments, and template definitions.)
-func (t *Template) Parse(text string) (*Template, error) {
- t.init()
- trees, err := parse.Parse(t.name, text, t.leftDelim, t.rightDelim, t.parseFuncs, builtins)
- if err != nil {
- return nil, err
- }
- // Add the newly parsed trees, including the one for t, into our common structure.
- for name, tree := range trees {
- // If the name we parsed is the name of this template, overwrite this template.
- // The associate method checks it's not a redefinition.
- tmpl := t
- if name != t.name {
- tmpl = t.New(name)
- }
- // Even if t == tmpl, we need to install it in the common.tmpl map.
- if replace, err := t.associate(tmpl, tree); err != nil {
- return nil, err
- } else if replace {
- tmpl.Tree = tree
- }
- tmpl.leftDelim = t.leftDelim
- tmpl.rightDelim = t.rightDelim
- }
- return t, nil
-}
-
-// associate installs the new template into the group of templates associated
-// with t. It is an error to reuse a name except to overwrite an empty
-// template. The two are already known to share the common structure.
-// The boolean return value reports wither to store this tree as t.Tree.
-func (t *Template) associate(new *Template, tree *parse.Tree) (bool, error) {
- if new.common != t.common {
- panic("internal error: associate not common")
- }
- name := new.name
- if old := t.tmpl[name]; old != nil {
- oldIsEmpty := parse.IsEmptyTree(old.Root)
- newIsEmpty := parse.IsEmptyTree(tree.Root)
- if newIsEmpty {
- // Whether old is empty or not, new is empty; no reason to replace old.
- return false, nil
- }
- if !oldIsEmpty {
- return false, fmt.Errorf("template: redefinition of template %q", name)
- }
- }
- t.tmpl[name] = new
- return true, nil
-}
diff --git a/vendor/github.com/alecthomas/units/README.md b/vendor/github.com/alecthomas/units/README.md
deleted file mode 100644
index bee884e..0000000
--- a/vendor/github.com/alecthomas/units/README.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# Units - Helpful unit multipliers and functions for Go
-
-The goal of this package is to have functionality similar to the [time](http://golang.org/pkg/time/) package.
-
-It allows for code like this:
-
-```go
-n, err := ParseBase2Bytes("1KB")
-// n == 1024
-n = units.Mebibyte * 512
-```
diff --git a/vendor/github.com/alecthomas/units/bytes.go b/vendor/github.com/alecthomas/units/bytes.go
deleted file mode 100644
index eaadeb8..0000000
--- a/vendor/github.com/alecthomas/units/bytes.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package units
-
-// Base2Bytes is the old non-SI power-of-2 byte scale (1024 bytes in a kilobyte,
-// etc.).
-type Base2Bytes int64
-
-// Base-2 byte units.
-const (
- Kibibyte Base2Bytes = 1024
- KiB = Kibibyte
- Mebibyte = Kibibyte * 1024
- MiB = Mebibyte
- Gibibyte = Mebibyte * 1024
- GiB = Gibibyte
- Tebibyte = Gibibyte * 1024
- TiB = Tebibyte
- Pebibyte = Tebibyte * 1024
- PiB = Pebibyte
- Exbibyte = Pebibyte * 1024
- EiB = Exbibyte
-)
-
-var (
- bytesUnitMap = MakeUnitMap("iB", "B", 1024)
- oldBytesUnitMap = MakeUnitMap("B", "B", 1024)
-)
-
-// ParseBase2Bytes supports both iB and B in base-2 multipliers. That is, KB
-// and KiB are both 1024.
-func ParseBase2Bytes(s string) (Base2Bytes, error) {
- n, err := ParseUnit(s, bytesUnitMap)
- if err != nil {
- n, err = ParseUnit(s, oldBytesUnitMap)
- }
- return Base2Bytes(n), err
-}
-
-func (b Base2Bytes) String() string {
- return ToString(int64(b), 1024, "iB", "B")
-}
-
-var (
- metricBytesUnitMap = MakeUnitMap("B", "B", 1000)
-)
-
-// MetricBytes are SI byte units (1000 bytes in a kilobyte).
-type MetricBytes SI
-
-// SI base-10 byte units.
-const (
- Kilobyte MetricBytes = 1000
- KB = Kilobyte
- Megabyte = Kilobyte * 1000
- MB = Megabyte
- Gigabyte = Megabyte * 1000
- GB = Gigabyte
- Terabyte = Gigabyte * 1000
- TB = Terabyte
- Petabyte = Terabyte * 1000
- PB = Petabyte
- Exabyte = Petabyte * 1000
- EB = Exabyte
-)
-
-// ParseMetricBytes parses base-10 metric byte units. That is, KB is 1000 bytes.
-func ParseMetricBytes(s string) (MetricBytes, error) {
- n, err := ParseUnit(s, metricBytesUnitMap)
- return MetricBytes(n), err
-}
-
-func (m MetricBytes) String() string {
- return ToString(int64(m), 1000, "B", "B")
-}
-
-// ParseStrictBytes supports both iB and B suffixes for base 2 and metric,
-// respectively. That is, KiB represents 1024 and KB represents 1000.
-func ParseStrictBytes(s string) (int64, error) {
- n, err := ParseUnit(s, bytesUnitMap)
- if err != nil {
- n, err = ParseUnit(s, metricBytesUnitMap)
- }
- return int64(n), err
-}
diff --git a/vendor/github.com/alecthomas/units/doc.go b/vendor/github.com/alecthomas/units/doc.go
deleted file mode 100644
index 156ae38..0000000
--- a/vendor/github.com/alecthomas/units/doc.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// Package units provides helpful unit multipliers and functions for Go.
-//
-// The goal of this package is to have functionality similar to the time [1] package.
-//
-//
-// [1] http://golang.org/pkg/time/
-//
-// It allows for code like this:
-//
-// n, err := ParseBase2Bytes("1KB")
-// // n == 1024
-// n = units.Mebibyte * 512
-package units
diff --git a/vendor/github.com/alecthomas/units/si.go b/vendor/github.com/alecthomas/units/si.go
deleted file mode 100644
index 8234a9d..0000000
--- a/vendor/github.com/alecthomas/units/si.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package units
-
-// SI units.
-type SI int64
-
-// SI unit multiples.
-const (
- Kilo SI = 1000
- Mega = Kilo * 1000
- Giga = Mega * 1000
- Tera = Giga * 1000
- Peta = Tera * 1000
- Exa = Peta * 1000
-)
-
-func MakeUnitMap(suffix, shortSuffix string, scale int64) map[string]float64 {
- return map[string]float64{
- shortSuffix: 1,
- "K" + suffix: float64(scale),
- "M" + suffix: float64(scale * scale),
- "G" + suffix: float64(scale * scale * scale),
- "T" + suffix: float64(scale * scale * scale * scale),
- "P" + suffix: float64(scale * scale * scale * scale * scale),
- "E" + suffix: float64(scale * scale * scale * scale * scale * scale),
- }
-}
diff --git a/vendor/github.com/alecthomas/units/util.go b/vendor/github.com/alecthomas/units/util.go
deleted file mode 100644
index 6527e92..0000000
--- a/vendor/github.com/alecthomas/units/util.go
+++ /dev/null
@@ -1,138 +0,0 @@
-package units
-
-import (
- "errors"
- "fmt"
- "strings"
-)
-
-var (
- siUnits = []string{"", "K", "M", "G", "T", "P", "E"}
-)
-
-func ToString(n int64, scale int64, suffix, baseSuffix string) string {
- mn := len(siUnits)
- out := make([]string, mn)
- for i, m := range siUnits {
- if n%scale != 0 || i == 0 && n == 0 {
- s := suffix
- if i == 0 {
- s = baseSuffix
- }
- out[mn-1-i] = fmt.Sprintf("%d%s%s", n%scale, m, s)
- }
- n /= scale
- if n == 0 {
- break
- }
- }
- return strings.Join(out, "")
-}
-
-// Below code ripped straight from http://golang.org/src/pkg/time/format.go?s=33392:33438#L1123
-var errLeadingInt = errors.New("units: bad [0-9]*") // never printed
-
-// leadingInt consumes the leading [0-9]* from s.
-func leadingInt(s string) (x int64, rem string, err error) {
- i := 0
- for ; i < len(s); i++ {
- c := s[i]
- if c < '0' || c > '9' {
- break
- }
- if x >= (1<<63-10)/10 {
- // overflow
- return 0, "", errLeadingInt
- }
- x = x*10 + int64(c) - '0'
- }
- return x, s[i:], nil
-}
-
-func ParseUnit(s string, unitMap map[string]float64) (int64, error) {
- // [-+]?([0-9]*(\.[0-9]*)?[a-z]+)+
- orig := s
- f := float64(0)
- neg := false
-
- // Consume [-+]?
- if s != "" {
- c := s[0]
- if c == '-' || c == '+' {
- neg = c == '-'
- s = s[1:]
- }
- }
- // Special case: if all that is left is "0", this is zero.
- if s == "0" {
- return 0, nil
- }
- if s == "" {
- return 0, errors.New("units: invalid " + orig)
- }
- for s != "" {
- g := float64(0) // this element of the sequence
-
- var x int64
- var err error
-
- // The next character must be [0-9.]
- if !(s[0] == '.' || ('0' <= s[0] && s[0] <= '9')) {
- return 0, errors.New("units: invalid " + orig)
- }
- // Consume [0-9]*
- pl := len(s)
- x, s, err = leadingInt(s)
- if err != nil {
- return 0, errors.New("units: invalid " + orig)
- }
- g = float64(x)
- pre := pl != len(s) // whether we consumed anything before a period
-
- // Consume (\.[0-9]*)?
- post := false
- if s != "" && s[0] == '.' {
- s = s[1:]
- pl := len(s)
- x, s, err = leadingInt(s)
- if err != nil {
- return 0, errors.New("units: invalid " + orig)
- }
- scale := 1.0
- for n := pl - len(s); n > 0; n-- {
- scale *= 10
- }
- g += float64(x) / scale
- post = pl != len(s)
- }
- if !pre && !post {
- // no digits (e.g. ".s" or "-.s")
- return 0, errors.New("units: invalid " + orig)
- }
-
- // Consume unit.
- i := 0
- for ; i < len(s); i++ {
- c := s[i]
- if c == '.' || ('0' <= c && c <= '9') {
- break
- }
- }
- u := s[:i]
- s = s[i:]
- unit, ok := unitMap[u]
- if !ok {
- return 0, errors.New("units: unknown unit " + u + " in " + orig)
- }
-
- f += g * unit
- }
-
- if neg {
- f = -f
- }
- if f < float64(-1<<63) || f > float64(1<<63-1) {
- return 0, errors.New("units: overflow parsing unit")
- }
- return int64(f), nil
-}
diff --git a/vendor/github.com/golang/snappy/snappy.go b/vendor/github.com/golang/snappy/snappy.go
index e98653a..15af18d 100644
--- a/vendor/github.com/golang/snappy/snappy.go
+++ b/vendor/github.com/golang/snappy/snappy.go
@@ -6,7 +6,7 @@
// It aims for very high speeds and reasonable compression.
//
// The C++ snappy implementation is at https://github.com/google/snappy
-package snappy
+package snappy // import "github.com/golang/snappy"
import (
"hash/crc32"
diff --git a/vendor/github.com/alecthomas/template/LICENSE b/vendor/github.com/gorilla/context/LICENSE
similarity index 83%
rename from vendor/github.com/alecthomas/template/LICENSE
rename to vendor/github.com/gorilla/context/LICENSE
index 7448756..0e5fb87 100644
--- a/vendor/github.com/alecthomas/template/LICENSE
+++ b/vendor/github.com/gorilla/context/LICENSE
@@ -1,16 +1,16 @@
-Copyright (c) 2012 The Go Authors. All rights reserved.
+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
+ * 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
+ * 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
+ * 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.
diff --git a/vendor/github.com/gorilla/context/README.md b/vendor/github.com/gorilla/context/README.md
new file mode 100644
index 0000000..08f8669
--- /dev/null
+++ b/vendor/github.com/gorilla/context/README.md
@@ -0,0 +1,10 @@
+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.
+
+> Note: gorilla/context, having been born well before `context.Context` existed, does not play well
+> with the shallow copying of the request that [`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext) (added to net/http Go 1.7 onwards) performs. You should either use *just* gorilla/context, or moving forward, the new `http.Request.Context()`.
+
+Read the full documentation here: http://www.gorillatoolkit.org/pkg/context
diff --git a/vendor/github.com/gorilla/context/context.go b/vendor/github.com/gorilla/context/context.go
new file mode 100644
index 0000000..81cb128
--- /dev/null
+++ b/vendor/github.com/gorilla/context/context.go
@@ -0,0 +1,143 @@
+// 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/gorilla/context/doc.go b/vendor/github.com/gorilla/context/doc.go
new file mode 100644
index 0000000..448d1bf
--- /dev/null
+++ b/vendor/github.com/gorilla/context/doc.go
@@ -0,0 +1,88 @@
+// 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.
+
+Note: gorilla/context, having been born well before `context.Context` existed,
+does not play well > with the shallow copying of the request that
+[`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext)
+(added to net/http Go 1.7 onwards) performs. You should either use *just*
+gorilla/context, or moving forward, the new `http.Request.Context()`.
+
+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/gorilla/csrf/LICENSE b/vendor/github.com/gorilla/csrf/LICENSE
new file mode 100644
index 0000000..f407b7f
--- /dev/null
+++ b/vendor/github.com/gorilla/csrf/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2015, Matt Silverlock (matt@eatsleeprepeat.net) All rights
+reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+
+2. 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.
+
+3. Neither the name of the copyright holder nor the names of its contributors
+may be used to endorse or promote products derived from this software without
+specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/gorilla/csrf/README.md b/vendor/github.com/gorilla/csrf/README.md
new file mode 100644
index 0000000..02e4f42
--- /dev/null
+++ b/vendor/github.com/gorilla/csrf/README.md
@@ -0,0 +1,232 @@
+# gorilla/csrf
+[![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Build Status](https://travis-ci.org/gorilla/csrf.svg?branch=master)](https://travis-ci.org/gorilla/csrf)
+
+gorilla/csrf is a HTTP middleware library that provides [cross-site request
+forgery](http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/) (CSRF)
+ protection. It includes:
+
+* The `csrf.Protect` middleware/handler provides CSRF protection on routes
+ attached to a router or a sub-router.
+* A `csrf.Token` function that provides the token to pass into your response,
+ whether that be a HTML form or a JSON response body.
+* ... and a `csrf.TemplateField` helper that you can pass into your `html/template`
+ templates to replace a `{{ .csrfField }}` template tag with a hidden input
+ field.
+
+gorilla/csrf is designed to work with any Go web framework, including:
+
+* The [Gorilla](http://www.gorillatoolkit.org/) toolkit
+* Go's built-in [net/http](http://golang.org/pkg/net/http/) package
+* [Goji](https://goji.io) - see the [tailored fork](https://github.com/goji/csrf)
+* [Gin](https://github.com/gin-gonic/gin)
+* [Echo](https://github.com/labstack/echo)
+* ... and any other router/framework that rallies around Go's `http.Handler` interface.
+
+gorilla/csrf is also compatible with middleware 'helper' libraries like
+[Alice](https://github.com/justinas/alice) and [Negroni](https://github.com/codegangsta/negroni).
+
+## Install
+
+With a properly configured Go toolchain:
+```sh
+go get github.com/gorilla/csrf
+```
+
+## Examples
+
+* [HTML Forms](#html-forms)
+* [JavaScript Apps](#javascript-applications)
+* [Google App Engine](#google-app-engine)
+* [Setting Options](#setting-options)
+
+gorilla/csrf is easy to use: add the middleware to your router with
+the below:
+
+```go
+CSRF := csrf.Protect([]byte("32-byte-long-auth-key"))
+http.ListenAndServe(":8000", CSRF(r))
+```
+
+...and then collect the token with `csrf.Token(r)` in your handlers before
+passing it to the template, JSON body or HTTP header (see below).
+
+Note that the authentication key passed to `csrf.Protect([]byte(key))` should be
+32-bytes long and persist across application restarts. Generating a random key
+won't allow you to authenticate existing cookies and will break your CSRF
+validation.
+
+gorilla/csrf inspects the HTTP headers (first) and form body (second) on
+subsequent POST/PUT/PATCH/DELETE/etc. requests for the token.
+
+### HTML Forms
+
+Here's the common use-case: HTML forms you want to provide CSRF protection for,
+in order to protect malicious POST requests being made:
+
+```go
+package main
+
+import (
+ "net/http"
+
+ "github.com/gorilla/csrf"
+ "github.com/gorilla/mux"
+)
+
+func main() {
+ r := mux.NewRouter()
+ r.HandleFunc("/signup", ShowSignupForm)
+ // All POST requests without a valid token will return HTTP 403 Forbidden.
+ r.HandleFunc("/signup/post", SubmitSignupForm)
+
+ // Add the middleware to your router by wrapping it.
+ http.ListenAndServe(":8000",
+ csrf.Protect([]byte("32-byte-long-auth-key"))(r))
+ // PS: Don't forget to pass csrf.Secure(false) if you're developing locally
+ // over plain HTTP (just don't leave it on in production).
+}
+
+func ShowSignupForm(w http.ResponseWriter, r *http.Request) {
+ // signup_form.tmpl just needs a {{ .csrfField }} template tag for
+ // csrf.TemplateField to inject the CSRF token into. Easy!
+ t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{
+ csrf.TemplateTag: csrf.TemplateField(r),
+ })
+ // We could also retrieve the token directly from csrf.Token(r) and
+ // set it in the request header - w.Header.Set("X-CSRF-Token", token)
+ // This is useful if your sending JSON to clients or a front-end JavaScript
+ // framework.
+}
+
+func SubmitSignupForm(w http.ResponseWriter, r *http.Request) {
+ // We can trust that requests making it this far have satisfied
+ // our CSRF protection requirements.
+}
+```
+
+Note that the CSRF middleware will (by necessity) consume the request body if the
+token is passed via POST form values. If you need to consume this in your
+handler, insert your own middleware earlier in the chain to capture the request
+body.
+
+### JavaScript Applications
+
+This approach is useful if you're using a front-end JavaScript framework like
+React, Ember or Angular, or are providing a JSON API.
+
+We'll also look at applying selective CSRF protection using
+[gorilla/mux's](http://www.gorillatoolkit.org/pkg/mux) sub-routers,
+as we don't handle any POST/PUT/DELETE requests with our top-level router.
+
+```go
+package main
+
+import (
+ "github.com/gorilla/csrf"
+ "github.com/gorilla/mux"
+)
+
+func main() {
+ r := mux.NewRouter()
+
+ api := r.PathPrefix("/api").Subrouter()
+ api.HandleFunc("/user/:id", GetUser).Methods("GET")
+
+ http.ListenAndServe(":8000",
+ csrf.Protect([]byte("32-byte-long-auth-key"))(r))
+}
+
+func GetUser(w http.ResponseWriter, r *http.Request) {
+ // Authenticate the request, get the id from the route params,
+ // and fetch the user from the DB, etc.
+
+ // Get the token and pass it in the CSRF header. Our JSON-speaking client
+ // or JavaScript framework can now read the header and return the token in
+ // in its own "X-CSRF-Token" request header on the subsequent POST.
+ w.Header().Set("X-CSRF-Token", csrf.Token(r))
+ b, err := json.Marshal(user)
+ if err != nil {
+ http.Error(w, err.Error(), 500)
+ return
+ }
+
+ w.Write(b)
+}
+```
+
+### Google App Engine
+
+If you're using [Google App
+Engine](https://cloud.google.com/appengine/docs/go/how-requests-are-handled#Go_Requests_and_HTTP),
+which doesn't allow you to hook into the default `http.ServeMux` directly,
+you can still use gorilla/csrf (and gorilla/mux):
+
+```go
+package app
+
+// Remember: appengine has its own package main
+func init() {
+ r := mux.NewRouter()
+ r.HandleFunc("/", IndexHandler)
+ // ...
+
+ // We pass our CSRF-protected router to the DefaultServeMux
+ http.Handle("/", csrf.Protect([]byte(your-key))(r))
+}
+```
+
+### Setting Options
+
+What about providing your own error handler and changing the HTTP header the
+package inspects on requests? (i.e. an existing API you're porting to Go). Well,
+gorilla/csrf provides options for changing these as you see fit:
+
+```go
+func main() {
+ CSRF := csrf.Protect(
+ []byte("a-32-byte-long-key-goes-here"),
+ csrf.RequestHeader("Authenticity-Token"),
+ csrf.FieldName("authenticity_token"),
+ csrf.ErrorHandler(http.HandlerFunc(serverError(403))),
+ )
+
+ r := mux.NewRouter()
+ r.HandleFunc("/signup", GetSignupForm)
+ r.HandleFunc("/signup/post", PostSignupForm)
+
+ http.ListenAndServe(":8000", CSRF(r))
+}
+```
+
+Not too bad, right?
+
+If there's something you're confused about or a feature you would like to see
+added, open an issue.
+
+## Design Notes
+
+Getting CSRF protection right is important, so here's some background:
+
+* This library generates unique-per-request (masked) tokens as a mitigation
+ against the [BREACH attack](http://breachattack.com/).
+* The 'base' (unmasked) token is stored in the session, which means that
+ multiple browser tabs won't cause a user problems as their per-request token
+ is compared with the base token.
+* Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods
+ (GET, HEAD, OPTIONS, TRACE) are the *only* methods where token validation is not
+ enforced.
+* The design is based on the battle-tested
+ [Django](https://docs.djangoproject.com/en/1.8/ref/csrf/) and [Ruby on
+ Rails](http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html)
+ approaches.
+* Cookies are authenticated and based on the [securecookie](https://github.com/gorilla/securecookie)
+ library. They're also Secure (issued over HTTPS only) and are HttpOnly
+ by default, because sane defaults are important.
+* Go's `crypto/rand` library is used to generate the 32 byte (256 bit) tokens
+ and the one-time-pad used for masking them.
+
+This library does not seek to be adventurous.
+
+## License
+
+BSD licensed. See the LICENSE file for details.
diff --git a/vendor/github.com/gorilla/csrf/context.go b/vendor/github.com/gorilla/csrf/context.go
new file mode 100644
index 0000000..d8bb42f
--- /dev/null
+++ b/vendor/github.com/gorilla/csrf/context.go
@@ -0,0 +1,29 @@
+// +build go1.7
+
+package csrf
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/pkg/errors"
+)
+
+func contextGet(r *http.Request, key string) (interface{}, error) {
+ val := r.Context().Value(key)
+ if val == nil {
+ return nil, errors.Errorf("no value exists in the context for key %q", key)
+ }
+
+ return val, nil
+}
+
+func contextSave(r *http.Request, key string, val interface{}) *http.Request {
+ ctx := r.Context()
+ ctx = context.WithValue(ctx, key, val)
+ return r.WithContext(ctx)
+}
+
+func contextClear(r *http.Request) {
+ // no-op for go1.7+
+}
diff --git a/vendor/github.com/gorilla/csrf/context_legacy.go b/vendor/github.com/gorilla/csrf/context_legacy.go
new file mode 100644
index 0000000..f88c9eb
--- /dev/null
+++ b/vendor/github.com/gorilla/csrf/context_legacy.go
@@ -0,0 +1,28 @@
+// +build !go1.7
+
+package csrf
+
+import (
+ "net/http"
+
+ "github.com/gorilla/context"
+
+ "github.com/pkg/errors"
+)
+
+func contextGet(r *http.Request, key string) (interface{}, error) {
+ if val, ok := context.GetOk(r, key); ok {
+ return val, nil
+ }
+
+ return nil, errors.Errorf("no value exists in the context for key %q", key)
+}
+
+func contextSave(r *http.Request, key string, val interface{}) *http.Request {
+ context.Set(r, key, val)
+ return r
+}
+
+func contextClear(r *http.Request) {
+ context.Clear(r)
+}
diff --git a/vendor/github.com/gorilla/csrf/csrf.go b/vendor/github.com/gorilla/csrf/csrf.go
new file mode 100644
index 0000000..b4b0439
--- /dev/null
+++ b/vendor/github.com/gorilla/csrf/csrf.go
@@ -0,0 +1,275 @@
+package csrf
+
+import (
+ "fmt"
+ "net/http"
+ "net/url"
+
+ "github.com/pkg/errors"
+
+ "github.com/gorilla/securecookie"
+)
+
+// CSRF token length in bytes.
+const tokenLength = 32
+
+// Context/session keys & prefixes
+const (
+ tokenKey string = "gorilla.csrf.Token"
+ formKey string = "gorilla.csrf.Form"
+ errorKey string = "gorilla.csrf.Error"
+ skipCheckKey string = "gorilla.csrf.Skip"
+ cookieName string = "_gorilla_csrf"
+ errorPrefix string = "gorilla/csrf: "
+)
+
+var (
+ // The name value used in form fields.
+ fieldName = tokenKey
+ // defaultAge sets the default MaxAge for cookies.
+ defaultAge = 3600 * 12
+ // The default HTTP request header to inspect
+ headerName = "X-CSRF-Token"
+ // Idempotent (safe) methods as defined by RFC7231 section 4.2.2.
+ safeMethods = []string{"GET", "HEAD", "OPTIONS", "TRACE"}
+)
+
+// TemplateTag provides a default template tag - e.g. {{ .csrfField }} - for use
+// with the TemplateField function.
+var TemplateTag = "csrfField"
+
+var (
+ // ErrNoReferer is returned when a HTTPS request provides an empty Referer
+ // header.
+ ErrNoReferer = errors.New("referer not supplied")
+ // ErrBadReferer is returned when the scheme & host in the URL do not match
+ // the supplied Referer header.
+ ErrBadReferer = errors.New("referer invalid")
+ // ErrNoToken is returned if no CSRF token is supplied in the request.
+ ErrNoToken = errors.New("CSRF token not found in request")
+ // ErrBadToken is returned if the CSRF token in the request does not match
+ // the token in the session, or is otherwise malformed.
+ ErrBadToken = errors.New("CSRF token invalid")
+)
+
+type csrf struct {
+ h http.Handler
+ sc *securecookie.SecureCookie
+ st store
+ opts options
+}
+
+// options contains the optional settings for the CSRF middleware.
+type options struct {
+ MaxAge int
+ Domain string
+ Path string
+ // Note that the function and field names match the case of the associated
+ // http.Cookie field instead of the "correct" HTTPOnly name that golint suggests.
+ HttpOnly bool
+ Secure bool
+ RequestHeader string
+ FieldName string
+ ErrorHandler http.Handler
+ CookieName string
+}
+
+// Protect is HTTP middleware that provides Cross-Site Request Forgery
+// protection.
+//
+// It securely generates a masked (unique-per-request) token that
+// can be embedded in the HTTP response (e.g. form field or HTTP header).
+// The original (unmasked) token is stored in the session, which is inaccessible
+// by an attacker (provided you are using HTTPS). Subsequent requests are
+// expected to include this token, which is compared against the session token.
+// Requests that do not provide a matching token are served with a HTTP 403
+// 'Forbidden' error response.
+//
+// Example:
+// package main
+//
+// import (
+// "github.com/elithrar/protect"
+// "github.com/gorilla/mux"
+// )
+//
+// func main() {
+// r := mux.NewRouter()
+//
+// mux.HandlerFunc("/signup", GetSignupForm)
+// // POST requests without a valid token will return a HTTP 403 Forbidden.
+// mux.HandlerFunc("/signup/post", PostSignupForm)
+//
+// // Add the middleware to your router.
+// http.ListenAndServe(":8000",
+// // Note that the authentication key provided should be 32 bytes
+// // long and persist across application restarts.
+// csrf.Protect([]byte("32-byte-long-auth-key"))(r))
+// }
+//
+// func GetSignupForm(w http.ResponseWriter, r *http.Request) {
+// // signup_form.tmpl just needs a {{ .csrfField }} template tag for
+// // csrf.TemplateField to inject the CSRF token into. Easy!
+// t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{
+// csrf.TemplateTag: csrf.TemplateField(r),
+// })
+// // We could also retrieve the token directly from csrf.Token(r) and
+// // set it in the request header - w.Header.Set("X-CSRF-Token", token)
+// // This is useful if your sending JSON to clients or a front-end JavaScript
+// // framework.
+// }
+//
+func Protect(authKey []byte, opts ...Option) func(http.Handler) http.Handler {
+ return func(h http.Handler) http.Handler {
+ cs := parseOptions(h, opts...)
+
+ // Set the defaults if no options have been specified
+ if cs.opts.ErrorHandler == nil {
+ cs.opts.ErrorHandler = http.HandlerFunc(unauthorizedHandler)
+ }
+
+ if cs.opts.MaxAge < 0 {
+ // Default of 12 hours
+ cs.opts.MaxAge = defaultAge
+ }
+
+ if cs.opts.FieldName == "" {
+ cs.opts.FieldName = fieldName
+ }
+
+ if cs.opts.CookieName == "" {
+ cs.opts.CookieName = cookieName
+ }
+
+ if cs.opts.RequestHeader == "" {
+ cs.opts.RequestHeader = headerName
+ }
+
+ // Create an authenticated securecookie instance.
+ if cs.sc == nil {
+ cs.sc = securecookie.New(authKey, nil)
+ // Use JSON serialization (faster than one-off gob encoding)
+ cs.sc.SetSerializer(securecookie.JSONEncoder{})
+ // Set the MaxAge of the underlying securecookie.
+ cs.sc.MaxAge(cs.opts.MaxAge)
+ }
+
+ if cs.st == nil {
+ // Default to the cookieStore
+ cs.st = &cookieStore{
+ name: cs.opts.CookieName,
+ maxAge: cs.opts.MaxAge,
+ secure: cs.opts.Secure,
+ httpOnly: cs.opts.HttpOnly,
+ path: cs.opts.Path,
+ domain: cs.opts.Domain,
+ sc: cs.sc,
+ }
+ }
+
+ return cs
+ }
+}
+
+// Implements http.Handler for the csrf type.
+func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ // Skip the check if directed to. This should always be a bool.
+ if val, err := contextGet(r, skipCheckKey); err == nil {
+ if skip, ok := val.(bool); ok {
+ if skip {
+ cs.h.ServeHTTP(w, r)
+ return
+ }
+ }
+ }
+
+ // Retrieve the token from the session.
+ // An error represents either a cookie that failed HMAC validation
+ // or that doesn't exist.
+ realToken, err := cs.st.Get(r)
+ if err != nil || len(realToken) != tokenLength {
+ // If there was an error retrieving the token, the token doesn't exist
+ // yet, or it's the wrong length, generate a new token.
+ // Note that the new token will (correctly) fail validation downstream
+ // as it will no longer match the request token.
+ realToken, err = generateRandomBytes(tokenLength)
+ if err != nil {
+ r = envError(r, err)
+ cs.opts.ErrorHandler.ServeHTTP(w, r)
+ return
+ }
+
+ // Save the new (real) token in the session store.
+ err = cs.st.Save(realToken, w)
+ if err != nil {
+ r = envError(r, err)
+ cs.opts.ErrorHandler.ServeHTTP(w, r)
+ return
+ }
+ }
+
+ // Save the masked token to the request context
+ r = contextSave(r, tokenKey, mask(realToken, r))
+ // Save the field name to the request context
+ r = contextSave(r, formKey, cs.opts.FieldName)
+
+ // HTTP methods not defined as idempotent ("safe") under RFC7231 require
+ // inspection.
+ if !contains(safeMethods, r.Method) {
+ // Enforce an origin check for HTTPS connections. As per the Django CSRF
+ // implementation (https://goo.gl/vKA7GE) the Referer header is almost
+ // always present for same-domain HTTP requests.
+ if r.URL.Scheme == "https" {
+ // Fetch the Referer value. Call the error handler if it's empty or
+ // otherwise fails to parse.
+ referer, err := url.Parse(r.Referer())
+ if err != nil || referer.String() == "" {
+ r = envError(r, ErrNoReferer)
+ cs.opts.ErrorHandler.ServeHTTP(w, r)
+ return
+ }
+
+ if sameOrigin(r.URL, referer) == false {
+ r = envError(r, ErrBadReferer)
+ cs.opts.ErrorHandler.ServeHTTP(w, r)
+ return
+ }
+ }
+
+ // If the token returned from the session store is nil for non-idempotent
+ // ("unsafe") methods, call the error handler.
+ if realToken == nil {
+ r = envError(r, ErrNoToken)
+ cs.opts.ErrorHandler.ServeHTTP(w, r)
+ return
+ }
+
+ // Retrieve the combined token (pad + masked) token and unmask it.
+ requestToken := unmask(cs.requestToken(r))
+
+ // Compare the request token against the real token
+ if !compareTokens(requestToken, realToken) {
+ r = envError(r, ErrBadToken)
+ cs.opts.ErrorHandler.ServeHTTP(w, r)
+ return
+ }
+
+ }
+
+ // Set the Vary: Cookie header to protect clients from caching the response.
+ w.Header().Add("Vary", "Cookie")
+
+ // Call the wrapped handler/router on success.
+ cs.h.ServeHTTP(w, r)
+ // Clear the request context after the handler has completed.
+ contextClear(r)
+}
+
+// unauthorizedhandler sets a HTTP 403 Forbidden status and writes the
+// CSRF failure reason to the response.
+func unauthorizedHandler(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, fmt.Sprintf("%s - %s",
+ http.StatusText(http.StatusForbidden), FailureReason(r)),
+ http.StatusForbidden)
+ return
+}
diff --git a/vendor/github.com/gorilla/csrf/doc.go b/vendor/github.com/gorilla/csrf/doc.go
new file mode 100644
index 0000000..e0bf408
--- /dev/null
+++ b/vendor/github.com/gorilla/csrf/doc.go
@@ -0,0 +1,161 @@
+/*
+Package csrf (gorilla/csrf) provides Cross Site Request Forgery (CSRF)
+prevention middleware for Go web applications & services.
+
+It includes:
+
+ * The `csrf.Protect` middleware/handler provides CSRF protection on routes
+ attached to a router or a sub-router.
+ * A `csrf.Token` function that provides the token to pass into your response,
+ whether that be a HTML form or a JSON response body.
+ * ... and a `csrf.TemplateField` helper that you can pass into your `html/template`
+ templates to replace a `{{ .csrfField }}` template tag with a hidden input
+ field.
+
+gorilla/csrf is easy to use: add the middleware to individual handlers with
+the below:
+
+ CSRF := csrf.Protect([]byte("32-byte-long-auth-key"))
+ http.HandlerFunc("/route", CSRF(YourHandler))
+
+... and then collect the token with `csrf.Token(r)` before passing it to the
+template, JSON body or HTTP header (you pick!). gorilla/csrf inspects the form body
+(first) and HTTP headers (second) on subsequent POST/PUT/PATCH/DELETE/etc. requests
+for the token.
+
+Note that the authentication key passed to `csrf.Protect([]byte(key))` should be
+32-bytes long and persist across application restarts. Generating a random key
+won't allow you to authenticate existing cookies and will break your CSRF
+validation.
+
+Here's the common use-case: HTML forms you want to provide CSRF protection for,
+in order to protect malicious POST requests being made:
+
+ package main
+
+ import (
+ "fmt"
+ "html/template"
+ "net/http"
+
+ "github.com/gorilla/csrf"
+ "github.com/gorilla/mux"
+ )
+
+ var form = `
+
+
+ Sign Up!
+
+
+
+
+
+ `
+
+ var t = template.Must(template.New("signup_form.tmpl").Parse(form))
+
+ func main() {
+ r := mux.NewRouter()
+ r.HandleFunc("/signup", ShowSignupForm)
+ // All POST requests without a valid token will return HTTP 403 Forbidden.
+ r.HandleFunc("/signup/post", SubmitSignupForm)
+
+ // Add the middleware to your router by wrapping it.
+ http.ListenAndServe(":8000",
+ csrf.Protect([]byte("32-byte-long-auth-key"))(r))
+ // PS: Don't forget to pass csrf.Secure(false) if you're developing locally
+ // over plain HTTP (just don't leave it on in production).
+ }
+
+ func ShowSignupForm(w http.ResponseWriter, r *http.Request) {
+ // signup_form.tmpl just needs a {{ .csrfField }} template tag for
+ // csrf.TemplateField to inject the CSRF token into. Easy!
+ t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{
+ csrf.TemplateTag: csrf.TemplateField(r),
+ })
+ }
+
+ func SubmitSignupForm(w http.ResponseWriter, r *http.Request) {
+ // We can trust that requests making it this far have satisfied
+ // our CSRF protection requirements.
+ fmt.Fprintf(w, "%v\n", r.PostForm)
+ }
+
+Note that the CSRF middleware will (by necessity) consume the request body if the
+token is passed via POST form values. If you need to consume this in your
+handler, insert your own middleware earlier in the chain to capture the request
+body.
+
+You can also send the CSRF token in the response header. This approach is useful
+if you're using a front-end JavaScript framework like Ember or Angular, or are
+providing a JSON API:
+
+ package main
+
+ import (
+ "github.com/gorilla/csrf"
+ "github.com/gorilla/mux"
+ )
+
+ func main() {
+ r := mux.NewRouter()
+
+ api := r.PathPrefix("/api").Subrouter()
+ api.HandleFunc("/user/:id", GetUser).Methods("GET")
+
+ http.ListenAndServe(":8000",
+ csrf.Protect([]byte("32-byte-long-auth-key"))(r))
+ }
+
+ func GetUser(w http.ResponseWriter, r *http.Request) {
+ // Authenticate the request, get the id from the route params,
+ // and fetch the user from the DB, etc.
+
+ // Get the token and pass it in the CSRF header. Our JSON-speaking client
+ // or JavaScript framework can now read the header and return the token in
+ // in its own "X-CSRF-Token" request header on the subsequent POST.
+ w.Header().Set("X-CSRF-Token", csrf.Token(r))
+ b, err := json.Marshal(user)
+ if err != nil {
+ http.Error(w, err.Error(), 500)
+ return
+ }
+
+ w.Write(b)
+ }
+
+In addition: getting CSRF protection right is important, so here's some background:
+
+ * This library generates unique-per-request (masked) tokens as a mitigation
+ against the [BREACH attack](http://breachattack.com/).
+ * The 'base' (unmasked) token is stored in the session, which means that
+ multiple browser tabs won't cause a user problems as their per-request token
+ is compared with the base token.
+ * Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods
+ (GET, HEAD, OPTIONS, TRACE) are the *only* methods where token validation is not
+ enforced.
+ * The design is based on the battle-tested
+ [Django](https://docs.djangoproject.com/en/1.8/ref/csrf/) and [Ruby on
+ Rails](http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html)
+ approaches.
+ * Cookies are authenticated and based on the [securecookie](https://github.com/gorilla/securecookie)
+ library. They're also Secure (issued over HTTPS only) and are HttpOnly
+ by default, because sane defaults are important.
+ * Go's `crypto/rand` library is used to generate the 32 byte (256 bit) tokens
+ and the one-time-pad used for masking them.
+
+This library does not seek to be adventurous.
+
+*/
+package csrf
diff --git a/vendor/github.com/gorilla/csrf/helpers.go b/vendor/github.com/gorilla/csrf/helpers.go
new file mode 100644
index 0000000..3dacfd2
--- /dev/null
+++ b/vendor/github.com/gorilla/csrf/helpers.go
@@ -0,0 +1,203 @@
+package csrf
+
+import (
+ "crypto/rand"
+ "crypto/subtle"
+ "encoding/base64"
+ "fmt"
+ "html/template"
+ "net/http"
+ "net/url"
+)
+
+// Token returns a masked CSRF token ready for passing into HTML template or
+// a JSON response body. An empty token will be returned if the middleware
+// has not been applied (which will fail subsequent validation).
+func Token(r *http.Request) string {
+ if val, err := contextGet(r, tokenKey); err == nil {
+ if maskedToken, ok := val.(string); ok {
+ return maskedToken
+ }
+ }
+
+ return ""
+}
+
+// FailureReason makes CSRF validation errors available in the request context.
+// This is useful when you want to log the cause of the error or report it to
+// client.
+func FailureReason(r *http.Request) error {
+ if val, err := contextGet(r, errorKey); err == nil {
+ if err, ok := val.(error); ok {
+ return err
+ }
+ }
+
+ return nil
+}
+
+// UnsafeSkipCheck will skip the CSRF check for any requests. This must be
+// called before the CSRF middleware.
+//
+// Note: You should not set this without otherwise securing the request from
+// CSRF attacks. The primary use-case for this function is to turn off CSRF
+// checks for non-browser clients using authorization tokens against your API.
+func UnsafeSkipCheck(r *http.Request) *http.Request {
+ return contextSave(r, skipCheckKey, true)
+}
+
+// TemplateField is a template helper for html/template that provides an field
+// populated with a CSRF token.
+//
+// Example:
+//
+// // The following tag in our form.tmpl template:
+// {{ .csrfField }}
+//
+// // ... becomes:
+//
+//
+func TemplateField(r *http.Request) template.HTML {
+ if name, err := contextGet(r, formKey); err == nil {
+ fragment := fmt.Sprintf(``,
+ name, Token(r))
+
+ return template.HTML(fragment)
+ }
+
+ return template.HTML("")
+}
+
+// mask returns a unique-per-request token to mitigate the BREACH attack
+// as per http://breachattack.com/#mitigations
+//
+// The token is generated by XOR'ing a one-time-pad and the base (session) CSRF
+// token and returning them together as a 64-byte slice. This effectively
+// randomises the token on a per-request basis without breaking multiple browser
+// tabs/windows.
+func mask(realToken []byte, r *http.Request) string {
+ otp, err := generateRandomBytes(tokenLength)
+ if err != nil {
+ return ""
+ }
+
+ // XOR the OTP with the real token to generate a masked token. Append the
+ // OTP to the front of the masked token to allow unmasking in the subsequent
+ // request.
+ return base64.StdEncoding.EncodeToString(append(otp, xorToken(otp, realToken)...))
+}
+
+// unmask splits the issued token (one-time-pad + masked token) and returns the
+// unmasked request token for comparison.
+func unmask(issued []byte) []byte {
+ // Issued tokens are always masked and combined with the pad.
+ if len(issued) != tokenLength*2 {
+ return nil
+ }
+
+ // We now know the length of the byte slice.
+ otp := issued[tokenLength:]
+ masked := issued[:tokenLength]
+
+ // Unmask the token by XOR'ing it against the OTP used to mask it.
+ return xorToken(otp, masked)
+}
+
+// requestToken returns the issued token (pad + masked token) from the HTTP POST
+// body or HTTP header. It will return nil if the token fails to decode.
+func (cs *csrf) requestToken(r *http.Request) []byte {
+ // 1. Check the HTTP header first.
+ issued := r.Header.Get(cs.opts.RequestHeader)
+
+ // 2. Fall back to the POST (form) value.
+ if issued == "" {
+ issued = r.PostFormValue(cs.opts.FieldName)
+ }
+
+ // 3. Finally, fall back to the multipart form (if set).
+ if issued == "" && r.MultipartForm != nil {
+ vals := r.MultipartForm.Value[cs.opts.FieldName]
+
+ if len(vals) > 0 {
+ issued = vals[0]
+ }
+ }
+
+ // Decode the "issued" (pad + masked) token sent in the request. Return a
+ // nil byte slice on a decoding error (this will fail upstream).
+ decoded, err := base64.StdEncoding.DecodeString(issued)
+ if err != nil {
+ return nil
+ }
+
+ return decoded
+}
+
+// generateRandomBytes returns securely generated random bytes.
+// It will return an error if the system's secure random number generator
+// fails to function correctly.
+func generateRandomBytes(n int) ([]byte, error) {
+ b := make([]byte, n)
+ _, err := rand.Read(b)
+ // err == nil only if len(b) == n
+ if err != nil {
+ return nil, err
+ }
+
+ return b, nil
+
+}
+
+// sameOrigin returns true if URLs a and b share the same origin. The same
+// origin is defined as host (which includes the port) and scheme.
+func sameOrigin(a, b *url.URL) bool {
+ return (a.Scheme == b.Scheme && a.Host == b.Host)
+}
+
+// compare securely (constant-time) compares the unmasked token from the request
+// against the real token from the session.
+func compareTokens(a, b []byte) bool {
+ // This is required as subtle.ConstantTimeCompare does not check for equal
+ // lengths in Go versions prior to 1.3.
+ if len(a) != len(b) {
+ return false
+ }
+
+ return subtle.ConstantTimeCompare(a, b) == 1
+}
+
+// xorToken XORs tokens ([]byte) to provide unique-per-request CSRF tokens. It
+// will return a masked token if the base token is XOR'ed with a one-time-pad.
+// An unmasked token will be returned if a masked token is XOR'ed with the
+// one-time-pad used to mask it.
+func xorToken(a, b []byte) []byte {
+ n := len(a)
+ if len(b) < n {
+ n = len(b)
+ }
+
+ res := make([]byte, n)
+
+ for i := 0; i < n; i++ {
+ res[i] = a[i] ^ b[i]
+ }
+
+ return res
+}
+
+// contains is a helper function to check if a string exists in a slice - e.g.
+// whether a HTTP method exists in a list of safe methods.
+func contains(vals []string, s string) bool {
+ for _, v := range vals {
+ if v == s {
+ return true
+ }
+ }
+
+ return false
+}
+
+// envError stores a CSRF error in the request context.
+func envError(r *http.Request, err error) *http.Request {
+ return contextSave(r, errorKey, err)
+}
diff --git a/vendor/github.com/gorilla/csrf/options.go b/vendor/github.com/gorilla/csrf/options.go
new file mode 100644
index 0000000..c644d49
--- /dev/null
+++ b/vendor/github.com/gorilla/csrf/options.go
@@ -0,0 +1,130 @@
+package csrf
+
+import "net/http"
+
+// Option describes a functional option for configuring the CSRF handler.
+type Option func(*csrf)
+
+// MaxAge sets the maximum age (in seconds) of a CSRF token's underlying cookie.
+// Defaults to 12 hours.
+func MaxAge(age int) Option {
+ return func(cs *csrf) {
+ cs.opts.MaxAge = age
+ }
+}
+
+// Domain sets the cookie domain. Defaults to the current domain of the request
+// only (recommended).
+//
+// This should be a hostname and not a URL. If set, the domain is treated as
+// being prefixed with a '.' - e.g. "example.com" becomes ".example.com" and
+// matches "www.example.com" and "secure.example.com".
+func Domain(domain string) Option {
+ return func(cs *csrf) {
+ cs.opts.Domain = domain
+ }
+}
+
+// Path sets the cookie path. Defaults to the path the cookie was issued from
+// (recommended).
+//
+// This instructs clients to only respond with cookie for that path and its
+// subpaths - i.e. a cookie issued from "/register" would be included in requests
+// to "/register/step2" and "/register/submit".
+func Path(p string) Option {
+ return func(cs *csrf) {
+ cs.opts.Path = p
+ }
+}
+
+// Secure sets the 'Secure' flag on the cookie. Defaults to true (recommended).
+// Set this to 'false' in your development environment otherwise the cookie won't
+// be sent over an insecure channel. Setting this via the presence of a 'DEV'
+// environmental variable is a good way of making sure this won't make it to a
+// production environment.
+func Secure(s bool) Option {
+ return func(cs *csrf) {
+ cs.opts.Secure = s
+ }
+}
+
+// HttpOnly sets the 'HttpOnly' flag on the cookie. Defaults to true (recommended).
+func HttpOnly(h bool) Option {
+ return func(cs *csrf) {
+ // Note that the function and field names match the case of the
+ // related http.Cookie field instead of the "correct" HTTPOnly name
+ // that golint suggests.
+ cs.opts.HttpOnly = h
+ }
+}
+
+// ErrorHandler allows you to change the handler called when CSRF request
+// processing encounters an invalid token or request. A typical use would be to
+// provide a handler that returns a static HTML file with a HTTP 403 status. By
+// default a HTTP 403 status and a plain text CSRF failure reason are served.
+//
+// Note that a custom error handler can also access the csrf.Failure(r)
+// function to retrieve the CSRF validation reason from the request context.
+func ErrorHandler(h http.Handler) Option {
+ return func(cs *csrf) {
+ cs.opts.ErrorHandler = h
+ }
+}
+
+// RequestHeader allows you to change the request header the CSRF middleware
+// inspects. The default is X-CSRF-Token.
+func RequestHeader(header string) Option {
+ return func(cs *csrf) {
+ cs.opts.RequestHeader = header
+ }
+}
+
+// FieldName allows you to change the name attribute of the hidden field
+// inspected by this package. The default is 'gorilla.csrf.Token'.
+func FieldName(name string) Option {
+ return func(cs *csrf) {
+ cs.opts.FieldName = name
+ }
+}
+
+// CookieName changes the name of the CSRF cookie issued to clients.
+//
+// Note that cookie names should not contain whitespace, commas, semicolons,
+// backslashes or control characters as per RFC6265.
+func CookieName(name string) Option {
+ return func(cs *csrf) {
+ cs.opts.CookieName = name
+ }
+}
+
+// setStore sets the store used by the CSRF middleware.
+// Note: this is private (for now) to allow for internal API changes.
+func setStore(s store) Option {
+ return func(cs *csrf) {
+ cs.st = s
+ }
+}
+
+// parseOptions parses the supplied options functions and returns a configured
+// csrf handler.
+func parseOptions(h http.Handler, opts ...Option) *csrf {
+ // Set the handler to call after processing.
+ cs := &csrf{
+ h: h,
+ }
+
+ // Default to true. See Secure & HttpOnly function comments for rationale.
+ // Set here to allow package users to override the default.
+ cs.opts.Secure = true
+ cs.opts.HttpOnly = true
+
+ // Range over each options function and apply it
+ // to our csrf type to configure it. Options functions are
+ // applied in order, with any conflicting options overriding
+ // earlier calls.
+ for _, option := range opts {
+ option(cs)
+ }
+
+ return cs
+}
diff --git a/vendor/github.com/gorilla/csrf/store.go b/vendor/github.com/gorilla/csrf/store.go
new file mode 100644
index 0000000..39f47ad
--- /dev/null
+++ b/vendor/github.com/gorilla/csrf/store.go
@@ -0,0 +1,82 @@
+package csrf
+
+import (
+ "net/http"
+ "time"
+
+ "github.com/gorilla/securecookie"
+)
+
+// store represents the session storage used for CSRF tokens.
+type store interface {
+ // Get returns the real CSRF token from the store.
+ Get(*http.Request) ([]byte, error)
+ // Save stores the real CSRF token in the store and writes a
+ // cookie to the http.ResponseWriter.
+ // For non-cookie stores, the cookie should contain a unique (256 bit) ID
+ // or key that references the token in the backend store.
+ // csrf.GenerateRandomBytes is a helper function for generating secure IDs.
+ Save(token []byte, w http.ResponseWriter) error
+}
+
+// cookieStore is a signed cookie session store for CSRF tokens.
+type cookieStore struct {
+ name string
+ maxAge int
+ secure bool
+ httpOnly bool
+ path string
+ domain string
+ sc *securecookie.SecureCookie
+}
+
+// Get retrieves a CSRF token from the session cookie. It returns an empty token
+// if decoding fails (e.g. HMAC validation fails or the named cookie doesn't exist).
+func (cs *cookieStore) Get(r *http.Request) ([]byte, error) {
+ // Retrieve the cookie from the request
+ cookie, err := r.Cookie(cs.name)
+ if err != nil {
+ return nil, err
+ }
+
+ token := make([]byte, tokenLength)
+ // Decode the HMAC authenticated cookie.
+ err = cs.sc.Decode(cs.name, cookie.Value, &token)
+ if err != nil {
+ return nil, err
+ }
+
+ return token, nil
+}
+
+// Save stores the CSRF token in the session cookie.
+func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error {
+ // Generate an encoded cookie value with the CSRF token.
+ encoded, err := cs.sc.Encode(cs.name, token)
+ if err != nil {
+ return err
+ }
+
+ cookie := &http.Cookie{
+ Name: cs.name,
+ Value: encoded,
+ MaxAge: cs.maxAge,
+ HttpOnly: cs.httpOnly,
+ Secure: cs.secure,
+ Path: cs.path,
+ Domain: cs.domain,
+ }
+
+ // Set the Expires field on the cookie based on the MaxAge
+ // If MaxAge <= 0, we don't set the Expires attribute, making the cookie
+ // session-only.
+ if cs.maxAge > 0 {
+ cookie.Expires = time.Now().Add(
+ time.Duration(cs.maxAge) * time.Second)
+ }
+
+ // Write the authenticated cookie to the response.
+ http.SetCookie(w, cookie)
+
+ return nil
+}
diff --git a/vendor/golang.org/x/sys/LICENSE b/vendor/github.com/gorilla/securecookie/LICENSE
similarity index 83%
rename from vendor/golang.org/x/sys/LICENSE
rename to vendor/github.com/gorilla/securecookie/LICENSE
index 6a66aea..0e5fb87 100644
--- a/vendor/golang.org/x/sys/LICENSE
+++ b/vendor/github.com/gorilla/securecookie/LICENSE
@@ -1,16 +1,16 @@
-Copyright (c) 2009 The Go Authors. All rights reserved.
+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
+ * 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
+ * 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
+ * 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.
diff --git a/vendor/github.com/gorilla/securecookie/README.md b/vendor/github.com/gorilla/securecookie/README.md
new file mode 100644
index 0000000..da112e4
--- /dev/null
+++ b/vendor/github.com/gorilla/securecookie/README.md
@@ -0,0 +1,78 @@
+securecookie
+============
+[![GoDoc](https://godoc.org/github.com/gorilla/securecookie?status.svg)](https://godoc.org/github.com/gorilla/securecookie) [![Build Status](https://travis-ci.org/gorilla/securecookie.png?branch=master)](https://travis-ci.org/gorilla/securecookie)
+
+securecookie encodes and decodes authenticated and optionally encrypted
+cookie values.
+
+Secure cookies can't be forged, because their values are validated using HMAC.
+When encrypted, the content is also inaccessible to malicious eyes. It is still
+recommended that sensitive data not be stored in cookies, and that HTTPS be used
+to prevent cookie [replay attacks](https://en.wikipedia.org/wiki/Replay_attack).
+
+## Examples
+
+To use it, first create a new SecureCookie instance:
+
+```go
+// Hash keys should be at least 32 bytes long
+var hashKey = []byte("very-secret")
+// Block keys should be 16 bytes (AES-128) or 32 bytes (AES-256) long.
+// Shorter keys may weaken the encryption used.
+var blockKey = []byte("a-lot-secret")
+var s = securecookie.New(hashKey, blockKey)
+```
+
+The hashKey is required, used to authenticate the cookie value using HMAC.
+It is recommended to use a key with 32 or 64 bytes.
+
+The blockKey is optional, used to encrypt the cookie value -- set it to nil
+to not use encryption. If set, the length must correspond to the block size
+of the encryption algorithm. For AES, used by default, valid lengths are
+16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
+
+Strong keys can be created using the convenience function GenerateRandomKey().
+
+Once a SecureCookie instance is set, use it to encode a cookie value:
+
+```go
+func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
+ value := map[string]string{
+ "foo": "bar",
+ }
+ if encoded, err := s.Encode("cookie-name", value); err == nil {
+ cookie := &http.Cookie{
+ Name: "cookie-name",
+ Value: encoded,
+ Path: "/",
+ Secure: true,
+ HttpOnly: true,
+ }
+ http.SetCookie(w, cookie)
+ }
+}
+```
+
+Later, use the same SecureCookie instance to decode and validate a cookie
+value:
+
+```go
+func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
+ if cookie, err := r.Cookie("cookie-name"); err == nil {
+ value := make(map[string]string)
+ if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil {
+ fmt.Fprintf(w, "The value of foo is %q", value["foo"])
+ }
+ }
+}
+```
+
+We stored a map[string]string, but secure cookies can hold any value that
+can be encoded using `encoding/gob`. To store custom types, they must be
+registered first using gob.Register(). For basic types this is not needed;
+it works out of the box. An optional JSON encoder that uses `encoding/json` is
+available for types compatible with JSON.
+
+## License
+
+BSD licensed. See the LICENSE file for details.
diff --git a/vendor/github.com/gorilla/securecookie/doc.go b/vendor/github.com/gorilla/securecookie/doc.go
new file mode 100644
index 0000000..ae89408
--- /dev/null
+++ b/vendor/github.com/gorilla/securecookie/doc.go
@@ -0,0 +1,61 @@
+// 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 securecookie encodes and decodes authenticated and optionally
+encrypted cookie values.
+
+Secure cookies can't be forged, because their values are validated using HMAC.
+When encrypted, the content is also inaccessible to malicious eyes.
+
+To use it, first create a new SecureCookie instance:
+
+ var hashKey = []byte("very-secret")
+ var blockKey = []byte("a-lot-secret")
+ var s = securecookie.New(hashKey, blockKey)
+
+The hashKey is required, used to authenticate the cookie value using HMAC.
+It is recommended to use a key with 32 or 64 bytes.
+
+The blockKey is optional, used to encrypt the cookie value -- set it to nil
+to not use encryption. If set, the length must correspond to the block size
+of the encryption algorithm. For AES, used by default, valid lengths are
+16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
+
+Strong keys can be created using the convenience function GenerateRandomKey().
+
+Once a SecureCookie instance is set, use it to encode a cookie value:
+
+ func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
+ value := map[string]string{
+ "foo": "bar",
+ }
+ if encoded, err := s.Encode("cookie-name", value); err == nil {
+ cookie := &http.Cookie{
+ Name: "cookie-name",
+ Value: encoded,
+ Path: "/",
+ }
+ http.SetCookie(w, cookie)
+ }
+ }
+
+Later, use the same SecureCookie instance to decode and validate a cookie
+value:
+
+ func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
+ if cookie, err := r.Cookie("cookie-name"); err == nil {
+ value := make(map[string]string)
+ if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil {
+ fmt.Fprintf(w, "The value of foo is %q", value["foo"])
+ }
+ }
+ }
+
+We stored a map[string]string, but secure cookies can hold any value that
+can be encoded using encoding/gob. To store custom types, they must be
+registered first using gob.Register(). For basic types this is not needed;
+it works out of the box.
+*/
+package securecookie
diff --git a/vendor/github.com/gorilla/securecookie/fuzz.go b/vendor/github.com/gorilla/securecookie/fuzz.go
new file mode 100644
index 0000000..e4d0534
--- /dev/null
+++ b/vendor/github.com/gorilla/securecookie/fuzz.go
@@ -0,0 +1,25 @@
+// +build gofuzz
+
+package securecookie
+
+var hashKey = []byte("very-secret12345")
+var blockKey = []byte("a-lot-secret1234")
+var s = New(hashKey, blockKey)
+
+type Cookie struct {
+ B bool
+ I int
+ S string
+}
+
+func Fuzz(data []byte) int {
+ datas := string(data)
+ var c Cookie
+ if err := s.Decode("fuzz", datas, &c); err != nil {
+ return 0
+ }
+ if _, err := s.Encode("fuzz", c); err != nil {
+ panic(err)
+ }
+ return 1
+}
diff --git a/vendor/github.com/gorilla/securecookie/securecookie.go b/vendor/github.com/gorilla/securecookie/securecookie.go
new file mode 100644
index 0000000..83dd606
--- /dev/null
+++ b/vendor/github.com/gorilla/securecookie/securecookie.go
@@ -0,0 +1,646 @@
+// 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 securecookie
+
+import (
+ "bytes"
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/base64"
+ "encoding/gob"
+ "encoding/json"
+ "fmt"
+ "hash"
+ "io"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// Error is the interface of all errors returned by functions in this library.
+type Error interface {
+ error
+
+ // IsUsage returns true for errors indicating the client code probably
+ // uses this library incorrectly. For example, the client may have
+ // failed to provide a valid hash key, or may have failed to configure
+ // the Serializer adequately for encoding value.
+ IsUsage() bool
+
+ // IsDecode returns true for errors indicating that a cookie could not
+ // be decoded and validated. Since cookies are usually untrusted
+ // user-provided input, errors of this type should be expected.
+ // Usually, the proper action is simply to reject the request.
+ IsDecode() bool
+
+ // IsInternal returns true for unexpected errors occurring in the
+ // securecookie implementation.
+ IsInternal() bool
+
+ // Cause, if it returns a non-nil value, indicates that this error was
+ // propagated from some underlying library. If this method returns nil,
+ // this error was raised directly by this library.
+ //
+ // Cause is provided principally for debugging/logging purposes; it is
+ // rare that application logic should perform meaningfully different
+ // logic based on Cause. See, for example, the caveats described on
+ // (MultiError).Cause().
+ Cause() error
+}
+
+// errorType is a bitmask giving the error type(s) of an cookieError value.
+type errorType int
+
+const (
+ usageError = errorType(1 << iota)
+ decodeError
+ internalError
+)
+
+type cookieError struct {
+ typ errorType
+ msg string
+ cause error
+}
+
+func (e cookieError) IsUsage() bool { return (e.typ & usageError) != 0 }
+func (e cookieError) IsDecode() bool { return (e.typ & decodeError) != 0 }
+func (e cookieError) IsInternal() bool { return (e.typ & internalError) != 0 }
+
+func (e cookieError) Cause() error { return e.cause }
+
+func (e cookieError) Error() string {
+ parts := []string{"securecookie: "}
+ if e.msg == "" {
+ parts = append(parts, "error")
+ } else {
+ parts = append(parts, e.msg)
+ }
+ if c := e.Cause(); c != nil {
+ parts = append(parts, " - caused by: ", c.Error())
+ }
+ return strings.Join(parts, "")
+}
+
+var (
+ errGeneratingIV = cookieError{typ: internalError, msg: "failed to generate random iv"}
+
+ errNoCodecs = cookieError{typ: usageError, msg: "no codecs provided"}
+ errHashKeyNotSet = cookieError{typ: usageError, msg: "hash key is not set"}
+ errBlockKeyNotSet = cookieError{typ: usageError, msg: "block key is not set"}
+ errEncodedValueTooLong = cookieError{typ: usageError, msg: "the value is too long"}
+
+ errValueToDecodeTooLong = cookieError{typ: decodeError, msg: "the value is too long"}
+ errTimestampInvalid = cookieError{typ: decodeError, msg: "invalid timestamp"}
+ errTimestampTooNew = cookieError{typ: decodeError, msg: "timestamp is too new"}
+ errTimestampExpired = cookieError{typ: decodeError, msg: "expired timestamp"}
+ errDecryptionFailed = cookieError{typ: decodeError, msg: "the value could not be decrypted"}
+ errValueNotByte = cookieError{typ: decodeError, msg: "value not a []byte."}
+
+ // ErrMacInvalid indicates that cookie decoding failed because the HMAC
+ // could not be extracted and verified. Direct use of this error
+ // variable is deprecated; it is public only for legacy compatibility,
+ // and may be privatized in the future, as it is rarely useful to
+ // distinguish between this error and other Error implementations.
+ ErrMacInvalid = cookieError{typ: decodeError, msg: "the value is not valid"}
+)
+
+// Codec defines an interface to encode and decode cookie values.
+type Codec interface {
+ Encode(name string, value interface{}) (string, error)
+ Decode(name, value string, dst interface{}) error
+}
+
+// New returns a new SecureCookie.
+//
+// hashKey is required, used to authenticate values using HMAC. Create it using
+// GenerateRandomKey(). It is recommended to use a key with 32 or 64 bytes.
+//
+// blockKey is optional, used to encrypt values. Create it using
+// GenerateRandomKey(). The key length must correspond to the block size
+// of the encryption algorithm. For AES, used by default, valid lengths are
+// 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
+// The default encoder used for cookie serialization is encoding/gob.
+//
+// Note that keys created using GenerateRandomKey() are not automatically
+// persisted. New keys will be created when the application is restarted, and
+// previously issued cookies will not be able to be decoded.
+func New(hashKey, blockKey []byte) *SecureCookie {
+ s := &SecureCookie{
+ hashKey: hashKey,
+ blockKey: blockKey,
+ hashFunc: sha256.New,
+ maxAge: 86400 * 30,
+ maxLength: 4096,
+ sz: GobEncoder{},
+ }
+ if hashKey == nil {
+ s.err = errHashKeyNotSet
+ }
+ if blockKey != nil {
+ s.BlockFunc(aes.NewCipher)
+ }
+ return s
+}
+
+// SecureCookie encodes and decodes authenticated and optionally encrypted
+// cookie values.
+type SecureCookie struct {
+ hashKey []byte
+ hashFunc func() hash.Hash
+ blockKey []byte
+ block cipher.Block
+ maxLength int
+ maxAge int64
+ minAge int64
+ err error
+ sz Serializer
+ // For testing purposes, the function that returns the current timestamp.
+ // If not set, it will use time.Now().UTC().Unix().
+ timeFunc func() int64
+}
+
+// Serializer provides an interface for providing custom serializers for cookie
+// values.
+type Serializer interface {
+ Serialize(src interface{}) ([]byte, error)
+ Deserialize(src []byte, dst interface{}) error
+}
+
+// GobEncoder encodes cookie values using encoding/gob. This is the simplest
+// encoder and can handle complex types via gob.Register.
+type GobEncoder struct{}
+
+// JSONEncoder encodes cookie values using encoding/json. Users who wish to
+// encode complex types need to satisfy the json.Marshaller and
+// json.Unmarshaller interfaces.
+type JSONEncoder struct{}
+
+// NopEncoder does not encode cookie values, and instead simply accepts a []byte
+// (as an interface{}) and returns a []byte. This is particularly useful when
+// you encoding an object upstream and do not wish to re-encode it.
+type NopEncoder struct{}
+
+// MaxLength restricts the maximum length, in bytes, for the cookie value.
+//
+// Default is 4096, which is the maximum value accepted by Internet Explorer.
+func (s *SecureCookie) MaxLength(value int) *SecureCookie {
+ s.maxLength = value
+ return s
+}
+
+// MaxAge restricts the maximum age, in seconds, for the cookie value.
+//
+// Default is 86400 * 30. Set it to 0 for no restriction.
+func (s *SecureCookie) MaxAge(value int) *SecureCookie {
+ s.maxAge = int64(value)
+ return s
+}
+
+// MinAge restricts the minimum age, in seconds, for the cookie value.
+//
+// Default is 0 (no restriction).
+func (s *SecureCookie) MinAge(value int) *SecureCookie {
+ s.minAge = int64(value)
+ return s
+}
+
+// HashFunc sets the hash function used to create HMAC.
+//
+// Default is crypto/sha256.New.
+func (s *SecureCookie) HashFunc(f func() hash.Hash) *SecureCookie {
+ s.hashFunc = f
+ return s
+}
+
+// BlockFunc sets the encryption function used to create a cipher.Block.
+//
+// Default is crypto/aes.New.
+func (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie {
+ if s.blockKey == nil {
+ s.err = errBlockKeyNotSet
+ } else if block, err := f(s.blockKey); err == nil {
+ s.block = block
+ } else {
+ s.err = cookieError{cause: err, typ: usageError}
+ }
+ return s
+}
+
+// Encoding sets the encoding/serialization method for cookies.
+//
+// Default is encoding/gob. To encode special structures using encoding/gob,
+// they must be registered first using gob.Register().
+func (s *SecureCookie) SetSerializer(sz Serializer) *SecureCookie {
+ s.sz = sz
+
+ return s
+}
+
+// Encode encodes a cookie value.
+//
+// It serializes, optionally encrypts, signs with a message authentication code,
+// and finally encodes the value.
+//
+// The name argument is the cookie name. It is stored with the encoded value.
+// The value argument is the value to be encoded. It can be any value that can
+// be encoded using the currently selected serializer; see SetSerializer().
+//
+// It is the client's responsibility to ensure that value, when encoded using
+// the current serialization/encryption settings on s and then base64-encoded,
+// is shorter than the maximum permissible length.
+func (s *SecureCookie) Encode(name string, value interface{}) (string, error) {
+ if s.err != nil {
+ return "", s.err
+ }
+ if s.hashKey == nil {
+ s.err = errHashKeyNotSet
+ return "", s.err
+ }
+ var err error
+ var b []byte
+ // 1. Serialize.
+ if b, err = s.sz.Serialize(value); err != nil {
+ return "", cookieError{cause: err, typ: usageError}
+ }
+ // 2. Encrypt (optional).
+ if s.block != nil {
+ if b, err = encrypt(s.block, b); err != nil {
+ return "", cookieError{cause: err, typ: usageError}
+ }
+ }
+ b = encode(b)
+ // 3. Create MAC for "name|date|value". Extra pipe to be used later.
+ b = []byte(fmt.Sprintf("%s|%d|%s|", name, s.timestamp(), b))
+ mac := createMac(hmac.New(s.hashFunc, s.hashKey), b[:len(b)-1])
+ // Append mac, remove name.
+ b = append(b, mac...)[len(name)+1:]
+ // 4. Encode to base64.
+ b = encode(b)
+ // 5. Check length.
+ if s.maxLength != 0 && len(b) > s.maxLength {
+ return "", errEncodedValueTooLong
+ }
+ // Done.
+ return string(b), nil
+}
+
+// Decode decodes a cookie value.
+//
+// It decodes, verifies a message authentication code, optionally decrypts and
+// finally deserializes the value.
+//
+// The name argument is the cookie name. It must be the same name used when
+// it was stored. The value argument is the encoded cookie value. The dst
+// argument is where the cookie will be decoded. It must be a pointer.
+func (s *SecureCookie) Decode(name, value string, dst interface{}) error {
+ if s.err != nil {
+ return s.err
+ }
+ if s.hashKey == nil {
+ s.err = errHashKeyNotSet
+ return s.err
+ }
+ // 1. Check length.
+ if s.maxLength != 0 && len(value) > s.maxLength {
+ return errValueToDecodeTooLong
+ }
+ // 2. Decode from base64.
+ b, err := decode([]byte(value))
+ if err != nil {
+ return err
+ }
+ // 3. Verify MAC. Value is "date|value|mac".
+ parts := bytes.SplitN(b, []byte("|"), 3)
+ if len(parts) != 3 {
+ return ErrMacInvalid
+ }
+ h := hmac.New(s.hashFunc, s.hashKey)
+ b = append([]byte(name+"|"), b[:len(b)-len(parts[2])-1]...)
+ if err = verifyMac(h, b, parts[2]); err != nil {
+ return err
+ }
+ // 4. Verify date ranges.
+ var t1 int64
+ if t1, err = strconv.ParseInt(string(parts[0]), 10, 64); err != nil {
+ return errTimestampInvalid
+ }
+ t2 := s.timestamp()
+ if s.minAge != 0 && t1 > t2-s.minAge {
+ return errTimestampTooNew
+ }
+ if s.maxAge != 0 && t1 < t2-s.maxAge {
+ return errTimestampExpired
+ }
+ // 5. Decrypt (optional).
+ b, err = decode(parts[1])
+ if err != nil {
+ return err
+ }
+ if s.block != nil {
+ if b, err = decrypt(s.block, b); err != nil {
+ return err
+ }
+ }
+ // 6. Deserialize.
+ if err = s.sz.Deserialize(b, dst); err != nil {
+ return cookieError{cause: err, typ: decodeError}
+ }
+ // Done.
+ return nil
+}
+
+// timestamp returns the current timestamp, in seconds.
+//
+// For testing purposes, the function that generates the timestamp can be
+// overridden. If not set, it will return time.Now().UTC().Unix().
+func (s *SecureCookie) timestamp() int64 {
+ if s.timeFunc == nil {
+ return time.Now().UTC().Unix()
+ }
+ return s.timeFunc()
+}
+
+// Authentication -------------------------------------------------------------
+
+// createMac creates a message authentication code (MAC).
+func createMac(h hash.Hash, value []byte) []byte {
+ h.Write(value)
+ return h.Sum(nil)
+}
+
+// verifyMac verifies that a message authentication code (MAC) is valid.
+func verifyMac(h hash.Hash, value []byte, mac []byte) error {
+ mac2 := createMac(h, value)
+ // Check that both MACs are of equal length, as subtle.ConstantTimeCompare
+ // does not do this prior to Go 1.4.
+ if len(mac) == len(mac2) && subtle.ConstantTimeCompare(mac, mac2) == 1 {
+ return nil
+ }
+ return ErrMacInvalid
+}
+
+// Encryption -----------------------------------------------------------------
+
+// encrypt encrypts a value using the given block in counter mode.
+//
+// A random initialization vector (http://goo.gl/zF67k) with the length of the
+// block size is prepended to the resulting ciphertext.
+func encrypt(block cipher.Block, value []byte) ([]byte, error) {
+ iv := GenerateRandomKey(block.BlockSize())
+ if iv == nil {
+ return nil, errGeneratingIV
+ }
+ // Encrypt it.
+ stream := cipher.NewCTR(block, iv)
+ stream.XORKeyStream(value, value)
+ // Return iv + ciphertext.
+ return append(iv, value...), nil
+}
+
+// decrypt decrypts a value using the given block in counter mode.
+//
+// The value to be decrypted must be prepended by a initialization vector
+// (http://goo.gl/zF67k) with the length of the block size.
+func decrypt(block cipher.Block, value []byte) ([]byte, error) {
+ size := block.BlockSize()
+ if len(value) > size {
+ // Extract iv.
+ iv := value[:size]
+ // Extract ciphertext.
+ value = value[size:]
+ // Decrypt it.
+ stream := cipher.NewCTR(block, iv)
+ stream.XORKeyStream(value, value)
+ return value, nil
+ }
+ return nil, errDecryptionFailed
+}
+
+// Serialization --------------------------------------------------------------
+
+// Serialize encodes a value using gob.
+func (e GobEncoder) Serialize(src interface{}) ([]byte, error) {
+ buf := new(bytes.Buffer)
+ enc := gob.NewEncoder(buf)
+ if err := enc.Encode(src); err != nil {
+ return nil, cookieError{cause: err, typ: usageError}
+ }
+ return buf.Bytes(), nil
+}
+
+// Deserialize decodes a value using gob.
+func (e GobEncoder) Deserialize(src []byte, dst interface{}) error {
+ dec := gob.NewDecoder(bytes.NewBuffer(src))
+ if err := dec.Decode(dst); err != nil {
+ return cookieError{cause: err, typ: decodeError}
+ }
+ return nil
+}
+
+// Serialize encodes a value using encoding/json.
+func (e JSONEncoder) Serialize(src interface{}) ([]byte, error) {
+ buf := new(bytes.Buffer)
+ enc := json.NewEncoder(buf)
+ if err := enc.Encode(src); err != nil {
+ return nil, cookieError{cause: err, typ: usageError}
+ }
+ return buf.Bytes(), nil
+}
+
+// Deserialize decodes a value using encoding/json.
+func (e JSONEncoder) Deserialize(src []byte, dst interface{}) error {
+ dec := json.NewDecoder(bytes.NewReader(src))
+ if err := dec.Decode(dst); err != nil {
+ return cookieError{cause: err, typ: decodeError}
+ }
+ return nil
+}
+
+// Serialize passes a []byte through as-is.
+func (e NopEncoder) Serialize(src interface{}) ([]byte, error) {
+ if b, ok := src.([]byte); ok {
+ return b, nil
+ }
+
+ return nil, errValueNotByte
+}
+
+// Deserialize passes a []byte through as-is.
+func (e NopEncoder) Deserialize(src []byte, dst interface{}) error {
+ if _, ok := dst.([]byte); ok {
+ dst = src
+ return nil
+ }
+
+ return errValueNotByte
+}
+
+// Encoding -------------------------------------------------------------------
+
+// encode encodes a value using base64.
+func encode(value []byte) []byte {
+ encoded := make([]byte, base64.URLEncoding.EncodedLen(len(value)))
+ base64.URLEncoding.Encode(encoded, value)
+ return encoded
+}
+
+// decode decodes a cookie using base64.
+func decode(value []byte) ([]byte, error) {
+ decoded := make([]byte, base64.URLEncoding.DecodedLen(len(value)))
+ b, err := base64.URLEncoding.Decode(decoded, value)
+ if err != nil {
+ return nil, cookieError{cause: err, typ: decodeError, msg: "base64 decode failed"}
+ }
+ return decoded[:b], nil
+}
+
+// Helpers --------------------------------------------------------------------
+
+// GenerateRandomKey creates a random key with the given length in bytes.
+// On failure, returns nil.
+//
+// Callers should explicitly check for the possibility of a nil return, treat
+// it as a failure of the system random number generator, and not continue.
+func GenerateRandomKey(length int) []byte {
+ k := make([]byte, length)
+ if _, err := io.ReadFull(rand.Reader, k); err != nil {
+ return nil
+ }
+ return k
+}
+
+// CodecsFromPairs returns a slice of SecureCookie instances.
+//
+// It is a convenience function to create a list of codecs for key rotation. Note
+// that the generated Codecs will have the default options applied: callers
+// should iterate over each Codec and type-assert the underlying *SecureCookie to
+// change these.
+//
+// Example:
+//
+// codecs := securecookie.CodecsFromPairs(
+// []byte("new-hash-key"),
+// []byte("new-block-key"),
+// []byte("old-hash-key"),
+// []byte("old-block-key"),
+// )
+//
+// // Modify each instance.
+// for _, s := range codecs {
+// if cookie, ok := s.(*securecookie.SecureCookie); ok {
+// cookie.MaxAge(86400 * 7)
+// cookie.SetSerializer(securecookie.JSONEncoder{})
+// cookie.HashFunc(sha512.New512_256)
+// }
+// }
+//
+func CodecsFromPairs(keyPairs ...[]byte) []Codec {
+ codecs := make([]Codec, len(keyPairs)/2+len(keyPairs)%2)
+ for i := 0; i < len(keyPairs); i += 2 {
+ var blockKey []byte
+ if i+1 < len(keyPairs) {
+ blockKey = keyPairs[i+1]
+ }
+ codecs[i/2] = New(keyPairs[i], blockKey)
+ }
+ return codecs
+}
+
+// EncodeMulti encodes a cookie value using a group of codecs.
+//
+// The codecs are tried in order. Multiple codecs are accepted to allow
+// key rotation.
+//
+// On error, may return a MultiError.
+func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) {
+ if len(codecs) == 0 {
+ return "", errNoCodecs
+ }
+
+ var errors MultiError
+ for _, codec := range codecs {
+ encoded, err := codec.Encode(name, value)
+ if err == nil {
+ return encoded, nil
+ }
+ errors = append(errors, err)
+ }
+ return "", errors
+}
+
+// DecodeMulti decodes a cookie value using a group of codecs.
+//
+// The codecs are tried in order. Multiple codecs are accepted to allow
+// key rotation.
+//
+// On error, may return a MultiError.
+func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error {
+ if len(codecs) == 0 {
+ return errNoCodecs
+ }
+
+ var errors MultiError
+ for _, codec := range codecs {
+ err := codec.Decode(name, value, dst)
+ if err == nil {
+ return nil
+ }
+ errors = append(errors, err)
+ }
+ return errors
+}
+
+// MultiError groups multiple errors.
+type MultiError []error
+
+func (m MultiError) IsUsage() bool { return m.any(func(e Error) bool { return e.IsUsage() }) }
+func (m MultiError) IsDecode() bool { return m.any(func(e Error) bool { return e.IsDecode() }) }
+func (m MultiError) IsInternal() bool { return m.any(func(e Error) bool { return e.IsInternal() }) }
+
+// Cause returns nil for MultiError; there is no unique underlying cause in the
+// general case.
+//
+// Note: we could conceivably return a non-nil Cause only when there is exactly
+// one child error with a Cause. However, it would be brittle for client code
+// to rely on the arity of causes inside a MultiError, so we have opted not to
+// provide this functionality. Clients which really wish to access the Causes
+// of the underlying errors are free to iterate through the errors themselves.
+func (m MultiError) Cause() error { return nil }
+
+func (m MultiError) Error() string {
+ s, n := "", 0
+ for _, e := range m {
+ if e != nil {
+ if n == 0 {
+ s = e.Error()
+ }
+ n++
+ }
+ }
+ switch n {
+ case 0:
+ return "(0 errors)"
+ case 1:
+ return s
+ case 2:
+ return s + " (and 1 other error)"
+ }
+ return fmt.Sprintf("%s (and %d other errors)", s, n-1)
+}
+
+// any returns true if any element of m is an Error for which pred returns true.
+func (m MultiError) any(pred func(Error) bool) bool {
+ for _, e := range m {
+ if ourErr, ok := e.(Error); ok && pred(ourErr) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/vendor/github.com/gravitational/configure/.gitignore b/vendor/github.com/gravitational/configure/.gitignore
deleted file mode 100644
index 26f60be..0000000
--- a/vendor/github.com/gravitational/configure/.gitignore
+++ /dev/null
@@ -1,25 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-*.prof
-*.flymake
diff --git a/vendor/github.com/gravitational/configure/LICENSE b/vendor/github.com/gravitational/configure/LICENSE
deleted file mode 100644
index 9faf6ba..0000000
--- a/vendor/github.com/gravitational/configure/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
-Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright 2015 Gravitational, 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.
\ No newline at end of file
diff --git a/vendor/github.com/gravitational/configure/Makefile b/vendor/github.com/gravitational/configure/Makefile
deleted file mode 100644
index 74017e0..0000000
--- a/vendor/github.com/gravitational/configure/Makefile
+++ /dev/null
@@ -1,13 +0,0 @@
-.PHONY: test test-package remove-temp-files sloccount
-
-test: remove-temp-files
- go test -v -test.parallel=0 ./... -cover
-
-test-package: remove-temp-files
- go test -v -test.parallel=0 ./$(p)
-
-remove-temp-files:
- find . -name flymake_* -delete
-
-sloccount:
- find . -path ./Godeps -prune -o -name "*.go" -print0 | xargs -0 wc -l
diff --git a/vendor/github.com/gravitational/configure/README.md b/vendor/github.com/gravitational/configure/README.md
deleted file mode 100644
index dffb070..0000000
--- a/vendor/github.com/gravitational/configure/README.md
+++ /dev/null
@@ -1,43 +0,0 @@
-# Configure
-
-`configure` is a golang library that populates a struct from environment variables, command line arguments and YAML files.
-It works by reading a struct definition with special tags.
-
-### Usage
-
-The latest can be seen if you run:
-```
-godoc github.com/gravitational/configure
-```
-
-But here's a quickstart: Define a sample structure, for example:
-```go
-
- type Config struct {
- StringVar string `env:"STRING_VAR" cli:"string-var" yaml:"string_var"`
- BoolVar bool `env:"BOOL_VAR" cli:"bool_var" yaml:"bool_var"`
- IntVar int `env:"INT_VAR" cli:"int_var" yaml:"int_var"`
- HexVar hexType `env:"HEX_VAR" cli:"hex_var" yaml:"hex_var"`
- MapVar map[string]string `env:"MAP_VAR" cli:"map_var" yaml:"map_var,flow"`
- SliceMapVar []map[string]string `env:"SLICE_MAP_VAR" cli:"slice_var" yaml:"slice_var,flow"`
- }
-```
-
-Then you can query the environment and populate that structure from environment variables, YAML files or command line arguments.
-
-```go
- import (
- "os"
- "github.com/gravitational/configure"
- )
-
- func main() {
- var cfg Config
- // parse environment variables
- err := configure.ParseEnv(&cfg)
- // parse YAML
- err = configure.ParseYAML(&cfg)
- // parse command line arguments
- err = configure.ParseCommandLine(&cfg, os.Args[1:])
- }
-```
diff --git a/vendor/github.com/gravitational/configure/cli.go b/vendor/github.com/gravitational/configure/cli.go
deleted file mode 100644
index e0ae520..0000000
--- a/vendor/github.com/gravitational/configure/cli.go
+++ /dev/null
@@ -1,277 +0,0 @@
-/*
-Copyright 2015 Gravitational, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-package configure
-
-import (
- "fmt"
- "reflect"
- "strconv"
- "strings"
-
- "github.com/gravitational/configure/cstrings"
- "github.com/gravitational/trace"
- "gopkg.in/alecthomas/kingpin.v2"
-)
-
-// ParseCommandLine takes a pointer to a function and attempts
-// to initialize it from environment variables.
-func ParseCommandLine(v interface{}, args []string) error {
- app, err := NewCommandLineApp(v)
- if err != nil {
- return trace.Wrap(err)
- }
- if _, err := app.Parse(args); err != nil {
- return trace.Wrap(err)
- }
- return nil
-}
-
-// NewCommandLineApp generates a command line parsing tool based on the struct
-// that was passed in as a parameter
-func NewCommandLineApp(v interface{}) (*kingpin.Application, error) {
- s := reflect.ValueOf(v).Elem()
- app := kingpin.New("app", "Auto generated command line application")
- if err := setupApp(app, s); err != nil {
- return nil, trace.Wrap(err)
- }
- return app, nil
-}
-
-// CLISetter is an interface for setting any value from command line flag
-type CLISetter interface {
- SetCLI(string) error
-}
-
-func setupApp(app *kingpin.Application, v reflect.Value) error {
- // for structs, walk every element and parse
- vType := v.Type()
- if v.Kind() != reflect.Struct {
- return nil
- }
- for i := 0; i < v.NumField(); i++ {
- structField := vType.Field(i)
- field := v.Field(i)
- if !field.CanSet() {
- continue
- }
- kind := field.Kind()
- if kind == reflect.Struct {
- if err := setupApp(app, field); err != nil {
- return trace.Wrap(err,
- fmt.Sprintf("failed parsing struct field %v",
- structField.Name))
- }
- }
- cliFlag := structField.Tag.Get("cli")
- if cliFlag == "" {
- continue
- }
- if !field.CanAddr() {
- continue
- }
- f := app.Flag(cliFlag, cliFlag)
- fieldPtr := field.Addr().Interface()
- if setter, ok := fieldPtr.(CLISetter); ok {
- f.SetValue(&cliValue{setter: setter})
- continue
- }
- if setter, ok := fieldPtr.(StringSetter); ok {
- f.SetValue(&cliValue{setter: &cliStringSetter{setter: setter}})
- continue
- }
- switch ptr := fieldPtr.(type) {
- case *map[string]string:
- f.SetValue(&cliMapValue{v: ptr})
- continue
- case *[]map[string]string:
- f.SetValue(&cliSliceMapValue{v: ptr})
- continue
- case *int:
- f.SetValue(&cliIntValue{v: ptr})
- continue
- case *int32:
- f.SetValue(&cliInt32Value{v: ptr})
- continue
- case *int64:
- f.SetValue(&cliInt64Value{v: ptr})
- continue
- case *string:
- f.SetValue(&cliStringValue{v: ptr})
- case *bool:
- f.SetValue(&cliBoolValue{v: ptr})
- default:
- return trace.Errorf("unsupported type: %T", ptr)
- }
- }
- return nil
-}
-
-type cliStringSetter struct {
- setter StringSetter
-}
-
-func (s *cliStringSetter) SetCLI(v string) error {
- return s.setter.Set(v)
-}
-
-type cliValue struct {
- setter CLISetter
-}
-
-func (c *cliValue) String() string {
- return ""
-}
-
-func (c *cliValue) Set(v string) error {
- return c.setter.SetCLI(v)
-}
-
-type cliMapValue struct {
- v *map[string]string
-}
-
-func (c *cliMapValue) IsCumulative() bool {
- return true
-}
-
-func (c *cliMapValue) String() string {
- return ""
-}
-
-func (c *cliMapValue) Set(v string) error {
- return setMap(c.v, v)
-}
-
-func setMap(kv *map[string]string, val string) error {
- if len(*kv) == 0 {
- *kv = make(map[string]string)
- }
- for _, i := range cstrings.SplitComma(val) {
- vals := strings.SplitN(i, ":", 2)
- if len(vals) != 2 {
- return trace.Errorf("extra options should be defined like KEY:VAL")
- }
- (*kv)[vals[0]] = vals[1]
- }
- return nil
-}
-
-type cliSliceMapValue struct {
- v *[]map[string]string
-}
-
-func (c *cliSliceMapValue) String() string {
- return ""
-}
-
-func (c *cliSliceMapValue) IsCumulative() bool {
- return true
-}
-
-func (c *cliSliceMapValue) Set(v string) error {
- if len(*c.v) == 0 {
- (*c.v) = make([]map[string]string, 0)
- }
- var kv map[string]string
- if err := setMap(&kv, v); err != nil {
- return trace.Wrap(err)
- }
- *c.v = append(*c.v, kv)
- return nil
-}
-
-type cliStringValue struct {
- v *string
-}
-
-func (c *cliStringValue) String() string {
- return *c.v
-}
-
-func (c *cliStringValue) Set(v string) error {
- *c.v = v
- return nil
-}
-
-type cliIntValue struct {
- v *int
-}
-
-func (c *cliIntValue) String() string {
- return fmt.Sprintf("%v", *c.v)
-}
-
-func (c *cliIntValue) Set(v string) error {
- intValue, err := strconv.ParseInt(v, 0, 0)
- if err != nil {
- return trace.Wrap(err)
- }
- *c.v = int(intValue)
- return nil
-}
-
-type cliInt64Value struct {
- v *int64
- bits int
-}
-
-func (c *cliInt64Value) String() string {
- return fmt.Sprintf("%v", *c.v)
-}
-
-func (c *cliInt64Value) Set(v string) error {
- intValue, err := strconv.ParseInt(v, 0, 64)
- if err != nil {
- return trace.Wrap(err)
- }
- *c.v = intValue
- return nil
-}
-
-type cliInt32Value struct {
- v *int32
- bits int
-}
-
-func (c *cliInt32Value) String() string {
- return fmt.Sprintf("%v", *c.v)
-}
-
-func (c *cliInt32Value) Set(v string) error {
- intValue, err := strconv.ParseInt(v, 0, 32)
- if err != nil {
- return trace.Wrap(err)
- }
- *c.v = int32(intValue)
- return nil
-}
-
-type cliBoolValue struct {
- v *bool
-}
-
-func (c *cliBoolValue) String() string {
- return fmt.Sprintf("%v", *c.v)
-}
-
-func (c *cliBoolValue) Set(v string) error {
- boolVal, err := strconv.ParseBool(v)
- if err != nil {
- return trace.Wrap(err)
- }
- *c.v = boolVal
- return nil
-}
diff --git a/vendor/github.com/gravitational/configure/cstrings/domain.go b/vendor/github.com/gravitational/configure/cstrings/domain.go
deleted file mode 100644
index 78bd707..0000000
--- a/vendor/github.com/gravitational/configure/cstrings/domain.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package cstrings
-
-// IsValidDomainName is a primitive domain name checker
-// taken from go standard library
-func IsValidDomainName(s string) bool {
- // See RFC 1035, RFC 3696.
- if len(s) == 0 {
- return false
- }
- if len(s) > 255 {
- return false
- }
-
- last := byte('.')
- ok := false // Ok once we've seen a letter.
- partlen := 0
- for i := 0; i < len(s); i++ {
- c := s[i]
- switch {
- default:
- return false
- case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_':
- ok = true
- partlen++
- case '0' <= c && c <= '9':
- // fine
- partlen++
- case c == '-':
- // Byte before dash cannot be dot.
- if last == '.' {
- return false
- }
- partlen++
- case c == '.':
- // Byte before dot cannot be dot, dash.
- if last == '.' || last == '-' {
- return false
- }
- if partlen > 63 || partlen == 0 {
- return false
- }
- partlen = 0
- }
- last = c
- }
- if last == '-' || partlen > 63 {
- return false
- }
-
- return ok
-}
diff --git a/vendor/github.com/gravitational/configure/cstrings/split.go b/vendor/github.com/gravitational/configure/cstrings/split.go
deleted file mode 100644
index b379263..0000000
--- a/vendor/github.com/gravitational/configure/cstrings/split.go
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
-Copyright 2015 Gravitational, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-package cstrings
-
-import (
- "bufio"
- "strings"
- "unicode/utf8"
-)
-
-// SplitComma splits a comma-delimted string, comma can be escaped
-// using '\' escape rune.
-func SplitComma(v string) []string {
- return Split(',', '\\', v)
-}
-
-// Split splits the string v using delimiter rune. Rune can be escaped
-// if prefixed with the escape rune.
-func Split(delim, escape rune, v string) []string {
- if delim == 0 || escape == 0 {
- return []string{v}
- }
- scanner := bufio.NewScanner(strings.NewReader(v))
- s := &splitter{delim: delim, escape: escape}
- scanner.Split(s.scan)
-
- out := []string{}
- for scanner.Scan() {
- out = append(out, scanner.Text())
- }
- return out
-}
-
-// SplitAt splits array of strings at a given separator
-func SplitAt(args []string, sep string) ([]string, []string) {
- index := -1
- for i, a := range args {
- if a == sep {
- index = i
- break
- }
- }
- if index == -1 {
- return args, []string{}
- }
- return args[:index], args[index+1:]
-}
-
-// WithoutFlag removes the flag from the argument list
-func WithoutFlag(args []string, flag string) []string {
- out := make([]string, 0, len(args))
- for i := 0; i < len(args); i += 1 {
- val := args[i]
- if !strings.HasPrefix(val, flag) {
- out = append(out, val)
- } else {
- if !strings.Contains(val, "=") && i+1 <= len(args)-1 {
- i += 1
- }
- }
- }
- return out
-}
-
-type splitter struct {
- delim rune
- escape rune
- prev rune
-}
-
-func (s *splitter) scan(data []byte, atEOF bool) (advance int, token []byte, err error) {
- // scan until first unescaped delimiter and return token
- idx := 0
- var r rune
- for width := 0; idx < len(data); idx += width {
- r, width = utf8.DecodeRune(data[idx:])
- if r == s.delim && s.prev != s.escape && idx != 0 {
- s.prev = r
- return idx + width, data[:idx], nil
- }
- s.prev = r
- }
-
- // If we're at EOF, we have a final, non-empty, non-terminated chunk
- if atEOF && idx != 0 {
- return len(data), data[:idx], nil
- }
- // Request more data.
- return 0, nil, nil
-}
diff --git a/vendor/github.com/gravitational/configure/cstrings/user.go b/vendor/github.com/gravitational/configure/cstrings/user.go
deleted file mode 100644
index 8ea47dd..0000000
--- a/vendor/github.com/gravitational/configure/cstrings/user.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package cstrings
-
-import (
- "regexp"
-)
-
-var usersRe = regexp.MustCompile("^[a-z_][a-z0-9_-]*$")
-
-// IsValidUnixUser returns true if passed string appears to
-func IsValidUnixUser(u string) bool {
- if len(u) > 32 {
- return false
- }
- return usersRe.MatchString(u)
-}
diff --git a/vendor/github.com/gravitational/configure/doc.go b/vendor/github.com/gravitational/configure/doc.go
deleted file mode 100644
index 0aa6c1e..0000000
--- a/vendor/github.com/gravitational/configure/doc.go
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
-Copyright 2015 Gravitational, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-// Package configure generates configuration tools based on a struct
-// definition with tags. It can read a configuration for a struct
-// from YAML, environment variables and command line.
-//
-// Given the struct definition:
-//
-// type Config struct {
-// StringVar string `env:"TEST_STRING_VAR" cli:"string" yaml:"string"`
-// BoolVar bool `env:"TEST_BOOL_VAR" cli:"bool" yaml:"bool"`
-// IntVar int `env:"TEST_INT_VAR" cli:"int" yaml:"int"`
-// HexVar hexType `env:"TEST_HEX_VAR" cli:"hex" yaml:"hex"`
-// MapVar map[string]string `env:"TEST_MAP_VAR" cli:"map" yaml:"map,flow"`
-// SliceMapVar []map[string]string `env:"TEST_SLICE_MAP_VAR" cli:"slice" yaml:"slice,flow"`
-// }
-//
-// You can start initializing the struct from YAML, command line or environment:
-//
-// import (
-// "os"
-//
-// "github.com/gravitational/configure"
-// )
-//
-// func main() {
-// var cfg Config
-// // parse environment variables
-// err := configure.ParseEnv(&cfg)
-// // parse YAML
-// err = configure.ParseYAML(&cfg)
-// // parse command line arguments
-// err = configure.ParseCommandLine(&cfg, os.Ars[1:])
-// }
-package configure
diff --git a/vendor/github.com/gravitational/configure/env.go b/vendor/github.com/gravitational/configure/env.go
deleted file mode 100644
index 4229ecb..0000000
--- a/vendor/github.com/gravitational/configure/env.go
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
-Copyright 2015 Gravitational, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-package configure
-
-import (
- "fmt"
- "os"
- "reflect"
- "strconv"
- "strings"
-
- "github.com/gravitational/trace"
-)
-
-// ParseEnv takes a pointer to a struct and attempts
-// to initialize it from environment variables.
-func ParseEnv(v interface{}) error {
- env, err := parseEnvironment()
- if err != nil {
- return err
- }
- s := reflect.ValueOf(v).Elem()
- return setEnv(s, env)
-}
-
-// Setter is an interface that properties of struct can implement
-// to initialize the value of any struct from string
-type EnvSetter interface {
- SetEnv(string) error
-}
-
-// StringSetter is an interface that allows to set variable from any string
-type StringSetter interface {
- Set(string) error
-}
-
-func setEnv(v reflect.Value, env map[string]string) error {
- // for structs, walk every element and parse
- vType := v.Type()
- if v.Kind() != reflect.Struct {
- return nil
- }
- for i := 0; i < v.NumField(); i++ {
- structField := vType.Field(i)
- field := v.Field(i)
- if !field.CanSet() {
- continue
- }
- kind := field.Kind()
- if kind == reflect.Struct {
- if err := setEnv(field, env); err != nil {
- return trace.Wrap(err,
- fmt.Sprintf("failed parsing struct field %v",
- structField.Name))
- }
- }
- envKey := structField.Tag.Get("env")
-
- if envKey == "" {
- continue
- }
- val, ok := env[envKey]
- if !ok || val == "" { // assume defaults
- continue
- }
- if field.CanAddr() {
- if s, ok := field.Addr().Interface().(EnvSetter); ok {
- if err := s.SetEnv(val); err != nil {
- return trace.Wrap(err)
- }
- continue
- }
- if s, ok := field.Addr().Interface().(StringSetter); ok {
- if err := s.Set(val); err != nil {
- return trace.Wrap(err)
- }
- continue
- }
- }
- switch kind {
- case reflect.Slice:
- if _, ok := field.Interface().([]map[string]string); ok {
- var kv KeyValSlice
- if err := kv.SetEnv(val); err != nil {
- return trace.Wrap(err, "error parsing key value list")
- }
- field.Set(reflect.ValueOf([]map[string]string(kv)))
- }
- case reflect.Map:
- if _, ok := field.Interface().(map[string]string); ok {
- var kv KeyVal
- if err := kv.SetEnv(val); err != nil {
- return trace.Wrap(err, "error parsing key value list")
- }
- field.Set(reflect.ValueOf(map[string]string(kv)))
- }
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- intValue, err := strconv.ParseInt(val, 0, field.Type().Bits())
- if err != nil {
- return trace.Wrap(err)
- }
- field.SetInt(intValue)
- case reflect.String:
- field.SetString(val)
- case reflect.Bool:
- boolVal, err := strconv.ParseBool(val)
- if err != nil {
- return trace.Wrap(
- err,
- fmt.Sprintf("failed parsing struct field %v, expected bool, got '%v'",
- structField.Name, val))
- }
- field.SetBool(boolVal)
- }
- }
- return nil
-}
-
-func parseEnvironment() (map[string]string, error) {
- values := os.Environ()
- env := make(map[string]string, len(values))
- for _, v := range values {
- vals := strings.SplitN(v, "=", 2)
- if len(vals) != 2 {
- return nil, trace.Errorf("failed to parse variable: '%v'", v)
- }
- env[vals[0]] = vals[1]
- }
- return env, nil
-}
diff --git a/vendor/github.com/gravitational/configure/kv.go b/vendor/github.com/gravitational/configure/kv.go
deleted file mode 100644
index f13fe84..0000000
--- a/vendor/github.com/gravitational/configure/kv.go
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
-Copyright 2015 Gravitational, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-package configure
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "strings"
-
- "github.com/gravitational/configure/cstrings"
- "github.com/gravitational/trace"
- "gopkg.in/alecthomas/kingpin.v2"
-)
-
-// KeyVal is map that can parse itself from string, represented as a
-// comma-separated list of keys and values "key:val,key:val"
-type KeyVal map[string]string
-
-// Set accepts string with arguments in the form "key:val,key2:val2"
-func (kv *KeyVal) Set(v string) error {
- if len(*kv) == 0 {
- *kv = make(map[string]string)
- }
- for _, i := range cstrings.SplitComma(v) {
- vals := strings.SplitN(i, ":", 2)
- if len(vals) != 2 {
- return trace.Errorf("extra options should be defined like KEY:VAL")
- }
- (*kv)[vals[0]] = vals[1]
- }
- return nil
-}
-
-// SetEnv sets the value from environment variable using json encoding
-func (kv *KeyVal) SetEnv(v string) error {
- if err := json.Unmarshal([]byte(v), &kv); err != nil {
- return trace.Wrap(
- err, "failed to parse environment variable, expected JSON map")
- }
- return nil
-}
-
-// String returns a string with comma separated key-values: "key:val,key2:val2"
-func (kv *KeyVal) String() string {
- out := make([]string, 0, len(*kv))
- for k, v := range *kv {
- out = append(out, fmt.Sprintf("%v:%v", k, v))
- }
- return strings.Join(out, ",")
-}
-
-// KeyValParam accepts a kingpin setting parameter and returns
-// kingpin-compatible value
-func KeyValParam(s kingpin.Settings) *KeyVal {
- kv := make(KeyVal)
- s.SetValue(&kv)
- return &kv
-}
-
-// KeyValSlice is a list of key value strings
-type KeyValSlice []map[string]string
-
-// Set accepts string with arguments in the form "key:val,key2:val2"
-func (kv *KeyValSlice) Set(v string) error {
- if len(*kv) == 0 {
- *kv = make([]map[string]string, 0)
- }
- var i KeyVal
- if err := i.Set(v); err != nil {
- return trace.Wrap(err)
- }
- *kv = append(*kv, i)
- return nil
-}
-
-// SetEnv sets the value from environment variable using json encoding
-func (kv *KeyValSlice) SetEnv(v string) error {
- if err := json.Unmarshal([]byte(v), &kv); err != nil {
- return trace.Wrap(
- err, "failed to parse environment variable, expected JSON map")
- }
- return nil
-}
-
-// String returns a string with comma separated key-values: "key:val,key2:val2"
-func (kv *KeyValSlice) String() string {
- b := &bytes.Buffer{}
- for k, v := range *kv {
- fmt.Fprintf(b, "%v:%v", k, v)
- fmt.Fprintf(b, " ")
- }
- return b.String()
-}
diff --git a/vendor/github.com/gravitational/configure/tpl.go b/vendor/github.com/gravitational/configure/tpl.go
deleted file mode 100644
index 05c40da..0000000
--- a/vendor/github.com/gravitational/configure/tpl.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package configure
-
-import (
- "bytes"
- "fmt"
- "io/ioutil"
- "os"
- "strings"
- "text/template"
-
- "github.com/gravitational/configure/cstrings"
- "github.com/gravitational/trace"
-)
-
-func renderTemplate(data []byte) ([]byte, error) {
- t := template.New("tpl")
- c, err := newCtx()
- if err != nil {
- return nil, trace.Wrap(err)
- }
- t.Funcs(map[string]interface{}{
- "env": c.Env,
- "file": c.File,
- })
- t, err = t.Parse(string(data))
- if err != nil {
- return nil, trace.Wrap(err)
- }
- buf := &bytes.Buffer{}
- if err := t.Execute(buf, nil); err != nil {
- return nil, trace.Wrap(err)
- }
- return buf.Bytes(), nil
-}
-
-func newCtx() (*ctx, error) {
- values := os.Environ()
- c := &ctx{
- env: make(map[string]string, len(values)),
- }
- for _, v := range values {
- vals := strings.SplitN(v, "=", 2)
- if len(vals) != 2 {
- return nil, trace.Errorf("failed to parse variable: '%v'", v)
- }
- c.env[vals[0]] = vals[1]
- }
- return c, nil
-}
-
-type ctx struct {
- env map[string]string
-}
-
-func (c *ctx) File(path string) (string, error) {
- o, err := ioutil.ReadFile(path)
- if err != nil {
- return "", trace.Wrap(err, fmt.Sprintf("reading file: %v", path))
- }
- return string(o), nil
-}
-
-func (c *ctx) Env(key string) (string, error) {
- v, ok := c.env[key]
- if !ok {
- return "", trace.Errorf("environment variable '%v' is not set", key)
- }
- values := cstrings.SplitComma(v)
- out := make([]string, len(values))
- for i, p := range values {
- out[i] = quoteYAML(p)
- }
- return strings.Join(out, ","), nil
-}
-
-func quoteYAML(val string) string {
- if len(val) == 0 {
- return val
- }
- if strings.HasPrefix(val, "'") && strings.HasSuffix(val, "'") {
- return val
- }
- if strings.ContainsAny(val, ":") {
- return "'" + val + "'"
- }
- return val
-}
diff --git a/vendor/github.com/gravitational/configure/yaml.go b/vendor/github.com/gravitational/configure/yaml.go
deleted file mode 100644
index f2d8000..0000000
--- a/vendor/github.com/gravitational/configure/yaml.go
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
-Copyright 2015 Gravitational, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-package configure
-
-import (
- "gopkg.in/yaml.v2"
-
- "github.com/gravitational/trace"
-)
-
-// ParseYAML parses yaml-encoded byte string into the struct
-// passed to the function.
-// EnableTemplating() argument allows to treat configuration file as a template
-// for example, it will support {{env "VAR"}} - that will substitute
-// environment variable "VAR" and pass it to YAML file parser
-func ParseYAML(data []byte, cfg interface{}, funcArgs ...ParseOption) error {
- var opts parseOptions
- for _, fn := range funcArgs {
- fn(&opts)
- }
- var err error
- if opts.templating {
- if data, err = renderTemplate(data); err != nil {
- return trace.Wrap(err)
- }
- }
-
- if err := yaml.Unmarshal(data, cfg); err != nil {
- return trace.Wrap(err)
- }
- return nil
-}
-
-type parseOptions struct {
- // templating turns on templating mode when
- // parsing yaml file
- templating bool
-}
-
-// ParseOption is a functional argument type
-type ParseOption func(p *parseOptions)
-
-// EnableTemplating allows to treat configuration file as a template
-// for example, it will support {{env "VAR"}} - that will substitute
-// environment variable "VAR" and pass it to YAML file parser
-func EnableTemplating() ParseOption {
- return func(p *parseOptions) {
- p.templating = true
- }
-}
diff --git a/vendor/github.com/gravitational/trace/.gitignore b/vendor/github.com/gravitational/trace/.gitignore
deleted file mode 100644
index daf913b..0000000
--- a/vendor/github.com/gravitational/trace/.gitignore
+++ /dev/null
@@ -1,24 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-*.prof
diff --git a/vendor/github.com/gravitational/trace/LICENSE b/vendor/github.com/gravitational/trace/LICENSE
deleted file mode 100644
index 9faf6ba..0000000
--- a/vendor/github.com/gravitational/trace/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
-Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright 2015 Gravitational, 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.
\ No newline at end of file
diff --git a/vendor/github.com/gravitational/trace/README.md b/vendor/github.com/gravitational/trace/README.md
deleted file mode 100644
index e767146..0000000
--- a/vendor/github.com/gravitational/trace/README.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# Trace
-
-Package for error handling and error reporting
-
-Read more here:
-
-http://blog.gravitational.com/thoughts-on-error-handling-in-go-programs/
-
-### Capture file, line and function
-
-```golang
-
-import (
- "github.com/gravitational/trace"
-)
-
-func someFunc() error {
- return trace.Wrap(err)
-}
-
-
-func main() {
- err := someFunc()
- fmt.Println(err.Error()) // prints file, line and function
-}
-```
-
-### Emit structured logs to Elastic search using udpbeat
-
-**Add trace's document template to your ElasticSearch cluster**
-
-```shell
-curl -XPUT 'http://localhost:9200/_template/trace' -d@udbbeat/template.json
-```
-
-**Start udpbeat UDP logs collector and emitter**
-
-```shell
-go get github.com/gravitational/trace/udpbeat
-udpbeat
-```
-
-**Hook up logger to UDP collector**
-
-In your code, attach a logrus hook to use udpbeat:
-
-```golang
-
-import (
- "github.com/gravitational/trace"
- log "github.com/Sirupsen/logrus"
-)
-
-func main() {
- hook, err := trace.NewUDPHook()
- if err != nil {
- log.Fatalf(err)
- }
- log.SetHook(hook)
-}
-```
-
-Done! You will get structured logs capturing output, log and error message.
-You can edit `udpbeat/template.json` to modify emitted fields to whatever makes sense to your app.
-
-
-
-
-
diff --git a/vendor/github.com/gravitational/trace/errors.go b/vendor/github.com/gravitational/trace/errors.go
deleted file mode 100644
index 6d72a3b..0000000
--- a/vendor/github.com/gravitational/trace/errors.go
+++ /dev/null
@@ -1,398 +0,0 @@
-/*
-Copyright 2015 Gravitational, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package trace
-
-import (
- "crypto/x509"
- "fmt"
- "io"
- "net"
- "net/url"
- "os"
-)
-
-// NotFound returns new instance of not found error
-func NotFound(message string, args ...interface{}) error {
- return wrap(&NotFoundError{
- Message: fmt.Sprintf(message, args...),
- }, message, args...)
-}
-
-// NotFoundError indicates that object has not been found
-type NotFoundError struct {
- Message string `json:"message"`
-}
-
-// IsNotFoundError returns true to indicate that is NotFoundError
-func (e *NotFoundError) IsNotFoundError() bool {
- return true
-}
-
-// Error returns log friendly description of an error
-func (e *NotFoundError) Error() string {
- if e.Message != "" {
- return e.Message
- }
- return "object not found"
-}
-
-// OrigError returns original error (in this case this is the error itself)
-func (e *NotFoundError) OrigError() error {
- return e
-}
-
-// IsNotFound returns whether this error is of NotFoundError type
-func IsNotFound(e error) bool {
- type nf interface {
- IsNotFoundError() bool
- }
- err := Unwrap(e)
- _, ok := err.(nf)
- if !ok {
- return os.IsNotExist(err)
- }
- return ok
-}
-
-// AlreadyExists returns a new instance of AlreadyExists error
-func AlreadyExists(message string, args ...interface{}) error {
- return wrap(&AlreadyExistsError{
- fmt.Sprintf(message, args...),
- }, message, args...)
-}
-
-// AlreadyExistsError indicates that there's a duplicate object that already
-// exists in the storage/system
-type AlreadyExistsError struct {
- Message string `json:"message"`
-}
-
-// Error returns log friendly description of an error
-func (n *AlreadyExistsError) Error() string {
- if n.Message != "" {
- return n.Message
- }
- return "object already exists"
-}
-
-// IsAlreadyExistsError indicates that this error of the AlreadyExistsError type
-func (AlreadyExistsError) IsAlreadyExistsError() bool {
- return true
-}
-
-// OrigError returns original error (in this case this is the error itself)
-func (e *AlreadyExistsError) OrigError() error {
- return e
-}
-
-// IsAlreadyExists returns whether this is error indicating that object
-// already exists
-func IsAlreadyExists(e error) bool {
- type ae interface {
- IsAlreadyExistsError() bool
- }
- _, ok := Unwrap(e).(ae)
- return ok
-}
-
-// BadParameter returns a new instance of BadParameterError
-func BadParameter(message string, args ...interface{}) error {
- return wrap(&BadParameterError{
- Message: fmt.Sprintf(message, args...),
- }, message, args...)
-}
-
-// BadParameterError indicates that something is wrong with passed
-// parameter to API method
-type BadParameterError struct {
- Message string `json:"message"`
-}
-
-// Error returns log friendly description of an error
-func (b *BadParameterError) Error() string {
- return b.Message
-}
-
-// OrigError returns original error (in this case this is the error itself)
-func (b *BadParameterError) OrigError() error {
- return b
-}
-
-// IsBadParameterError indicates that this error is of BadParameterError type
-func (b *BadParameterError) IsBadParameterError() bool {
- return true
-}
-
-// IsBadParameter returns whether this error is of BadParameterType
-func IsBadParameter(e error) bool {
- type bp interface {
- IsBadParameterError() bool
- }
- _, ok := Unwrap(e).(bp)
- return ok
-}
-
-// CompareFailed returns new instance of CompareFailedError
-func CompareFailed(message string, args ...interface{}) error {
- return wrap(&CompareFailedError{Message: fmt.Sprintf(message, args...)}, message, args...)
-}
-
-// CompareFailedError indicates a failed comparison (e.g. bad password or hash)
-type CompareFailedError struct {
- // Message is user-friendly error message
- Message string `json:"message"`
-}
-
-// Error is debug - friendly message
-func (e *CompareFailedError) Error() string {
- if e.Message != "" {
- return e.Message
- }
- return "compare failed"
-}
-
-// OrigError returns original error (in this case this is the error itself)
-func (e *CompareFailedError) OrigError() error {
- return e
-}
-
-// IsCompareFailedError indicates that this is CompareFailedError
-func (e *CompareFailedError) IsCompareFailedError() bool {
- return true
-}
-
-// IsCompareFailed detects if this error is of CompareFailed type
-func IsCompareFailed(e error) bool {
- type cf interface {
- IsCompareFailedError() bool
- }
- _, ok := Unwrap(e).(cf)
- return ok
-}
-
-// AccessDenied returns new instance of AccessDeniedError
-func AccessDenied(message string, args ...interface{}) error {
- return wrap(&AccessDeniedError{
- Message: fmt.Sprintf(message, args...),
- }, message, args...)
-}
-
-// AccessDeniedError indicates denied access
-type AccessDeniedError struct {
- Message string `json:"message"`
-}
-
-// Error is debug - friendly error message
-func (e *AccessDeniedError) Error() string {
- if e.Message != "" {
- return e.Message
- }
- return "access denied"
-}
-
-// IsAccessDeniedError indicates that this error is of AccessDeniedError type
-func (e *AccessDeniedError) IsAccessDeniedError() bool {
- return true
-}
-
-// OrigError returns original error (in this case this is the error itself)
-func (e *AccessDeniedError) OrigError() error {
- return e
-}
-
-// IsAccessDenied detects if this error is of AccessDeniedError type
-func IsAccessDenied(e error) bool {
- type ad interface {
- IsAccessDeniedError() bool
- }
- _, ok := Unwrap(e).(ad)
- return ok
-}
-
-// ConvertSystemError converts system error to appropriate trace error
-// if it is possible, otherwise, returns original error
-func ConvertSystemError(err error) error {
- innerError := Unwrap(err)
-
- if os.IsNotExist(innerError) {
- return wrap(&NotFoundError{Message: innerError.Error()}, innerError.Error())
- }
- if os.IsPermission(innerError) {
- return wrap(&AccessDeniedError{Message: innerError.Error()}, innerError.Error())
- }
- switch realErr := innerError.(type) {
- case *net.OpError:
- message := fmt.Sprintf("failed to connect to server %v", realErr.Addr)
- return wrap(&ConnectionProblemError{
- Message: message,
- Err: realErr}, message)
- case *os.PathError:
- message := fmt.Sprintf("failed to execute command %v error: %v", realErr.Path, realErr.Err)
- return wrap(&AccessDeniedError{
- Message: message,
- }, message)
- case x509.SystemRootsError, x509.UnknownAuthorityError:
- return wrapWithDepth(&TrustError{Err: innerError}, 2)
- default:
- return err
- }
-}
-
-// ConnectionProblem returns new instance of ConnectionProblemError
-func ConnectionProblem(err error, message string, args ...interface{}) error {
- return wrap(&ConnectionProblemError{
- Message: fmt.Sprintf(message, args...),
- Err: err,
- }, message, args...)
-}
-
-// ConnectionProblemError indicates a network related problem
-type ConnectionProblemError struct {
- Message string `json:"message"`
- Err error `json:"-"`
-}
-
-// Error is debug - friendly error message
-func (c *ConnectionProblemError) Error() string {
- return fmt.Sprintf("%v: %v", c.Message, c.Err)
-}
-
-// IsConnectionProblemError indicates that this error is of ConnectionProblemError type
-func (c *ConnectionProblemError) IsConnectionProblemError() bool {
- return true
-}
-
-// OrigError returns original error (in this case this is the error itself)
-func (c *ConnectionProblemError) OrigError() error {
- return c
-}
-
-// IsConnectionProblem returns whether this error is of ConnectionProblemError
-func IsConnectionProblem(e error) bool {
- type ad interface {
- IsConnectionProblemError() bool
- }
- _, ok := Unwrap(e).(ad)
- return ok
-}
-
-// LimitExceeded returns whether new instance of LimitExceededError
-func LimitExceeded(message string, args ...interface{}) error {
- return wrap(&LimitExceededError{
- Message: fmt.Sprintf(message, args...),
- }, message, args...)
-}
-
-// LimitExceededError indicates rate limit or connection limit problem
-type LimitExceededError struct {
- Message string `json:"message"`
-}
-
-// Error is debug - friendly error message
-func (c *LimitExceededError) Error() string {
- return c.Message
-}
-
-// IsLimitExceededError indicates that this error is of ConnectionProblem
-func (c *LimitExceededError) IsLimitExceededError() bool {
- return true
-}
-
-// OrigError returns original error (in this case this is the error itself)
-func (c *LimitExceededError) OrigError() error {
- return c
-}
-
-// IsLimitExceeded detects if this error is of LimitExceededError
-func IsLimitExceeded(e error) bool {
- type ad interface {
- IsLimitExceededError() bool
- }
- _, ok := Unwrap(e).(ad)
- return ok
-}
-
-// TrustError indicates trust-related validation error (e.g. untrusted cert)
-type TrustError struct {
- // Err is original error
- Err error `json:"error"`
- Message string
-}
-
-// Error returns log-friendly error description
-func (t *TrustError) Error() string {
- return t.Err.Error()
-}
-
-// IsTrustError indicates that this error is of TrustError type
-func (*TrustError) IsTrustError() bool {
- return true
-}
-
-// OrigError returns original error (in this case this is the error itself)
-func (t *TrustError) OrigError() error {
- return t
-}
-
-// IsTrustError returns if this is a trust error
-func IsTrustError(e error) bool {
- type te interface {
- IsTrustError() bool
- }
- _, ok := Unwrap(e).(te)
- return ok
-}
-
-// OAuth2 returns new instance of OAuth2Error
-func OAuth2(code, message string, query url.Values) Error {
- return wrap(&OAuth2Error{
- Code: code,
- Message: message,
- Query: query,
- }, message)
-}
-
-// OAuth2Error defined an error used in OpenID Connect Flow (OIDC)
-type OAuth2Error struct {
- Code string `json:"code"`
- Message string `json:"message"`
- Query url.Values `json:"query"`
-}
-
-//Error returns log friendly description of an error
-func (o *OAuth2Error) Error() string {
- return fmt.Sprintf("OAuth2 error code=%v, message=%v", o.Code, o.Message)
-}
-
-// IsOAuth2Error returns whether this error of OAuth2Error type
-func (o *OAuth2Error) IsOAuth2Error() bool {
- return true
-}
-
-// IsOAuth2 returns if this is a OAuth2-related error
-func IsOAuth2(e error) bool {
- type oe interface {
- IsOAuth2Error() bool
- }
- _, ok := Unwrap(e).(oe)
- return ok
-}
-
-// IsEOF returns true if the passed error is io.EOF
-func IsEOF(e error) bool {
- return Unwrap(e) == io.EOF
-}
diff --git a/vendor/github.com/gravitational/trace/httplib.go b/vendor/github.com/gravitational/trace/httplib.go
deleted file mode 100644
index baf7e07..0000000
--- a/vendor/github.com/gravitational/trace/httplib.go
+++ /dev/null
@@ -1,138 +0,0 @@
-package trace
-
-import (
- "encoding/json"
- "fmt"
- "net/http"
-)
-
-const (
- statusTooManyRequests = 429
- statusTrustError = 504
-)
-
-// WriteError sets up HTTP error response and writes it to writer w
-func WriteError(w http.ResponseWriter, err error) {
- if IsAggregate(err) {
- for i := 0; i < maxHops; i++ {
- var aggErr Aggregate
- var ok bool
- if aggErr, ok = Unwrap(err).(Aggregate); !ok {
- break
- }
- errors := aggErr.Errors()
- if len(errors) == 0 {
- break
- }
- err = errors[0]
- }
- }
- writeError(w, err)
-}
-
-func writeError(w http.ResponseWriter, err error) {
- if IsNotFound(err) {
- replyJSON(
- w, http.StatusNotFound, err)
- } else if IsBadParameter(err) || IsOAuth2(err) {
- replyJSON(
- w, http.StatusBadRequest, err)
- } else if IsCompareFailed(err) {
- replyJSON(
- w, http.StatusPreconditionFailed, err)
- } else if IsAccessDenied(err) {
- replyJSON(
- w, http.StatusForbidden, err)
- } else if IsAlreadyExists(err) {
- replyJSON(
- w, http.StatusConflict, err)
- } else if IsLimitExceeded(err) {
- replyJSON(
- w, statusTooManyRequests, err)
- } else if IsConnectionProblem(err) {
- replyJSON(
- w, http.StatusGatewayTimeout, err)
- } else {
- replyJSON(
- w, http.StatusInternalServerError, err)
- }
-}
-
-// ReadError converts http error to internal error type
-// based on HTTP response code and HTTP body contents
-// if status code does not indicate error, it will return nil
-func ReadError(statusCode int, re []byte) error {
- var e error
- switch statusCode {
- case http.StatusNotFound:
- e = &NotFoundError{}
- case http.StatusBadRequest:
- e = &BadParameterError{}
- case http.StatusPreconditionFailed:
- e = &CompareFailedError{}
- case http.StatusForbidden:
- e = &AccessDeniedError{}
- case http.StatusConflict:
- e = &AlreadyExistsError{}
- case statusTooManyRequests:
- e = &LimitExceededError{}
- case http.StatusGatewayTimeout:
- e = &ConnectionProblemError{}
- default:
- if statusCode < 200 || statusCode > 299 {
- return Errorf(string(re))
- }
- return nil
- }
- return unmarshalError(e, re)
-}
-
-func replyJSON(w http.ResponseWriter, code int, err error) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(code)
-
- var out []byte
- if IsDebug() {
- // trace error can marshal itself,
- // otherwise capture error message and marshal it explicitly
- var obj interface{} = err
- if _, ok := err.(*TraceErr); !ok {
- obj = message{Message: err.Error()}
- }
- out, err = json.MarshalIndent(obj, "", " ")
- if err != nil {
- out = []byte(fmt.Sprintf(`{"message": "internal marshal error: %v"}`, err))
- }
- } else {
- innerError := err
- if terr, ok := err.(Error); ok {
- innerError = terr.OrigError()
- }
- out, err = json.Marshal(message{Message: innerError.Error()})
- }
- w.Write(out)
-}
-
-type message struct {
- Message string `json:"message"`
-}
-
-func unmarshalError(err error, responseBody []byte) error {
- if len(responseBody) == 0 {
- return err
- }
- var raw rawTrace
- if err2 := json.Unmarshal(responseBody, &raw); err2 != nil {
- return err
- }
- if len(raw.Traces) != 0 && len(raw.Err) != 0 {
- // try to capture traces, if there are any
- err2 := json.Unmarshal(raw.Err, err)
- if err2 != nil {
- return err
- }
- return &TraceErr{Traces: raw.Traces, Err: err, Message: raw.Message}
- }
- json.Unmarshal(responseBody, err)
- return err
-}
diff --git a/vendor/github.com/gravitational/trace/log.go b/vendor/github.com/gravitational/trace/log.go
deleted file mode 100644
index d2e66ef..0000000
--- a/vendor/github.com/gravitational/trace/log.go
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
-Copyright 2015 Gravitational, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package trace implements utility functions for capturing logs
-package trace
-
-import (
- "strings"
-
- log "github.com/Sirupsen/logrus"
-
- "runtime"
-)
-
-const (
- // FileField is a field with code file added to structured traces
- FileField = "file"
- // FunctionField is a field with function name
- FunctionField = "func"
- // LevelField returns logging level as set by logrus
- LevelField = "level"
- // Component is a field that represents component - e.g. service or
- // function
- Component = "component"
-)
-
-// TextFormatter is logrus-compatible formatter and adds
-// file and line details to every logged entry.
-type TextFormatter struct {
- log.TextFormatter
-}
-
-// Format implements logrus.Formatter interface and adds file and line
-func (tf *TextFormatter) Format(e *log.Entry) ([]byte, error) {
- if frameNo := findFrame(); frameNo != -1 {
- t := newTrace(frameNo, nil)
- new := e.WithFields(log.Fields{FileField: t.Loc(), FunctionField: t.FuncName()})
- new.Level = e.Level
- new.Message = e.Message
- e = new
- }
- return (&tf.TextFormatter).Format(e)
-}
-
-// JSONFormatter implements logrus.Formatter interface and adds file and line
-// properties to JSON entries
-type JSONFormatter struct {
- log.JSONFormatter
-}
-
-// Format implements logrus.Formatter interface
-func (j *JSONFormatter) Format(e *log.Entry) ([]byte, error) {
- if frameNo := findFrame(); frameNo != -1 {
- t := newTrace(frameNo, nil)
- new := e.WithFields(log.Fields{
- FileField: t.Loc(),
- FunctionField: t.FuncName(),
- })
- new.Level = e.Level
- new.Message = e.Message
- e = new
- }
- return (&j.JSONFormatter).Format(e)
-}
-
-func findFrame() int {
- for i := 3; i < 10; i++ {
- _, file, _, ok := runtime.Caller(i)
- if !ok {
- return -1
- }
- if !strings.Contains(file, "Sirupsen/logrus") {
- return i
- }
- }
- return -1
-}
diff --git a/vendor/github.com/gravitational/trace/trace.go b/vendor/github.com/gravitational/trace/trace.go
deleted file mode 100644
index b5e9956..0000000
--- a/vendor/github.com/gravitational/trace/trace.go
+++ /dev/null
@@ -1,371 +0,0 @@
-/*
-Copyright 2015 Gravitational, Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-// Package trace implements utility functions for capturing debugging
-// information about file and line in error reports and logs.
-package trace
-
-import (
- "encoding/json"
- "fmt"
- "path/filepath"
- "runtime"
- "strings"
- "sync/atomic"
-
- "golang.org/x/net/context"
-)
-
-var debug int32
-
-// SetDebug turns on/off debugging mode, that causes Fatalf to panic
-func SetDebug(enabled bool) {
- if enabled {
- atomic.StoreInt32(&debug, 1)
- } else {
- atomic.StoreInt32(&debug, 0)
- }
-}
-
-// IsDebug returns true if debug mode is on, false otherwize
-func IsDebug() bool {
- return atomic.LoadInt32(&debug) == 1
-}
-
-// Wrap takes the original error and wraps it into the Trace struct
-// memorizing the context of the error.
-func Wrap(err error, args ...interface{}) Error {
- return wrapWithDepth(err, 2, args...)
-}
-
-// Unwrap unwraps error to it's original error
-func Unwrap(err error) error {
- if terr, ok := err.(Error); ok {
- return terr.OrigError()
- }
- return err
-}
-
-// UserMessage returns user-friendly part of the error
-func UserMessage(err error) string {
- if err == nil {
- return ""
- }
- if wrap, ok := err.(Error); ok {
- return wrap.UserMessage()
- }
- return err.Error()
-}
-
-// DebugReport returns debug report with all known information
-// about the error including stack trace if it was captured
-func DebugReport(err error) string {
- if err == nil {
- return ""
- }
- if wrap, ok := err.(Error); ok {
- return wrap.DebugReport()
- }
- return err.Error()
-}
-
-func wrap(err error, message string, args ...interface{}) Error {
- args = append([]interface{}{message}, args...)
- return wrapWithDepth(err, 3, args...)
-}
-
-func wrapWithDepth(err error, depth int, args ...interface{}) Error {
- if err == nil {
- return nil
- }
- var wrapper Error
- if wrap, ok := err.(Error); ok {
- wrapper = wrap
- } else {
- wrapper = newTrace(depth+1, err)
- }
- if len(args) != 0 {
- wrapper.AddUserMessage(args[0], args[1:]...)
- }
- return wrapper
-}
-
-// Errorf is similar to fmt.Errorf except that it captures
-// more information about the origin of error, such as
-// callee, line number and function that simplifies debugging
-func Errorf(format string, args ...interface{}) error {
- return newTrace(2, fmt.Errorf(format, args...))
-}
-
-// Fatalf - If debug is false Fatalf calls Errorf. If debug is
-// true Fatalf calls panic
-func Fatalf(format string, args ...interface{}) error {
- if IsDebug() {
- panic(fmt.Sprintf(format, args))
- } else {
- return Errorf(format, args)
- }
-}
-
-func newTrace(depth int, err error) *TraceErr {
- var pc [32]uintptr
- count := runtime.Callers(depth+1, pc[:])
-
- traces := make(Traces, count)
- for i := 0; i < count; i++ {
- fn := runtime.FuncForPC(pc[i])
- filePath, line := fn.FileLine(pc[i])
- traces[i] = Trace{
- Func: fn.Name(),
- Path: filePath,
- Line: line,
- }
- }
- return &TraceErr{
- err,
- traces,
- "",
- }
-}
-
-// Traces is a list of trace entries
-type Traces []Trace
-
-// SetTraces adds new traces to the list
-func (s Traces) SetTraces(traces ...Trace) {
- s = append(s, traces...)
-}
-
-// Func returns first function in trace list
-func (s Traces) Func() string {
- if len(s) == 0 {
- return ""
- }
- return s[0].Func
-}
-
-// Func returns just function name
-func (s Traces) FuncName() string {
- if len(s) == 0 {
- return ""
- }
- fn := filepath.ToSlash(s[0].Func)
- idx := strings.LastIndex(fn, "/")
- if idx == -1 || idx == len(fn)-1 {
- return fn
- }
- return fn[idx+1:]
-}
-
-// Loc points to file/line location in the code
-func (s Traces) Loc() string {
- if len(s) == 0 {
- return ""
- }
- return s[0].String()
-}
-
-// String returns debug-friendly representaton of trace stack
-func (s Traces) String() string {
- if len(s) == 0 {
- return ""
- }
- out := make([]string, len(s))
- for i, t := range s {
- out[i] = fmt.Sprintf("\t%v:%v %v", t.Path, t.Line, t.Func)
- }
- return strings.Join(out, "\n")
-}
-
-// Trace stores structured trace entry, including file line and path
-type Trace struct {
- // Path is a full file path
- Path string `json:"path"`
- // Func is a function name
- Func string `json:"func"`
- // Line is a code line number
- Line int `json:"line"`
-}
-
-// String returns debug-friendly representation of this trace
-func (t *Trace) String() string {
- dir, file := filepath.Split(t.Path)
- dirs := strings.Split(filepath.ToSlash(filepath.Clean(dir)), "/")
- if len(dirs) != 0 {
- file = filepath.Join(dirs[len(dirs)-1], file)
- }
- return fmt.Sprintf("%v:%v", file, t.Line)
-}
-
-// TraceErr contains error message and some additional
-// information about the error origin
-type TraceErr struct {
- Err error `json:"error"`
- Traces `json:"traces"`
- Message string `json:"message,omitemtpy"`
-}
-
-type rawTrace struct {
- Err json.RawMessage `json:"error"`
- Traces `json:"traces"`
- Message string `json:"message"`
-}
-
-// AddUserMessage adds user-friendly message describing the error nature
-func (e *TraceErr) AddUserMessage(formatArg interface{}, rest ...interface{}) {
- newMessage := fmt.Sprintf(fmt.Sprintf("%v", formatArg), rest...)
- if len(e.Message) == 0 {
- e.Message = newMessage
- } else {
- e.Message = strings.Join([]string{e.Message, newMessage}, ", ")
- }
-}
-
-// UserMessage returns user-friendly error message
-func (e *TraceErr) UserMessage() string {
- if e.Message != "" {
- return e.Message
- }
- return e.Err.Error()
-}
-
-// DebugReport returns develeoper-friendly error report
-func (e *TraceErr) DebugReport() string {
- return fmt.Sprintf("\nERROR REPORT:\nOriginal Error: %T %v\nStack Trace:\n%v\nUser Message: %v\n", e.Err, e.Err.Error(), e.Traces.String(), e.Message)
-}
-
-// Error returns user-friendly error message when not in debug mode
-func (e *TraceErr) Error() string {
- if IsDebug() {
- return e.DebugReport()
- }
- return e.UserMessage()
-}
-
-// OrigError returns original wrapped error
-func (e *TraceErr) OrigError() error {
- err := e.Err
- // this is not an endless loop because I'm being
- // paranoid, this is a safe protection against endless
- // loops
- for i := 0; i < maxHops; i++ {
- newerr, ok := err.(Error)
- if !ok {
- break
- }
- if newerr.OrigError() != err {
- err = newerr.OrigError()
- }
- }
- return err
-}
-
-// maxHops is a max supported nested depth for errors
-const maxHops = 50
-
-// Error is an interface that helps to adapt usage of trace in the code
-// When applications define new error types, they can implement the interface
-// So error handlers can use OrigError() to retrieve error from the wrapper
-type Error interface {
- error
- // OrigError returns original error wrapped in this error
- OrigError() error
- // AddMessage adds formatted user-facing message
- // to the error, depends on the implementation,
- // usually works as fmt.Sprintf(formatArg, rest...)
- // but implementations can choose another way, e.g. treat
- // arguments as structured args
- AddUserMessage(formatArg interface{}, rest ...interface{})
-
- // UserMessage returns user-friendly error message
- UserMessage() string
-
- // DebugReport returns develeoper-friendly error report
- DebugReport() string
-}
-
-// NewAggregate creates a new aggregate instance from the specified
-// list of errors
-func NewAggregate(errs ...error) error {
- // filter out possible nil values
- var nonNils []error
- for _, err := range errs {
- if err != nil {
- nonNils = append(nonNils, err)
- }
- }
- if len(nonNils) == 0 {
- return nil
- }
- return wrapWithDepth(aggregate(nonNils), 2)
-}
-
-// NewAggregateFromChannel creates a new aggregate instance from the provided
-// errors channel.
-//
-// A context.Context can be passed in so the caller has the ability to cancel
-// the operation. If this is not desired, simply pass context.Background().
-func NewAggregateFromChannel(errCh chan error, ctx context.Context) error {
- var errs []error
-
-Loop:
- for {
- select {
- case err, ok := <-errCh:
- if !ok { // the channel is closed, time to exit
- break Loop
- }
- errs = append(errs, err)
- case <-ctx.Done():
- break Loop
- }
- }
-
- return NewAggregate(errs...)
-}
-
-// Aggregate interface combines several errors into one error
-type Aggregate interface {
- error
- // Errors obtains the list of errors this aggregate combines
- Errors() []error
-}
-
-// aggregate implements Aggregate
-type aggregate []error
-
-// Error implements the error interface
-func (r aggregate) Error() string {
- if len(r) == 0 {
- return ""
- }
- output := r[0].Error()
- for i := 1; i < len(r); i++ {
- output = fmt.Sprintf("%v, %v", output, r[i])
- }
- return output
-}
-
-// Errors obtains the list of errors this aggregate combines
-func (r aggregate) Errors() []error {
- return []error(r)
-}
-
-// IsAggregate returns whether this error of Aggregate error type
-func IsAggregate(err error) bool {
- _, ok := Unwrap(err).(Aggregate)
- return ok
-}
diff --git a/vendor/github.com/gravitational/trace/udphook.go b/vendor/github.com/gravitational/trace/udphook.go
deleted file mode 100644
index 69ed2dc..0000000
--- a/vendor/github.com/gravitational/trace/udphook.go
+++ /dev/null
@@ -1,111 +0,0 @@
-package trace
-
-import (
- "encoding/json"
- "net"
- "time"
-
- log "github.com/Sirupsen/logrus"
- "github.com/jonboulle/clockwork"
-)
-
-const (
- // UDPDefaultAddr is a default address to emit logs to
- UDPDefaultAddr = "127.0.0.1:5000"
- // UDPDefaultNet is a default network
- UDPDefaultNet = "udp"
-)
-
-// UDPOptionSetter represents functional arguments passed to ELKHook
-type UDPOptionSetter func(f *UDPHook)
-
-// NewUDPHook returns logrus-compatible hook that sends data to UDP socket
-func NewUDPHook(opts ...UDPOptionSetter) (*UDPHook, error) {
- f := &UDPHook{}
- for _, o := range opts {
- o(f)
- }
- if f.Clock == nil {
- f.Clock = clockwork.NewRealClock()
- }
- if f.clientNet == "" {
- f.clientNet = UDPDefaultNet
- }
- if f.clientAddr == "" {
- f.clientAddr = UDPDefaultAddr
- }
- addr, err := net.ResolveUDPAddr(f.clientNet, f.clientAddr)
- if err != nil {
- return nil, Wrap(err)
- }
- conn, err := net.ListenPacket("udp", ":0")
- if err != nil {
- return nil, Wrap(err)
- }
- f.addr = addr
- f.conn = conn.(*net.UDPConn)
- return f, nil
-}
-
-type UDPHook struct {
- Clock clockwork.Clock
- clientNet string
- clientAddr string
- addr *net.UDPAddr
- conn *net.UDPConn
-}
-
-type Frame struct {
- Time time.Time `json:"time"`
- Type string `json:"type"`
- Entry map[string]interface{} `json:"entry"`
- Message string `json:"message"`
- Level string `json:"level"`
-}
-
-// Fire fires the event to the ELK beat
-func (elk *UDPHook) Fire(e *log.Entry) error {
- // Make a copy to safely modify
- entry := e.WithFields(nil)
- if frameNo := findFrame(); frameNo != -1 {
- t := newTrace(frameNo-1, nil)
- entry.Data[FileField] = t.String()
- entry.Data[FunctionField] = t.Func()
- }
- data, err := json.Marshal(Frame{
- Time: elk.Clock.Now().UTC(),
- Type: "trace",
- Entry: entry.Data,
- Message: entry.Message,
- Level: entry.Level.String(),
- })
- if err != nil {
- return Wrap(err)
- }
-
- c, err := net.ListenPacket("udp", ":0")
- if err != nil {
- return Wrap(err)
- }
-
- ra, err := net.ResolveUDPAddr("udp", "127.0.0.1:5000")
- if err != nil {
- return Wrap(err)
- }
-
- _, err = (c.(*net.UDPConn)).WriteToUDP(data, ra)
- return Wrap(err)
-
-}
-
-// Levels returns logging levels supported by logrus
-func (elk *UDPHook) Levels() []log.Level {
- return []log.Level{
- log.PanicLevel,
- log.FatalLevel,
- log.ErrorLevel,
- log.WarnLevel,
- log.InfoLevel,
- log.DebugLevel,
- }
-}
diff --git a/vendor/github.com/hashicorp/golang-lru/.gitignore b/vendor/github.com/hashicorp/golang-lru/.gitignore
deleted file mode 100644
index 8365624..0000000
--- a/vendor/github.com/hashicorp/golang-lru/.gitignore
+++ /dev/null
@@ -1,23 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
diff --git a/vendor/github.com/jonboulle/clockwork/.gitignore b/vendor/github.com/jonboulle/clockwork/.gitignore
deleted file mode 100644
index 010c242..0000000
--- a/vendor/github.com/jonboulle/clockwork/.gitignore
+++ /dev/null
@@ -1,25 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-
-*.swp
diff --git a/vendor/github.com/jonboulle/clockwork/.travis.yml b/vendor/github.com/jonboulle/clockwork/.travis.yml
deleted file mode 100644
index aefda90..0000000
--- a/vendor/github.com/jonboulle/clockwork/.travis.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-language: go
-go:
- - 1.3
-
-sudo: false
diff --git a/vendor/github.com/jonboulle/clockwork/LICENSE b/vendor/github.com/jonboulle/clockwork/LICENSE
deleted file mode 100644
index 5c304d1..0000000
--- a/vendor/github.com/jonboulle/clockwork/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
-Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright {yyyy} {name of copyright owner}
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/vendor/github.com/jonboulle/clockwork/README.md b/vendor/github.com/jonboulle/clockwork/README.md
deleted file mode 100644
index d43a6c7..0000000
--- a/vendor/github.com/jonboulle/clockwork/README.md
+++ /dev/null
@@ -1,61 +0,0 @@
-clockwork
-=========
-
-[![Build Status](https://travis-ci.org/jonboulle/clockwork.png?branch=master)](https://travis-ci.org/jonboulle/clockwork)
-[![godoc](https://godoc.org/github.com/jonboulle/clockwork?status.svg)](http://godoc.org/github.com/jonboulle/clockwork)
-
-a simple fake clock for golang
-
-# Usage
-
-Replace uses of the `time` package with the `clockwork.Clock` interface instead.
-
-For example, instead of using `time.Sleep` directly:
-
-```
-func my_func() {
- time.Sleep(3 * time.Second)
- do_something()
-}
-```
-
-inject a clock and use its `Sleep` method instead:
-
-```
-func my_func(clock clockwork.Clock) {
- clock.Sleep(3 * time.Second)
- do_something()
-}
-```
-
-Now you can easily test `my_func` with a `FakeClock`:
-
-```
-func TestMyFunc(t *testing.T) {
- c := clockwork.NewFakeClock()
-
- // Start our sleepy function
- my_func(c)
-
- // Ensure we wait until my_func is sleeping
- c.BlockUntil(1)
-
- assert_state()
-
- // Advance the FakeClock forward in time
- c.Advance(3)
-
- assert_state()
-}
-```
-
-and in production builds, simply inject the real clock instead:
-```
-my_func(clockwork.NewRealClock())
-```
-
-See [example_test.go](example_test.go) for a full example.
-
-# Credits
-
-clockwork is inspired by @wickman's [threaded fake clock](https://gist.github.com/wickman/3840816), and the [Golang playground](http://blog.golang.org/playground#Faking time)
diff --git a/vendor/github.com/jonboulle/clockwork/clockwork.go b/vendor/github.com/jonboulle/clockwork/clockwork.go
deleted file mode 100644
index 999fddd..0000000
--- a/vendor/github.com/jonboulle/clockwork/clockwork.go
+++ /dev/null
@@ -1,179 +0,0 @@
-package clockwork
-
-import (
- "sync"
- "time"
-)
-
-// Clock provides an interface that packages can use instead of directly
-// using the time module, so that chronology-related behavior can be tested
-type Clock interface {
- After(d time.Duration) <-chan time.Time
- Sleep(d time.Duration)
- Now() time.Time
- Since(t time.Time) time.Duration
-}
-
-// FakeClock provides an interface for a clock which can be
-// manually advanced through time
-type FakeClock interface {
- Clock
- // Advance advances the FakeClock to a new point in time, ensuring any existing
- // sleepers are notified appropriately before returning
- Advance(d time.Duration)
- // BlockUntil will block until the FakeClock has the given number of
- // sleepers (callers of Sleep or After)
- BlockUntil(n int)
-}
-
-// NewRealClock returns a Clock which simply delegates calls to the actual time
-// package; it should be used by packages in production.
-func NewRealClock() Clock {
- return &realClock{}
-}
-
-// NewFakeClock returns a FakeClock implementation which can be
-// manually advanced through time for testing. The initial time of the
-// FakeClock will be an arbitrary non-zero time.
-func NewFakeClock() FakeClock {
- // use a fixture that does not fulfill Time.IsZero()
- return NewFakeClockAt(time.Date(1984, time.April, 4, 0, 0, 0, 0, time.UTC))
-}
-
-// NewFakeClockAt returns a FakeClock initialised at the given time.Time.
-func NewFakeClockAt(t time.Time) FakeClock {
- return &fakeClock{
- time: t,
- }
-}
-
-type realClock struct{}
-
-func (rc *realClock) After(d time.Duration) <-chan time.Time {
- return time.After(d)
-}
-
-func (rc *realClock) Sleep(d time.Duration) {
- time.Sleep(d)
-}
-
-func (rc *realClock) Now() time.Time {
- return time.Now()
-}
-
-func (rc *realClock) Since(t time.Time) time.Duration {
- return rc.Now().Sub(t)
-}
-
-type fakeClock struct {
- sleepers []*sleeper
- blockers []*blocker
- time time.Time
-
- l sync.RWMutex
-}
-
-// sleeper represents a caller of After or Sleep
-type sleeper struct {
- until time.Time
- done chan time.Time
-}
-
-// blocker represents a caller of BlockUntil
-type blocker struct {
- count int
- ch chan struct{}
-}
-
-// After mimics time.After; it waits for the given duration to elapse on the
-// fakeClock, then sends the current time on the returned channel.
-func (fc *fakeClock) After(d time.Duration) <-chan time.Time {
- fc.l.Lock()
- defer fc.l.Unlock()
- now := fc.time
- done := make(chan time.Time, 1)
- if d.Nanoseconds() == 0 {
- // special case - trigger immediately
- done <- now
- } else {
- // otherwise, add to the set of sleepers
- s := &sleeper{
- until: now.Add(d),
- done: done,
- }
- fc.sleepers = append(fc.sleepers, s)
- // and notify any blockers
- fc.blockers = notifyBlockers(fc.blockers, len(fc.sleepers))
- }
- return done
-}
-
-// notifyBlockers notifies all the blockers waiting until the
-// given number of sleepers are waiting on the fakeClock. It
-// returns an updated slice of blockers (i.e. those still waiting)
-func notifyBlockers(blockers []*blocker, count int) (newBlockers []*blocker) {
- for _, b := range blockers {
- if b.count == count {
- close(b.ch)
- } else {
- newBlockers = append(newBlockers, b)
- }
- }
- return
-}
-
-// Sleep blocks until the given duration has passed on the fakeClock
-func (fc *fakeClock) Sleep(d time.Duration) {
- <-fc.After(d)
-}
-
-// Time returns the current time of the fakeClock
-func (fc *fakeClock) Now() time.Time {
- fc.l.RLock()
- t := fc.time
- fc.l.RUnlock()
- return t
-}
-
-// Since returns the duration that has passed since the given time on the fakeClock
-func (fc *fakeClock) Since(t time.Time) time.Duration {
- return fc.Now().Sub(t)
-}
-
-// Advance advances fakeClock to a new point in time, ensuring channels from any
-// previous invocations of After are notified appropriately before returning
-func (fc *fakeClock) Advance(d time.Duration) {
- fc.l.Lock()
- defer fc.l.Unlock()
- end := fc.time.Add(d)
- var newSleepers []*sleeper
- for _, s := range fc.sleepers {
- if end.Sub(s.until) >= 0 {
- s.done <- end
- } else {
- newSleepers = append(newSleepers, s)
- }
- }
- fc.sleepers = newSleepers
- fc.blockers = notifyBlockers(fc.blockers, len(fc.sleepers))
- fc.time = end
-}
-
-// BlockUntil will block until the fakeClock has the given number of sleepers
-// (callers of Sleep or After)
-func (fc *fakeClock) BlockUntil(n int) {
- fc.l.Lock()
- // Fast path: current number of sleepers is what we're looking for
- if len(fc.sleepers) == n {
- fc.l.Unlock()
- return
- }
- // Otherwise, set up a new blocker
- b := &blocker{
- count: n,
- ch: make(chan struct{}),
- }
- fc.blockers = append(fc.blockers, b)
- fc.l.Unlock()
- <-b.ch
-}
diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE
new file mode 100644
index 0000000..835ba3e
--- /dev/null
+++ b/vendor/github.com/pkg/errors/LICENSE
@@ -0,0 +1,23 @@
+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
new file mode 100644
index 0000000..273db3c
--- /dev/null
+++ b/vendor/github.com/pkg/errors/README.md
@@ -0,0 +1,52 @@
+# 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)
+
+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.
+
+## Licence
+
+BSD-2-Clause
diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml
new file mode 100644
index 0000000..a932ead
--- /dev/null
+++ b/vendor/github.com/pkg/errors/appveyor.yml
@@ -0,0 +1,32 @@
+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
new file mode 100644
index 0000000..1c9731a
--- /dev/null
+++ b/vendor/github.com/pkg/errors/errors.go
@@ -0,0 +1,238 @@
+// 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. For example
+//
+// _, 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
+//
+// 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)
+ }
+}
+
+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 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 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(),
+ }
+}
+
+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
new file mode 100644
index 0000000..6b1f289
--- /dev/null
+++ b/vendor/github.com/pkg/errors/stack.go
@@ -0,0 +1,178 @@
+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 path of source file relative to the compile time GOPATH
+// %+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
+
+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:]
+}
+
+func trimGOPATH(name, file string) string {
+ // Here we want to get the source file path relative to the compile time
+ // GOPATH. As of Go 1.6.x there is no direct way to know the compiled
+ // GOPATH at runtime, but we can infer the number of path segments in the
+ // GOPATH. We note that fn.Name() returns the function name qualified by
+ // the import path, which does not include the GOPATH. Thus we can trim
+ // segments from the beginning of the file path until the number of path
+ // separators remaining is one more than the number of path separators in
+ // the function name. For example, given:
+ //
+ // GOPATH /home/user
+ // file /home/user/src/pkg/sub/file.go
+ // fn.Name() pkg/sub.Type.Method
+ //
+ // We want to produce:
+ //
+ // pkg/sub/file.go
+ //
+ // From this we can easily see that fn.Name() has one less path separator
+ // than our desired output. We count separators from the end of the file
+ // path until it finds two more than in the function name and then move
+ // one character forward to preserve the initial path segment without a
+ // leading separator.
+ const sep = "/"
+ goal := strings.Count(name, sep) + 2
+ i := len(file)
+ for n := 0; n < goal; n++ {
+ i = strings.LastIndex(file[:i], sep)
+ if i == -1 {
+ // not enough separators found, set i so that the slice expression
+ // below leaves file unmodified
+ i = -len(sep)
+ break
+ }
+ }
+ // get back to 0 or trim the leading separator
+ file = file[i+len(sep):]
+ return file
+}
diff --git a/vendor/github.com/rs/cors/.travis.yml b/vendor/github.com/rs/cors/.travis.yml
deleted file mode 100644
index bbb5185..0000000
--- a/vendor/github.com/rs/cors/.travis.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-language: go
-go:
-- 1.3
-- 1.4
diff --git a/vendor/github.com/rs/xhandler/.travis.yml b/vendor/github.com/rs/xhandler/.travis.yml
deleted file mode 100644
index b65c7a9..0000000
--- a/vendor/github.com/rs/xhandler/.travis.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-language: go
-go:
-- 1.5
-- tip
-matrix:
- allow_failures:
- - go: tip
diff --git a/vendor/github.com/rs/xhandler/xhandler.go b/vendor/github.com/rs/xhandler/xhandler.go
index 718c253..0dfcddf 100644
--- a/vendor/github.com/rs/xhandler/xhandler.go
+++ b/vendor/github.com/rs/xhandler/xhandler.go
@@ -9,7 +9,7 @@
//
// You may create net/context aware middlewares pretty much the same way as
// you would do with http.Handler.
-package xhandler
+package xhandler // import "github.com/rs/xhandler"
import (
"net/http"
diff --git a/vendor/golang.org/x/net/context/context.go b/vendor/golang.org/x/net/context/context.go
index 11bd8d3..134654c 100644
--- a/vendor/golang.org/x/net/context/context.go
+++ b/vendor/golang.org/x/net/context/context.go
@@ -34,14 +34,9 @@
//
// See http://blog.golang.org/context for example code for a server that uses
// Contexts.
-package context
+package context // import "golang.org/x/net/context"
-import (
- "errors"
- "fmt"
- "sync"
- "time"
-)
+import "time"
// A Context carries a deadline, a cancelation signal, and other values across
// API boundaries.
@@ -66,7 +61,7 @@ type Context interface {
//
// // 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 {
+ // func Stream(ctx context.Context, out chan<- Value) error {
// for {
// v, err := DoSomething(ctx)
// if err != nil {
@@ -138,48 +133,6 @@ type Context interface {
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
@@ -201,247 +154,3 @@ func TODO() Context {
// 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/golang.org/x/net/context/go17.go b/vendor/golang.org/x/net/context/go17.go
new file mode 100644
index 0000000..f8cda19
--- /dev/null
+++ b/vendor/golang.org/x/net/context/go17.go
@@ -0,0 +1,72 @@
+// Copyright 2016 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build go1.7
+
+package context
+
+import (
+ "context" // standard library's context, as of Go 1.7
+ "time"
+)
+
+var (
+ todo = context.TODO()
+ background = context.Background()
+)
+
+// Canceled is the error returned by Context.Err when the context is canceled.
+var Canceled = context.Canceled
+
+// DeadlineExceeded is the error returned by Context.Err when the context's
+// deadline passes.
+var DeadlineExceeded = context.DeadlineExceeded
+
+// WithCancel returns a copy of parent with a new Done channel. The returned
+// context's Done channel is closed when the returned cancel function is called
+// or when the parent context's Done channel is closed, whichever happens first.
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete.
+func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
+ ctx, f := context.WithCancel(parent)
+ return ctx, CancelFunc(f)
+}
+
+// WithDeadline returns a copy of the parent context with the deadline adjusted
+// to be no later than d. If the parent's deadline is already earlier than d,
+// WithDeadline(parent, d) is semantically equivalent to parent. The returned
+// context's Done channel is closed when the deadline expires, when the returned
+// cancel function is called, or when the parent context's Done channel is
+// closed, whichever happens first.
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete.
+func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
+ ctx, f := context.WithDeadline(parent, deadline)
+ return ctx, CancelFunc(f)
+}
+
+// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete:
+//
+// func slowOperationWithTimeout(ctx context.Context) (Result, error) {
+// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
+// defer cancel() // releases resources if slowOperation completes before timeout elapses
+// return slowOperation(ctx)
+// }
+func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
+ return WithDeadline(parent, time.Now().Add(timeout))
+}
+
+// WithValue returns a copy of parent in which the value associated with key is
+// val.
+//
+// Use context Values only for request-scoped data that transits processes and
+// APIs, not for passing optional parameters to functions.
+func WithValue(parent Context, key interface{}, val interface{}) Context {
+ return context.WithValue(parent, key, val)
+}
diff --git a/vendor/golang.org/x/net/context/pre_go17.go b/vendor/golang.org/x/net/context/pre_go17.go
new file mode 100644
index 0000000..5a30aca
--- /dev/null
+++ b/vendor/golang.org/x/net/context/pre_go17.go
@@ -0,0 +1,300 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !go1.7
+
+package context
+
+import (
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+)
+
+// An emptyCtx is never canceled, has no values, and has no deadline. It is not
+// struct{}, since vars of this type must have distinct addresses.
+type emptyCtx int
+
+func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
+ return
+}
+
+func (*emptyCtx) Done() <-chan struct{} {
+ return nil
+}
+
+func (*emptyCtx) Err() error {
+ return nil
+}
+
+func (*emptyCtx) Value(key interface{}) interface{} {
+ return nil
+}
+
+func (e *emptyCtx) String() string {
+ switch e {
+ case background:
+ return "context.Background"
+ case todo:
+ return "context.TODO"
+ }
+ return "unknown empty Context"
+}
+
+var (
+ background = new(emptyCtx)
+ todo = new(emptyCtx)
+)
+
+// Canceled is the error returned by Context.Err when the context is canceled.
+var Canceled = errors.New("context canceled")
+
+// DeadlineExceeded is the error returned by Context.Err when the context's
+// deadline passes.
+var DeadlineExceeded = errors.New("context deadline exceeded")
+
+// WithCancel returns a copy of parent with a new Done channel. The returned
+// context's Done channel is closed when the returned cancel function is called
+// or when the parent context's Done channel is closed, whichever happens first.
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete.
+func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
+ c := newCancelCtx(parent)
+ propagateCancel(parent, c)
+ return c, func() { c.cancel(true, Canceled) }
+}
+
+// newCancelCtx returns an initialized cancelCtx.
+func newCancelCtx(parent Context) *cancelCtx {
+ return &cancelCtx{
+ Context: parent,
+ done: make(chan struct{}),
+ }
+}
+
+// propagateCancel arranges for child to be canceled when parent is.
+func propagateCancel(parent Context, child canceler) {
+ if parent.Done() == nil {
+ return // parent is never canceled
+ }
+ if p, ok := parentCancelCtx(parent); ok {
+ p.mu.Lock()
+ if p.err != nil {
+ // parent has already been canceled
+ child.cancel(false, p.err)
+ } else {
+ if p.children == nil {
+ p.children = make(map[canceler]bool)
+ }
+ p.children[child] = true
+ }
+ p.mu.Unlock()
+ } else {
+ go func() {
+ select {
+ case <-parent.Done():
+ child.cancel(false, parent.Err())
+ case <-child.Done():
+ }
+ }()
+ }
+}
+
+// parentCancelCtx follows a chain of parent references until it finds a
+// *cancelCtx. This function understands how each of the concrete types in this
+// package represents its parent.
+func parentCancelCtx(parent Context) (*cancelCtx, bool) {
+ for {
+ switch c := parent.(type) {
+ case *cancelCtx:
+ return c, true
+ case *timerCtx:
+ return c.cancelCtx, true
+ case *valueCtx:
+ parent = c.Context
+ default:
+ return nil, false
+ }
+ }
+}
+
+// removeChild removes a context from its parent.
+func removeChild(parent Context, child canceler) {
+ p, ok := parentCancelCtx(parent)
+ if !ok {
+ return
+ }
+ p.mu.Lock()
+ if p.children != nil {
+ delete(p.children, child)
+ }
+ p.mu.Unlock()
+}
+
+// A canceler is a context type that can be canceled directly. The
+// implementations are *cancelCtx and *timerCtx.
+type canceler interface {
+ cancel(removeFromParent bool, err error)
+ Done() <-chan struct{}
+}
+
+// A cancelCtx can be canceled. When canceled, it also cancels any children
+// that implement canceler.
+type cancelCtx struct {
+ Context
+
+ done chan struct{} // closed by the first cancel call.
+
+ mu sync.Mutex
+ children map[canceler]bool // set to nil by the first cancel call
+ err error // set to non-nil by the first cancel call
+}
+
+func (c *cancelCtx) Done() <-chan struct{} {
+ return c.done
+}
+
+func (c *cancelCtx) Err() error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.err
+}
+
+func (c *cancelCtx) String() string {
+ return fmt.Sprintf("%v.WithCancel", c.Context)
+}
+
+// cancel closes c.done, cancels each of c's children, and, if
+// removeFromParent is true, removes c from its parent's children.
+func (c *cancelCtx) cancel(removeFromParent bool, err error) {
+ if err == nil {
+ panic("context: internal error: missing cancel error")
+ }
+ c.mu.Lock()
+ if c.err != nil {
+ c.mu.Unlock()
+ return // already canceled
+ }
+ c.err = err
+ close(c.done)
+ for child := range c.children {
+ // NOTE: acquiring the child's lock while holding parent's lock.
+ child.cancel(false, err)
+ }
+ c.children = nil
+ c.mu.Unlock()
+
+ if removeFromParent {
+ removeChild(c.Context, c)
+ }
+}
+
+// WithDeadline returns a copy of the parent context with the deadline adjusted
+// to be no later than d. If the parent's deadline is already earlier than d,
+// WithDeadline(parent, d) is semantically equivalent to parent. The returned
+// context's Done channel is closed when the deadline expires, when the returned
+// cancel function is called, or when the parent context's Done channel is
+// closed, whichever happens first.
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete.
+func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
+ if cur, ok := parent.Deadline(); ok && cur.Before(deadline) {
+ // The current deadline is already sooner than the new one.
+ return WithCancel(parent)
+ }
+ c := &timerCtx{
+ cancelCtx: newCancelCtx(parent),
+ deadline: deadline,
+ }
+ propagateCancel(parent, c)
+ d := deadline.Sub(time.Now())
+ if d <= 0 {
+ c.cancel(true, DeadlineExceeded) // deadline has already passed
+ return c, func() { c.cancel(true, Canceled) }
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err == nil {
+ c.timer = time.AfterFunc(d, func() {
+ c.cancel(true, DeadlineExceeded)
+ })
+ }
+ return c, func() { c.cancel(true, Canceled) }
+}
+
+// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
+// implement Done and Err. It implements cancel by stopping its timer then
+// delegating to cancelCtx.cancel.
+type timerCtx struct {
+ *cancelCtx
+ timer *time.Timer // Under cancelCtx.mu.
+
+ deadline time.Time
+}
+
+func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
+ return c.deadline, true
+}
+
+func (c *timerCtx) String() string {
+ return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now()))
+}
+
+func (c *timerCtx) cancel(removeFromParent bool, err error) {
+ c.cancelCtx.cancel(false, err)
+ if removeFromParent {
+ // Remove this timerCtx from its parent cancelCtx's children.
+ removeChild(c.cancelCtx.Context, c)
+ }
+ c.mu.Lock()
+ if c.timer != nil {
+ c.timer.Stop()
+ c.timer = nil
+ }
+ c.mu.Unlock()
+}
+
+// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete:
+//
+// func slowOperationWithTimeout(ctx context.Context) (Result, error) {
+// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
+// defer cancel() // releases resources if slowOperation completes before timeout elapses
+// return slowOperation(ctx)
+// }
+func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
+ return WithDeadline(parent, time.Now().Add(timeout))
+}
+
+// WithValue returns a copy of parent in which the value associated with key is
+// val.
+//
+// Use context Values only for request-scoped data that transits processes and
+// APIs, not for passing optional parameters to functions.
+func WithValue(parent Context, key interface{}, val interface{}) Context {
+ return &valueCtx{parent, key, val}
+}
+
+// A valueCtx carries a key-value pair. It implements Value for that key and
+// delegates all other calls to the embedded Context.
+type valueCtx struct {
+ Context
+ key, val interface{}
+}
+
+func (c *valueCtx) String() string {
+ return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val)
+}
+
+func (c *valueCtx) Value(key interface{}) interface{} {
+ if c.key == key {
+ return c.val
+ }
+ return c.Context.Value(key)
+}
diff --git a/vendor/golang.org/x/sys/PATENTS b/vendor/golang.org/x/sys/PATENTS
deleted file mode 100644
index 7330990..0000000
--- a/vendor/golang.org/x/sys/PATENTS
+++ /dev/null
@@ -1,22 +0,0 @@
-Additional IP Rights Grant (Patents)
-
-"This implementation" means the copyrightable works distributed by
-Google as part of the Go project.
-
-Google hereby grants to You a perpetual, worldwide, non-exclusive,
-no-charge, royalty-free, irrevocable (except as stated in this section)
-patent license to make, have made, use, offer to sell, sell, import,
-transfer and otherwise run, modify and propagate the contents of this
-implementation of Go, where such license applies only to those patent
-claims, both currently owned or controlled by Google and acquired in
-the future, licensable by Google that are necessarily infringed by this
-implementation of Go. This grant does not include claims that would be
-infringed only as a consequence of further modification of this
-implementation. If you or your agent or exclusive licensee institute or
-order or agree to the institution of patent litigation against any
-entity (including a cross-claim or counterclaim in a lawsuit) alleging
-that this implementation of Go or any code incorporated within this
-implementation of Go constitutes direct or contributory patent
-infringement, or inducement of patent infringement, then any patent
-rights granted to you under this License for this implementation of Go
-shall terminate as of the date such litigation is filed.
diff --git a/vendor/golang.org/x/sys/unix/.gitignore b/vendor/golang.org/x/sys/unix/.gitignore
deleted file mode 100644
index e482715..0000000
--- a/vendor/golang.org/x/sys/unix/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-_obj/
diff --git a/vendor/golang.org/x/sys/unix/asm.s b/vendor/golang.org/x/sys/unix/asm.s
deleted file mode 100644
index 8ed2fdb..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_darwin_386.s b/vendor/golang.org/x/sys/unix/asm_darwin_386.s
deleted file mode 100644
index 8a72783..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_darwin_amd64.s b/vendor/golang.org/x/sys/unix/asm_darwin_amd64.s
deleted file mode 100644
index 6321421..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_darwin_arm.s b/vendor/golang.org/x/sys/unix/asm_darwin_arm.s
deleted file mode 100644
index 333242d..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_darwin_arm64.s b/vendor/golang.org/x/sys/unix/asm_darwin_arm64.s
deleted file mode 100644
index 97e0174..0000000
--- a/vendor/golang.org/x/sys/unix/asm_darwin_arm64.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 arm64,darwin
-
-#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
- B syscall·Syscall(SB)
-
-TEXT ·Syscall6(SB),NOSPLIT,$0-80
- B syscall·Syscall6(SB)
-
-TEXT ·Syscall9(SB),NOSPLIT,$0-104
- B syscall·Syscall9(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/golang.org/x/sys/unix/asm_dragonfly_amd64.s b/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s
deleted file mode 100644
index d5ed672..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_freebsd_386.s b/vendor/golang.org/x/sys/unix/asm_freebsd_386.s
deleted file mode 100644
index c9a0a26..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_freebsd_amd64.s b/vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s
deleted file mode 100644
index 3517247..0000000
--- a/vendor/golang.org/x/sys/unix/asm_freebsd_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, FreeBSD
-//
-
-// 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/golang.org/x/sys/unix/asm_freebsd_arm.s b/vendor/golang.org/x/sys/unix/asm_freebsd_arm.s
deleted file mode 100644
index 9227c87..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_linux_386.s b/vendor/golang.org/x/sys/unix/asm_linux_386.s
deleted file mode 100644
index 4db2909..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_linux_amd64.s b/vendor/golang.org/x/sys/unix/asm_linux_amd64.s
deleted file mode 100644
index 44e25c6..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_linux_arm.s b/vendor/golang.org/x/sys/unix/asm_linux_arm.s
deleted file mode 100644
index cf0b574..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_linux_arm64.s b/vendor/golang.org/x/sys/unix/asm_linux_arm64.s
deleted file mode 100644
index 4be9bfe..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_linux_mips64x.s b/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s
deleted file mode 100644
index 724e580..0000000
--- a/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s
+++ /dev/null
@@ -1,28 +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 mips64 mips64le
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for mips64, 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)
diff --git a/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s b/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s
deleted file mode 100644
index 8d231fe..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_linux_s390x.s b/vendor/golang.org/x/sys/unix/asm_linux_s390x.s
deleted file mode 100644
index 1188985..0000000
--- a/vendor/golang.org/x/sys/unix/asm_linux_s390x.s
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build s390x
-// +build linux
-// +build !gccgo
-
-#include "textflag.h"
-
-//
-// System calls for s390x, 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/golang.org/x/sys/unix/asm_netbsd_386.s b/vendor/golang.org/x/sys/unix/asm_netbsd_386.s
deleted file mode 100644
index 48bdcd7..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_netbsd_amd64.s b/vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s
deleted file mode 100644
index 2ede05c..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_netbsd_arm.s b/vendor/golang.org/x/sys/unix/asm_netbsd_arm.s
deleted file mode 100644
index e892857..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_openbsd_386.s b/vendor/golang.org/x/sys/unix/asm_openbsd_386.s
deleted file mode 100644
index 00576f3..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_openbsd_amd64.s b/vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s
deleted file mode 100644
index 790ef77..0000000
--- a/vendor/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/golang.org/x/sys/unix/asm_solaris_amd64.s b/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s
deleted file mode 100644
index 43ed17a..0000000
--- a/vendor/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/golang.org/x/sys/unix/bluetooth_linux.go b/vendor/golang.org/x/sys/unix/bluetooth_linux.go
deleted file mode 100644
index 6e32296..0000000
--- a/vendor/golang.org/x/sys/unix/bluetooth_linux.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Bluetooth sockets and messages
-
-package unix
-
-// Bluetooth Protocols
-const (
- BTPROTO_L2CAP = 0
- BTPROTO_HCI = 1
- BTPROTO_SCO = 2
- BTPROTO_RFCOMM = 3
- BTPROTO_BNEP = 4
- BTPROTO_CMTP = 5
- BTPROTO_HIDP = 6
- BTPROTO_AVDTP = 7
-)
-
-const (
- HCI_CHANNEL_RAW = 0
- HCI_CHANNEL_USER = 1
- HCI_CHANNEL_MONITOR = 2
- HCI_CHANNEL_CONTROL = 3
-)
-
-// Socketoption Level
-const (
- SOL_BLUETOOTH = 0x112
- SOL_HCI = 0x0
- SOL_L2CAP = 0x6
- SOL_RFCOMM = 0x12
- SOL_SCO = 0x11
-)
diff --git a/vendor/golang.org/x/sys/unix/constants.go b/vendor/golang.org/x/sys/unix/constants.go
deleted file mode 100644
index a96f0eb..0000000
--- a/vendor/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/golang.org/x/sys/unix/env_unix.go b/vendor/golang.org/x/sys/unix/env_unix.go
deleted file mode 100644
index 45e281a..0000000
--- a/vendor/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/golang.org/x/sys/unix/env_unset.go b/vendor/golang.org/x/sys/unix/env_unset.go
deleted file mode 100644
index 9222262..0000000
--- a/vendor/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/golang.org/x/sys/unix/flock.go b/vendor/golang.org/x/sys/unix/flock.go
deleted file mode 100644
index ce67a59..0000000
--- a/vendor/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/golang.org/x/sys/unix/flock_linux_32bit.go b/vendor/golang.org/x/sys/unix/flock_linux_32bit.go
deleted file mode 100644
index 362831c..0000000
--- a/vendor/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/golang.org/x/sys/unix/gccgo.go b/vendor/golang.org/x/sys/unix/gccgo.go
deleted file mode 100644
index 94c8232..0000000
--- a/vendor/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/golang.org/x/sys/unix/gccgo_c.c b/vendor/golang.org/x/sys/unix/gccgo_c.c
deleted file mode 100644
index 07f6be0..0000000
--- a/vendor/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/golang.org/x/sys/unix/gccgo_linux_amd64.go b/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go
deleted file mode 100644
index bffe1a7..0000000
--- a/vendor/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/golang.org/x/sys/unix/mkall.sh b/vendor/golang.org/x/sys/unix/mkall.sh
deleted file mode 100644
index 3e224c5..0000000
--- a/vendor/golang.org/x/sys/unix/mkall.sh
+++ /dev/null
@@ -1,285 +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 signed 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 signed 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"
- ;;
-linux_s390x)
- GOOSARCH_in=syscall_linux_s390x.go
- unistd_h=/usr/include/asm/unistd.h
- mkerrors="$mkerrors -m64"
- mksysnum="./mksysnum_linux.pl $unistd_h"
- # Let the type of C char be signed to make the bare sys
- # API more consistent between platforms.
- # This is a deliberate departure from the way the syscall
- # package generates its version of the types file.
- mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
- ;;
-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 | go run mkpost.go >>ztypes_$GOOSARCH.go";
- fi
-) | $run
diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh
deleted file mode 100644
index c40d788..0000000
--- a/vendor/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/golang.org/x/sys/unix/mkpost.go b/vendor/golang.org/x/sys/unix/mkpost.go
deleted file mode 100644
index ed50d90..0000000
--- a/vendor/golang.org/x/sys/unix/mkpost.go
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-// mkpost processes the output of cgo -godefs to
-// modify the generated types. It is used to clean up
-// the sys API in an architecture specific manner.
-//
-// mkpost is run after cgo -godefs by mkall.sh.
-package main
-
-import (
- "fmt"
- "go/format"
- "io/ioutil"
- "log"
- "os"
- "regexp"
-)
-
-func main() {
- b, err := ioutil.ReadAll(os.Stdin)
- if err != nil {
- log.Fatal(err)
- }
- s := string(b)
-
- goarch := os.Getenv("GOARCH")
- goos := os.Getenv("GOOS")
- if goarch == "s390x" && goos == "linux" {
- // Export the types of PtraceRegs fields.
- re := regexp.MustCompile("ptrace(Psw|Fpregs|Per)")
- s = re.ReplaceAllString(s, "Ptrace$1")
-
- // Replace padding fields inserted by cgo with blank identifiers.
- re = regexp.MustCompile("Pad_cgo[A-Za-z0-9_]*")
- s = re.ReplaceAllString(s, "_")
-
- // Replace other unwanted fields with blank identifiers.
- re = regexp.MustCompile("X_[A-Za-z0-9_]*")
- s = re.ReplaceAllString(s, "_")
-
- // Replace the control_regs union with a blank identifier for now.
- re = regexp.MustCompile("(Control_regs)\\s+\\[0\\]uint64")
- s = re.ReplaceAllString(s, "_ [0]uint64")
- }
-
- // gofmt
- b, err = format.Source([]byte(s))
- if err != nil {
- log.Fatal(err)
- }
-
- // Append this command to the header to show where the new file
- // came from.
- re := regexp.MustCompile("(cgo -godefs [a-zA-Z0-9_]+\\.go.*)")
- b = re.ReplaceAll(b, []byte("$1 | go run mkpost.go"))
-
- fmt.Printf("%s", b)
-}
diff --git a/vendor/golang.org/x/sys/unix/mksyscall.pl b/vendor/golang.org/x/sys/unix/mksyscall.pl
deleted file mode 100644
index b1e7766..0000000
--- a/vendor/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 < uint64(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/golang.org/x/sys/unix/str.go b/vendor/golang.org/x/sys/unix/str.go
deleted file mode 100644
index 35ed664..0000000
--- a/vendor/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/golang.org/x/sys/unix/syscall.go b/vendor/golang.org/x/sys/unix/syscall.go
deleted file mode 100644
index 571e699..0000000
--- a/vendor/golang.org/x/sys/unix/syscall.go
+++ /dev/null
@@ -1,76 +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 "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
-}
-
-func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
-
-// 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/golang.org/x/sys/unix/syscall_bsd.go b/vendor/golang.org/x/sys/unix/syscall_bsd.go
deleted file mode 100644
index e967176..0000000
--- a/vendor/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/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go
deleted file mode 100644
index 3d534d2..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_darwin.go
+++ /dev/null
@@ -1,511 +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,
- )
- use(unsafe.Pointer(_p0))
- 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))
- use(unsafe.Pointer(_p0))
- 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/golang.org/x/sys/unix/syscall_darwin_386.go b/vendor/golang.org/x/sys/unix/syscall_darwin_386.go
deleted file mode 100644
index c172a3d..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_darwin_386.go
+++ /dev/null
@@ -1,77 +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 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/golang.org/x/sys/unix/syscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go
deleted file mode 100644
index fc1e5a4..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.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 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 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/golang.org/x/sys/unix/syscall_darwin_arm.go b/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go
deleted file mode 100644
index d286cf4..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go
+++ /dev/null
@@ -1,71 +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 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/golang.org/x/sys/unix/syscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go
deleted file mode 100644
index c33905c..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go
+++ /dev/null
@@ -1,77 +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 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/golang.org/x/sys/unix/syscall_dragonfly.go b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go
deleted file mode 100644
index ec408ee..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_dragonfly.go
+++ /dev/null
@@ -1,412 +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))
- use(unsafe.Pointer(_p0))
- 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/golang.org/x/sys/unix/syscall_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go
deleted file mode 100644
index da7cb79..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go
+++ /dev/null
@@ -1,61 +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 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/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go
deleted file mode 100644
index 520ccbe..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_freebsd.go
+++ /dev/null
@@ -1,683 +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))
- use(unsafe.Pointer(_p0))
- 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/golang.org/x/sys/unix/syscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go
deleted file mode 100644
index 6a0cd80..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go
+++ /dev/null
@@ -1,61 +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 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/golang.org/x/sys/unix/syscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go
deleted file mode 100644
index e142540..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go
+++ /dev/null
@@ -1,61 +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,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 = nsec / 1e9
- ts.Nsec = nsec % 1e9
- return
-}
-
-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/golang.org/x/sys/unix/syscall_freebsd_arm.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go
deleted file mode 100644
index 5504cb1..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +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 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/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go
deleted file mode 100644
index 6d10c9c..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_linux.go
+++ /dev/null
@@ -1,1115 +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 ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
-
-func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
- if len(fds) == 0 {
- return ppoll(nil, 0, timeout, sigmask)
- }
- return ppoll(&fds[0], len(fds), timeout, sigmask)
-}
-
-//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, flags int) error {
- return unlinkat(dirfd, path, flags)
-}
-
-//sys utimes(path string, times *[2]Timeval) (err error)
-
-func Utimes(path string, tv []Timeval) error {
- if tv == nil {
- err := utimensat(AT_FDCWD, path, nil, 0)
- if err != ENOSYS {
- return err
- }
- return utimes(path, nil)
- }
- if len(tv) != 2 {
- return EINVAL
- }
- var ts [2]Timespec
- ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
- ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
- err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
- if err != ENOSYS {
- return err
- }
- 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
-}
-
-type SockaddrHCI struct {
- Dev uint16
- Channel uint16
- raw RawSockaddrHCI
-}
-
-func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
- sa.raw.Family = AF_BLUETOOTH
- sa.raw.Dev = sa.Dev
- sa.raw.Channel = sa.Channel
- return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, 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 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 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)
-//sys Setns(fd int, nstype int) (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 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
-// 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/golang.org/x/sys/unix/syscall_linux_386.go b/vendor/golang.org/x/sys/unix/syscall_linux_386.go
deleted file mode 100644
index 2b881b9..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_linux_386.go
+++ /dev/null
@@ -1,399 +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 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)
-//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
-//sys Pause() (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)
-
-//sys Utime(path string, buf *Utimbuf) (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)
-}
-
-//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
-
-func Poll(fds []PollFd, timeout int) (n int, err error) {
- if len(fds) == 0 {
- return poll(nil, 0, timeout)
- }
- return poll(&fds[0], len(fds), timeout)
-}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go
deleted file mode 100644
index 18911c2..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go
+++ /dev/null
@@ -1,157 +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 EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
-//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64
-//sys Fchown(fd int, uid int, gid int) (err error)
-//sys Fstat(fd int, stat *Stat_t) (err error)
-//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 Pause() (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
-}
-
-//sys Utime(path string, buf *Utimbuf) (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 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)
-}
-
-//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
-
-func Poll(fds []PollFd, timeout int) (n int, err error) {
- if len(fds) == 0 {
- return poll(nil, 0, timeout)
- }
- return poll(&fds[0], len(fds), timeout)
-}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go
deleted file mode 100644
index 71d8702..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go
+++ /dev/null
@@ -1,263 +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)
-//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
-//sys Pause() (err error)
-
-func Time(t *Time_t) (Time_t, error) {
- var tv Timeval
- err := Gettimeofday(&tv)
- if err != nil {
- return 0, err
- }
- if t != nil {
- *t = Time_t(tv.Sec)
- }
- return Time_t(tv.Sec), nil
-}
-
-func Utime(path string, buf *Utimbuf) error {
- tv := []Timeval{
- {Sec: buf.Actime},
- {Sec: buf.Modtime},
- }
- return Utimes(path, tv)
-}
-
-//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_UGETRLIMIT
-
-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)
-}
-
-//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
-
-func Poll(fds []PollFd, timeout int) (n int, err error) {
- if len(fds) == 0 {
- return poll(nil, 0, timeout)
- }
- return poll(&fds[0], len(fds), timeout)
-}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go
deleted file mode 100644
index 4b6ff2a..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go
+++ /dev/null
@@ -1,192 +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 EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT
-//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)
-
-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 NsecToTimeval(nsec int64) (tv Timeval) {
- nsec += 999 // round up to microsecond
- tv.Sec = nsec / 1e9
- tv.Usec = nsec % 1e9 / 1e3
- return
-}
-
-func Time(t *Time_t) (Time_t, error) {
- var tv Timeval
- err := Gettimeofday(&tv)
- if err != nil {
- return 0, err
- }
- if t != nil {
- *t = Time_t(tv.Sec)
- }
- return Time_t(tv.Sec), nil
-}
-
-func Utime(path string, buf *Utimbuf) error {
- tv := []Timeval{
- {Sec: buf.Actime},
- {Sec: buf.Modtime},
- }
- return Utimes(path, tv)
-}
-
-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)
-}
-
-func Dup2(oldfd int, newfd int) (err error) {
- return Dup3(oldfd, newfd, 0)
-}
-
-func Pause() (err error) {
- _, _, e1 := Syscall6(SYS_PPOLL, 0, 0, 0, 0, 0, 0)
- if e1 != 0 {
- err = errnoErr(e1)
- }
- return
-}
-
-// 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
-)
-
-func Poll(fds []PollFd, timeout int) (n int, err error) {
- var ts *Timespec
- if timeout >= 0 {
- ts = new(Timespec)
- *ts = NsecToTimespec(int64(timeout) * 1e6)
- }
- if len(fds) == 0 {
- return ppoll(nil, 0, ts, nil)
- }
- return ppoll(&fds[0], len(fds), ts, nil)
-}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go
deleted file mode 100644
index 440f54e..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go
+++ /dev/null
@@ -1,215 +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 mips64 mips64le
-
-package unix
-
-// Linux introduced getdents64 syscall for N64 ABI only in 3.10
-// (May 21 2013, rev dec33abaafc89bcbd78f85fad0513170415a26d5),
-// to support older kernels, we have to use getdents for mips64.
-// Also note that struct dirent is different for these two.
-// Lookup linux_dirent{,64} in kernel source code for details.
-const _SYS_getdents = SYS_GETDENTS
-
-//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
-//sys Fchown(fd int, uid int, gid 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 Lchown(path string, uid int, gid int) (err error)
-//sys Listen(s int, n int) (err error)
-//sys Pause() (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)
-//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)
-
-func Time(t *Time_t) (tt Time_t, err error) {
- var tv Timeval
- err = Gettimeofday(&tv)
- if err != nil {
- return 0, err
- }
- if t != nil {
- *t = Time_t(tv.Sec)
- }
- return Time_t(tv.Sec), nil
-}
-
-//sys Utime(path string, buf *Utimbuf) (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 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 Ioperm(from int, num int, on int) (err error) {
- return ENOSYS
-}
-
-func Iopl(level int) (err error) {
- return ENOSYS
-}
-
-type stat_t struct {
- Dev uint32
- Pad0 [3]int32
- Ino uint64
- Mode uint32
- Nlink uint32
- Uid uint32
- Gid uint32
- Rdev uint32
- Pad1 [3]uint32
- Size int64
- Atime uint32
- Atime_nsec uint32
- Mtime uint32
- Mtime_nsec uint32
- Ctime uint32
- Ctime_nsec uint32
- Blksize uint32
- Pad2 uint32
- Blocks int64
-}
-
-//sys fstat(fd int, st *stat_t) (err error)
-//sys lstat(path string, st *stat_t) (err error)
-//sys stat(path string, st *stat_t) (err error)
-
-func Fstat(fd int, s *Stat_t) (err error) {
- st := &stat_t{}
- err = fstat(fd, st)
- fillStat_t(s, st)
- return
-}
-
-func Lstat(path string, s *Stat_t) (err error) {
- st := &stat_t{}
- err = lstat(path, st)
- fillStat_t(s, st)
- return
-}
-
-func Stat(path string, s *Stat_t) (err error) {
- st := &stat_t{}
- err = stat(path, st)
- fillStat_t(s, st)
- return
-}
-
-func fillStat_t(s *Stat_t, st *stat_t) {
- s.Dev = st.Dev
- s.Ino = st.Ino
- s.Mode = st.Mode
- s.Nlink = st.Nlink
- s.Uid = st.Uid
- s.Gid = st.Gid
- s.Rdev = st.Rdev
- s.Size = st.Size
- s.Atim = Timespec{int64(st.Atime), int64(st.Atime_nsec)}
- s.Mtim = Timespec{int64(st.Mtime), int64(st.Mtime_nsec)}
- s.Ctim = Timespec{int64(st.Ctime), int64(st.Ctime_nsec)}
- s.Blksize = st.Blksize
- s.Blocks = st.Blocks
-}
-
-func (r *PtraceRegs) PC() uint64 { return r.Regs[64] }
-
-func (r *PtraceRegs) SetPC(pc uint64) { r.Regs[64] = 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)
-}
-
-//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
-
-func Poll(fds []PollFd, timeout int) (n int, err error) {
- if len(fds) == 0 {
- return poll(nil, 0, timeout)
- }
- return poll(&fds[0], len(fds), timeout)
-}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go
deleted file mode 100644
index 60770f6..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go
+++ /dev/null
@@ -1,135 +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 EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
-//sys Dup2(oldfd int, newfd int) (err error)
-//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)
-//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 Pause() (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)
-
-//sys Utime(path string, buf *Utimbuf) (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 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)
-}
-
-//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
-}
-
-//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
-
-func Poll(fds []PollFd, timeout int) (n int, err error) {
- if len(fds) == 0 {
- return poll(nil, 0, timeout)
- }
- return poll(&fds[0], len(fds), timeout)
-}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go
deleted file mode 100644
index 81c5f47..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go
+++ /dev/null
@@ -1,329 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build s390x,linux
-
-package unix
-
-import (
- "unsafe"
-)
-
-//sys Dup2(oldfd int, newfd int) (err error)
-//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
-//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64
-//sys Fchown(fd int, uid int, gid int) (err error)
-//sys Fstat(fd int, stat *Stat_t) (err error)
-//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 Lchown(path string, uid int, gid int) (err error)
-//sys Lstat(path string, stat *Stat_t) (err error)
-//sys Pause() (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 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)
-//sysnb getgroups(n int, list *_Gid_t) (nn int, err error)
-//sysnb setgroups(n int, list *_Gid_t) (err error)
-
-func Getpagesize() int { return 4096 }
-
-//sysnb Gettimeofday(tv *Timeval) (err error)
-
-func Time(t *Time_t) (tt Time_t, err error) {
- var tv Timeval
- err = Gettimeofday(&tv)
- if err != nil {
- return 0, err
- }
- if t != nil {
- *t = Time_t(tv.Sec)
- }
- return Time_t(tv.Sec), nil
-}
-
-//sys Utime(path string, buf *Utimbuf) (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 NsecToTimeval(nsec int64) (tv Timeval) {
- nsec += 999 // round up to microsecond
- tv.Sec = nsec / 1e9
- tv.Usec = nsec % 1e9 / 1e3
- return
-}
-
-//sysnb pipe2(p *[2]_C_int, flags int) (err error)
-
-func Pipe(p []int) (err error) {
- if len(p) != 2 {
- return EINVAL
- }
- var pp [2]_C_int
- err = pipe2(&pp, 0) // pipe2 is the same as pipe when flags are set to 0.
- p[0] = int(pp[0])
- p[1] = int(pp[1])
- return
-}
-
-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 Ioperm(from int, num int, on int) (err error) {
- return ENOSYS
-}
-
-func Iopl(level int) (err error) {
- return ENOSYS
-}
-
-func (r *PtraceRegs) PC() uint64 { return r.Psw.Addr }
-
-func (r *PtraceRegs) SetPC(pc uint64) { r.Psw.Addr = 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)
-}
-
-// Linux on s390x uses the old mmap interface, which requires arguments to be passed in a struct.
-// mmap2 also requires arguments to be passed in a struct; it is currently not exposed in .
-func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
- mmap_args := [6]uintptr{addr, length, uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)}
- r0, _, e1 := Syscall(SYS_MMAP, uintptr(unsafe.Pointer(&mmap_args[0])), 0, 0)
- use(unsafe.Pointer(&mmap_args[0]))
- xaddr = uintptr(r0)
- if e1 != 0 {
- err = errnoErr(e1)
- }
- return
-}
-
-// On s390x Linux, all the socket calls go through an extra indirection.
-// The arguments to the underlying system call (SYS_SOCKETCALL) are the
-// number below and a pointer to an array of uintptr.
-const (
- // see linux/net.h
- netSocket = 1
- netBind = 2
- netConnect = 3
- netListen = 4
- netAccept = 5
- netGetSockName = 6
- netGetPeerName = 7
- netSocketPair = 8
- netSend = 9
- netRecv = 10
- netSendTo = 11
- netRecvFrom = 12
- netShutdown = 13
- netSetSockOpt = 14
- netGetSockOpt = 15
- netSendMsg = 16
- netRecvMsg = 17
- netAccept4 = 18
- netRecvMMsg = 19
- netSendMMsg = 20
-)
-
-func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (int, error) {
- args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))}
- fd, _, err := Syscall(SYS_SOCKETCALL, netAccept, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return 0, err
- }
- return int(fd), nil
-}
-
-func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (int, error) {
- args := [4]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags)}
- fd, _, err := Syscall(SYS_SOCKETCALL, netAccept4, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return 0, err
- }
- return int(fd), nil
-}
-
-func getsockname(s int, rsa *RawSockaddrAny, addrlen *_Socklen) error {
- args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))}
- _, _, err := RawSyscall(SYS_SOCKETCALL, netGetSockName, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return err
- }
- return nil
-}
-
-func getpeername(s int, rsa *RawSockaddrAny, addrlen *_Socklen) error {
- args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))}
- _, _, err := RawSyscall(SYS_SOCKETCALL, netGetPeerName, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return err
- }
- return nil
-}
-
-func socketpair(domain int, typ int, flags int, fd *[2]int32) error {
- args := [4]uintptr{uintptr(domain), uintptr(typ), uintptr(flags), uintptr(unsafe.Pointer(fd))}
- _, _, err := RawSyscall(SYS_SOCKETCALL, netSocketPair, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return err
- }
- return nil
-}
-
-func bind(s int, addr unsafe.Pointer, addrlen _Socklen) error {
- args := [3]uintptr{uintptr(s), uintptr(addr), uintptr(addrlen)}
- _, _, err := Syscall(SYS_SOCKETCALL, netBind, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return err
- }
- return nil
-}
-
-func connect(s int, addr unsafe.Pointer, addrlen _Socklen) error {
- args := [3]uintptr{uintptr(s), uintptr(addr), uintptr(addrlen)}
- _, _, err := Syscall(SYS_SOCKETCALL, netConnect, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return err
- }
- return nil
-}
-
-func socket(domain int, typ int, proto int) (int, error) {
- args := [3]uintptr{uintptr(domain), uintptr(typ), uintptr(proto)}
- fd, _, err := RawSyscall(SYS_SOCKETCALL, netSocket, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return 0, err
- }
- return int(fd), nil
-}
-
-func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) error {
- args := [5]uintptr{uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen))}
- _, _, err := Syscall(SYS_SOCKETCALL, netGetSockOpt, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return err
- }
- return nil
-}
-
-func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) error {
- args := [4]uintptr{uintptr(s), uintptr(level), uintptr(name), uintptr(val)}
- _, _, err := Syscall(SYS_SOCKETCALL, netSetSockOpt, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return err
- }
- return nil
-}
-
-func recvfrom(s int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (int, error) {
- var base uintptr
- if len(p) > 0 {
- base = uintptr(unsafe.Pointer(&p[0]))
- }
- args := [6]uintptr{uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))}
- n, _, err := Syscall(SYS_SOCKETCALL, netRecvFrom, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return 0, err
- }
- return int(n), nil
-}
-
-func sendto(s int, p []byte, flags int, to unsafe.Pointer, addrlen _Socklen) error {
- var base uintptr
- if len(p) > 0 {
- base = uintptr(unsafe.Pointer(&p[0]))
- }
- args := [6]uintptr{uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(to), uintptr(addrlen)}
- _, _, err := Syscall(SYS_SOCKETCALL, netSendTo, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return err
- }
- return nil
-}
-
-func recvmsg(s int, msg *Msghdr, flags int) (int, error) {
- args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)}
- n, _, err := Syscall(SYS_SOCKETCALL, netRecvMsg, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return 0, err
- }
- return int(n), nil
-}
-
-func sendmsg(s int, msg *Msghdr, flags int) (int, error) {
- args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)}
- n, _, err := Syscall(SYS_SOCKETCALL, netSendMsg, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return 0, err
- }
- return int(n), nil
-}
-
-func Listen(s int, n int) error {
- args := [2]uintptr{uintptr(s), uintptr(n)}
- _, _, err := Syscall(SYS_SOCKETCALL, netListen, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return err
- }
- return nil
-}
-
-func Shutdown(s, how int) error {
- args := [2]uintptr{uintptr(s), uintptr(how)}
- _, _, err := Syscall(SYS_SOCKETCALL, netShutdown, uintptr(unsafe.Pointer(&args)), 0)
- if err != 0 {
- return err
- }
- return nil
-}
-
-//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
-
-func Poll(fds []PollFd, timeout int) (n int, err error) {
- if len(fds) == 0 {
- return poll(nil, 0, timeout)
- }
- return poll(&fds[0], len(fds), timeout)
-}
diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/golang.org/x/sys/unix/syscall_netbsd.go
deleted file mode 100644
index c4e945c..0000000
--- a/vendor/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/golang.org/x/sys/unix/syscall_netbsd_386.go b/vendor/golang.org/x/sys/unix/syscall_netbsd_386.go
deleted file mode 100644
index afaca09..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_netbsd_386.go
+++ /dev/null
@@ -1,42 +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 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/golang.org/x/sys/unix/syscall_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go
deleted file mode 100644
index a6ff04c..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go
+++ /dev/null
@@ -1,42 +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 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/golang.org/x/sys/unix/syscall_netbsd_arm.go b/vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go
deleted file mode 100644
index 68a6969..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go
+++ /dev/null
@@ -1,42 +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 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/golang.org/x/sys/unix/syscall_no_getwd.go b/vendor/golang.org/x/sys/unix/syscall_no_getwd.go
deleted file mode 100644
index 530792e..0000000
--- a/vendor/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/golang.org/x/sys/unix/syscall_openbsd.go b/vendor/golang.org/x/sys/unix/syscall_openbsd.go
deleted file mode 100644
index 554a823..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_openbsd.go
+++ /dev/null
@@ -1,304 +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))
- use(unsafe.Pointer(_p0))
- 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/golang.org/x/sys/unix/syscall_openbsd_386.go b/vendor/golang.org/x/sys/unix/syscall_openbsd_386.go
deleted file mode 100644
index a66ddc5..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_openbsd_386.go
+++ /dev/null
@@ -1,42 +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 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/golang.org/x/sys/unix/syscall_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go
deleted file mode 100644
index 0776c1f..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go
+++ /dev/null
@@ -1,42 +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 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/golang.org/x/sys/unix/syscall_solaris.go b/vendor/golang.org/x/sys/unix/syscall_solaris.go
deleted file mode 100644
index eb489b1..0000000
--- a/vendor/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, flags int) (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/golang.org/x/sys/unix/syscall_solaris_amd64.go b/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go
deleted file mode 100644
index 5aff62c..0000000
--- a/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go
+++ /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 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 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/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go
deleted file mode 100644
index b46b250..0000000
--- a/vendor/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/golang.org/x/sys/unix/types_darwin.go b/vendor/golang.org/x/sys/unix/types_darwin.go
deleted file mode 100644
index 1153261..0000000
--- a/vendor/golang.org/x/sys/unix/types_darwin.go
+++ /dev/null
@@ -1,250 +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 ignore
-
-/*
-Input to cgo -godefs. See also mkerrors.sh and mkall.sh
-*/
-
-// +godefs map struct_in_addr [4]byte /* in_addr */
-// +godefs map struct_in6_addr [16]byte /* in6_addr */
-
-package unix
-
-/*
-#define __DARWIN_UNIX03 0
-#define KERNEL
-#define _DARWIN_USE_64_BIT_INODE
-#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
-#include
-#include
-#include
-
-enum {
- sizeofPtr = sizeof(void*),
-};
-
-union sockaddr_all {
- struct sockaddr s1; // this one gets used for fields
- struct sockaddr_in s2; // these pad it out
- struct sockaddr_in6 s3;
- struct sockaddr_un s4;
- struct sockaddr_dl s5;
-};
-
-struct sockaddr_any {
- struct sockaddr addr;
- char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
-};
-
-*/
-import "C"
-
-// Machine characteristics; for internal use.
-
-const (
- sizeofPtr = C.sizeofPtr
- sizeofShort = C.sizeof_short
- sizeofInt = C.sizeof_int
- sizeofLong = C.sizeof_long
- sizeofLongLong = C.sizeof_longlong
-)
-
-// Basic types
-
-type (
- _C_short C.short
- _C_int C.int
- _C_long C.long
- _C_long_long C.longlong
-)
-
-// Time
-
-type Timespec C.struct_timespec
-
-type Timeval C.struct_timeval
-
-type Timeval32 C.struct_timeval32
-
-// Processes
-
-type Rusage C.struct_rusage
-
-type Rlimit C.struct_rlimit
-
-type _Gid_t C.gid_t
-
-// Files
-
-type Stat_t C.struct_stat64
-
-type Statfs_t C.struct_statfs64
-
-type Flock_t C.struct_flock
-
-type Fstore_t C.struct_fstore
-
-type Radvisory_t C.struct_radvisory
-
-type Fbootstraptransfer_t C.struct_fbootstraptransfer
-
-type Log2phys_t C.struct_log2phys
-
-type Fsid C.struct_fsid
-
-type Dirent C.struct_dirent
-
-// Sockets
-
-type RawSockaddrInet4 C.struct_sockaddr_in
-
-type RawSockaddrInet6 C.struct_sockaddr_in6
-
-type RawSockaddrUnix C.struct_sockaddr_un
-
-type RawSockaddrDatalink C.struct_sockaddr_dl
-
-type RawSockaddr C.struct_sockaddr
-
-type RawSockaddrAny C.struct_sockaddr_any
-
-type _Socklen C.socklen_t
-
-type Linger C.struct_linger
-
-type Iovec C.struct_iovec
-
-type IPMreq C.struct_ip_mreq
-
-type IPv6Mreq C.struct_ipv6_mreq
-
-type Msghdr C.struct_msghdr
-
-type Cmsghdr C.struct_cmsghdr
-
-type Inet4Pktinfo C.struct_in_pktinfo
-
-type Inet6Pktinfo C.struct_in6_pktinfo
-
-type IPv6MTUInfo C.struct_ip6_mtuinfo
-
-type ICMPv6Filter C.struct_icmp6_filter
-
-const (
- SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in
- SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
- SizeofSockaddrAny = C.sizeof_struct_sockaddr_any
- SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
- SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl
- SizeofLinger = C.sizeof_struct_linger
- SizeofIPMreq = C.sizeof_struct_ip_mreq
- SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq
- SizeofMsghdr = C.sizeof_struct_msghdr
- SizeofCmsghdr = C.sizeof_struct_cmsghdr
- SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo
- SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo
- SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo
- SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter
-)
-
-// Ptrace requests
-
-const (
- PTRACE_TRACEME = C.PT_TRACE_ME
- PTRACE_CONT = C.PT_CONTINUE
- PTRACE_KILL = C.PT_KILL
-)
-
-// Events (kqueue, kevent)
-
-type Kevent_t C.struct_kevent
-
-// Select
-
-type FdSet C.fd_set
-
-// Routing and interface messages
-
-const (
- SizeofIfMsghdr = C.sizeof_struct_if_msghdr
- SizeofIfData = C.sizeof_struct_if_data
- SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr
- SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr
- SizeofIfmaMsghdr2 = C.sizeof_struct_ifma_msghdr2
- SizeofRtMsghdr = C.sizeof_struct_rt_msghdr
- SizeofRtMetrics = C.sizeof_struct_rt_metrics
-)
-
-type IfMsghdr C.struct_if_msghdr
-
-type IfData C.struct_if_data
-
-type IfaMsghdr C.struct_ifa_msghdr
-
-type IfmaMsghdr C.struct_ifma_msghdr
-
-type IfmaMsghdr2 C.struct_ifma_msghdr2
-
-type RtMsghdr C.struct_rt_msghdr
-
-type RtMetrics C.struct_rt_metrics
-
-// Berkeley packet filter
-
-const (
- SizeofBpfVersion = C.sizeof_struct_bpf_version
- SizeofBpfStat = C.sizeof_struct_bpf_stat
- SizeofBpfProgram = C.sizeof_struct_bpf_program
- SizeofBpfInsn = C.sizeof_struct_bpf_insn
- SizeofBpfHdr = C.sizeof_struct_bpf_hdr
-)
-
-type BpfVersion C.struct_bpf_version
-
-type BpfStat C.struct_bpf_stat
-
-type BpfProgram C.struct_bpf_program
-
-type BpfInsn C.struct_bpf_insn
-
-type BpfHdr C.struct_bpf_hdr
-
-// Terminal handling
-
-type Termios C.struct_termios
-
-// fchmodat-like syscalls.
-
-const (
- AT_FDCWD = C.AT_FDCWD
- AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW
-)
diff --git a/vendor/golang.org/x/sys/unix/types_dragonfly.go b/vendor/golang.org/x/sys/unix/types_dragonfly.go
deleted file mode 100644
index f3c971d..0000000
--- a/vendor/golang.org/x/sys/unix/types_dragonfly.go
+++ /dev/null
@@ -1,242 +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 ignore
-
-/*
-Input to cgo -godefs. See also mkerrors.sh and mkall.sh
-*/
-
-// +godefs map struct_in_addr [4]byte /* in_addr */
-// +godefs map struct_in6_addr [16]byte /* in6_addr */
-
-package unix
-
-/*
-#define KERNEL
-#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
-
-enum {
- sizeofPtr = sizeof(void*),
-};
-
-union sockaddr_all {
- struct sockaddr s1; // this one gets used for fields
- struct sockaddr_in s2; // these pad it out
- struct sockaddr_in6 s3;
- struct sockaddr_un s4;
- struct sockaddr_dl s5;
-};
-
-struct sockaddr_any {
- struct sockaddr addr;
- char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
-};
-
-*/
-import "C"
-
-// Machine characteristics; for internal use.
-
-const (
- sizeofPtr = C.sizeofPtr
- sizeofShort = C.sizeof_short
- sizeofInt = C.sizeof_int
- sizeofLong = C.sizeof_long
- sizeofLongLong = C.sizeof_longlong
-)
-
-// Basic types
-
-type (
- _C_short C.short
- _C_int C.int
- _C_long C.long
- _C_long_long C.longlong
-)
-
-// Time
-
-type Timespec C.struct_timespec
-
-type Timeval C.struct_timeval
-
-// Processes
-
-type Rusage C.struct_rusage
-
-type Rlimit C.struct_rlimit
-
-type _Gid_t C.gid_t
-
-// Files
-
-const ( // Directory mode bits
- S_IFMT = C.S_IFMT
- S_IFIFO = C.S_IFIFO
- S_IFCHR = C.S_IFCHR
- S_IFDIR = C.S_IFDIR
- S_IFBLK = C.S_IFBLK
- S_IFREG = C.S_IFREG
- S_IFLNK = C.S_IFLNK
- S_IFSOCK = C.S_IFSOCK
- S_ISUID = C.S_ISUID
- S_ISGID = C.S_ISGID
- S_ISVTX = C.S_ISVTX
- S_IRUSR = C.S_IRUSR
- S_IWUSR = C.S_IWUSR
- S_IXUSR = C.S_IXUSR
-)
-
-type Stat_t C.struct_stat
-
-type Statfs_t C.struct_statfs
-
-type Flock_t C.struct_flock
-
-type Dirent C.struct_dirent
-
-type Fsid C.struct_fsid
-
-// Sockets
-
-type RawSockaddrInet4 C.struct_sockaddr_in
-
-type RawSockaddrInet6 C.struct_sockaddr_in6
-
-type RawSockaddrUnix C.struct_sockaddr_un
-
-type RawSockaddrDatalink C.struct_sockaddr_dl
-
-type RawSockaddr C.struct_sockaddr
-
-type RawSockaddrAny C.struct_sockaddr_any
-
-type _Socklen C.socklen_t
-
-type Linger C.struct_linger
-
-type Iovec C.struct_iovec
-
-type IPMreq C.struct_ip_mreq
-
-type IPv6Mreq C.struct_ipv6_mreq
-
-type Msghdr C.struct_msghdr
-
-type Cmsghdr C.struct_cmsghdr
-
-type Inet6Pktinfo C.struct_in6_pktinfo
-
-type IPv6MTUInfo C.struct_ip6_mtuinfo
-
-type ICMPv6Filter C.struct_icmp6_filter
-
-const (
- SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in
- SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
- SizeofSockaddrAny = C.sizeof_struct_sockaddr_any
- SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
- SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl
- SizeofLinger = C.sizeof_struct_linger
- SizeofIPMreq = C.sizeof_struct_ip_mreq
- SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq
- SizeofMsghdr = C.sizeof_struct_msghdr
- SizeofCmsghdr = C.sizeof_struct_cmsghdr
- SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo
- SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo
- SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter
-)
-
-// Ptrace requests
-
-const (
- PTRACE_TRACEME = C.PT_TRACE_ME
- PTRACE_CONT = C.PT_CONTINUE
- PTRACE_KILL = C.PT_KILL
-)
-
-// Events (kqueue, kevent)
-
-type Kevent_t C.struct_kevent
-
-// Select
-
-type FdSet C.fd_set
-
-// Routing and interface messages
-
-const (
- SizeofIfMsghdr = C.sizeof_struct_if_msghdr
- SizeofIfData = C.sizeof_struct_if_data
- SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr
- SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr
- SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr
- SizeofRtMsghdr = C.sizeof_struct_rt_msghdr
- SizeofRtMetrics = C.sizeof_struct_rt_metrics
-)
-
-type IfMsghdr C.struct_if_msghdr
-
-type IfData C.struct_if_data
-
-type IfaMsghdr C.struct_ifa_msghdr
-
-type IfmaMsghdr C.struct_ifma_msghdr
-
-type IfAnnounceMsghdr C.struct_if_announcemsghdr
-
-type RtMsghdr C.struct_rt_msghdr
-
-type RtMetrics C.struct_rt_metrics
-
-// Berkeley packet filter
-
-const (
- SizeofBpfVersion = C.sizeof_struct_bpf_version
- SizeofBpfStat = C.sizeof_struct_bpf_stat
- SizeofBpfProgram = C.sizeof_struct_bpf_program
- SizeofBpfInsn = C.sizeof_struct_bpf_insn
- SizeofBpfHdr = C.sizeof_struct_bpf_hdr
-)
-
-type BpfVersion C.struct_bpf_version
-
-type BpfStat C.struct_bpf_stat
-
-type BpfProgram C.struct_bpf_program
-
-type BpfInsn C.struct_bpf_insn
-
-type BpfHdr C.struct_bpf_hdr
-
-// Terminal handling
-
-type Termios C.struct_termios
diff --git a/vendor/golang.org/x/sys/unix/types_freebsd.go b/vendor/golang.org/x/sys/unix/types_freebsd.go
deleted file mode 100644
index ae24557..0000000
--- a/vendor/golang.org/x/sys/unix/types_freebsd.go
+++ /dev/null
@@ -1,353 +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 ignore
-
-/*
-Input to cgo -godefs. See also mkerrors.sh and mkall.sh
-*/
-
-// +godefs map struct_in_addr [4]byte /* in_addr */
-// +godefs map struct_in6_addr [16]byte /* in6_addr */
-
-package unix
-
-/*
-#define KERNEL
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include