diff --git a/application/library/caddy/caddy.go b/application/library/caddy/caddy.go index 33bfd48be3..2f7bedeac4 100644 --- a/application/library/caddy/caddy.go +++ b/application/library/caddy/caddy.go @@ -20,6 +20,7 @@ package caddy import ( "bufio" + "context" "errors" "fmt" "io" @@ -54,6 +55,7 @@ var ( PidFile: `./caddy.pid`, } DefaultVersion = `2.0.0` + EnableReload = true ) func TrapSignals() { @@ -97,6 +99,7 @@ func Fixed(c *Config) { c.appName = `nging` c.appVersion = echo.String(`VERSION`, DefaultVersion) c.Agreed = true + c.ctx, c.cancel = context.WithCancel(context.Background()) } type Config struct { @@ -124,6 +127,12 @@ type Config struct { appName string instance *caddy.Instance stopped bool + ctx context.Context + cancel context.CancelFunc +} + +func now() string { + return time.Now().Format(`2006-01-02 15:04:05`) } func (c *Config) Start() error { @@ -140,36 +149,58 @@ func (c *Config) Start() error { if err != nil { return err } + + if EnableReload { + c.watchingSignal() + } + // Start your engines c.instance, err = caddy.Start(caddyfile) if err != nil { return err } - // Execute instantiation events - caddy.EmitEvent(caddy.InstanceStartupEvent, c.instance) + msgbox.Success(`Caddy`, `Server has been successfully started at `+now()) - // Listen to keypress of "return" and restart the app automatically + // Twiddle your thumbs + c.instance.Wait() + return nil +} + +// Listen to keypress of "return" and restart the app automatically +func (c *Config) watchingSignal() { + debug := false go func() { + if debug { + msgbox.Info(`Caddy`, `listen return ==> `+now()) + } in := bufio.NewReader(os.Stdin) for { - input, _ := in.ReadString('\n') - if input == "\n" || input == "\r\n" { - c.Restart() - } - if c.stopped { - break + select { + case <-c.ctx.Done(): + return + default: + if debug { + msgbox.Info(`Caddy`, `reading ==> `+now()) + } + input, _ := in.ReadString(com.LF) + if input == com.StrLF || input == com.StrCRLF { + if debug { + msgbox.Info(`Caddy`, `restart ==> `+now()) + } + c.Restart() + } else { + if debug { + msgbox.Info(`Caddy`, `waiting ==> `+now()) + } + } } } }() - - // Twiddle your thumbs - c.instance.Wait() - return nil } func (c *Config) Restart() error { - msgbox.Info(`Information`, `Caddy Server has been successfully reloaded at `+time.Now().Format(`2006-01-02 15:04:05`)) + defer msgbox.Success(`Caddy`, `Server has been successfully reloaded at `+now()) if c.instance == nil { return nil } @@ -187,6 +218,10 @@ func (c *Config) Restart() error { func (c *Config) Stop() error { c.stopped = true + defer func() { + c.cancel() + msgbox.Success(`Caddy`, `Server has been successfully stopped at `+now()) + }() if c.instance == nil { return nil } diff --git a/application/library/config/cliconfig.go b/application/library/config/cliconfig.go index 279fa10f57..b860b7be29 100644 --- a/application/library/config/cliconfig.go +++ b/application/library/config/cliconfig.go @@ -213,7 +213,11 @@ func (c *CLIConfig) CmdSendSignal(typeName string, sig os.Signal) error { if cmd.Process == nil { return nil } - return cmd.Process.Signal(sig) + err := cmd.Process.Signal(sig) + if err != nil && (cmd.ProcessState == nil || cmd.ProcessState.Exited()) { + err = nil + } + return err } func (c *CLIConfig) Kill(cmd *exec.Cmd) error { diff --git a/application/library/config/cliconfig_caddy.go b/application/library/config/cliconfig_caddy.go index defb6e2286..366c20c839 100644 --- a/application/library/config/cliconfig_caddy.go +++ b/application/library/config/cliconfig_caddy.go @@ -23,6 +23,7 @@ import ( "os" "github.com/admpub/log" + "github.com/admpub/nging/application/library/caddy" "github.com/webx-top/com" ) @@ -39,8 +40,12 @@ func (c *CLIConfig) CaddyStart(writer ...io.Writer) (err error) { log.Error(err.Error()) } params := []string{os.Args[0], `--config`, c.Conf, `--type`, `webserver`} - c.caddyCh = com.NewCmdChanReader() - c.cmds["caddy"] = com.RunCmdWithReaderWriter(params, c.caddyCh, writer...) + if caddy.EnableReload { + c.caddyCh = com.NewCmdChanReader() + c.cmds["caddy"] = com.RunCmdWithReaderWriter(params, c.caddyCh, writer...) + } else { + c.cmds["caddy"] = com.RunCmdWithWriter(params, writer...) + } return nil } @@ -54,14 +59,13 @@ func (c *CLIConfig) CaddyStop() error { return c.CmdStop("caddy") } -var eol = []byte("\n") - func (c *CLIConfig) CaddyReload() error { if c.caddyCh == nil || com.IsWindows { //windows不支持重载,需要重启 return c.CaddyRestart() } - c.caddyCh.Send(eol) + c.caddyCh.Send(com.BreakLine) return nil + //c.CmdSendSignal("caddy", os.Interrupt) } func (c *CLIConfig) CaddyRestart(writer ...io.Writer) error { diff --git a/application/library/msgbox/msgbox.go b/application/library/msgbox/msgbox.go index 1ff2477931..c17f97ca80 100644 --- a/application/library/msgbox/msgbox.go +++ b/application/library/msgbox/msgbox.go @@ -20,9 +20,11 @@ package msgbox import ( "fmt" + "io" "os" "strings" + isatty "github.com/admpub/go-isatty" "github.com/admpub/go-pretty/table" "github.com/admpub/go-pretty/text" ) @@ -47,14 +49,34 @@ func Debug(title, content string, args ...interface{}) { Render(title, content, `debug`, args...) } +func Colorable(w io.Writer) bool { + file, ok := w.(*os.File) + if !ok { + return false + } + if isatty.IsTerminal(file.Fd()) { + return true + } + if isatty.IsCygwinTerminal(file.Fd()) { + return true + } + return false +} + +var StdoutColorable = Colorable(os.Stdout) + func Render(title, content, typ string, args ...interface{}) { + if len(args) > 0 { + content = fmt.Sprintf(content, args...) + } + if !StdoutColorable { + os.Stdout.WriteString(`[` + strings.ToUpper(typ) + `][` + title + `] ` + content + "\n") + return + } t := table.NewWriter() t.SetOutputMirror(os.Stdout) t.AppendHeader(table.Row{title}) t.AppendRow([]interface{}{""}) - if len(args) > 0 { - content = fmt.Sprintf(content, args...) - } for _, row := range strings.Split(content, "\n") { t.AppendRow([]interface{}{row}) } diff --git a/vendor/github.com/admpub/go-isatty/LICENSE b/vendor/github.com/admpub/go-isatty/LICENSE new file mode 100644 index 0000000000..65dc692b6b --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/LICENSE @@ -0,0 +1,9 @@ +Copyright (c) Yasuhiro MATSUMOTO + +MIT License (Expat) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/admpub/go-isatty/README.md b/vendor/github.com/admpub/go-isatty/README.md new file mode 100644 index 0000000000..1e69004bb0 --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/README.md @@ -0,0 +1,50 @@ +# go-isatty + +[![Godoc Reference](https://godoc.org/github.com/mattn/go-isatty?status.svg)](http://godoc.org/github.com/mattn/go-isatty) +[![Build Status](https://travis-ci.org/mattn/go-isatty.svg?branch=master)](https://travis-ci.org/mattn/go-isatty) +[![Coverage Status](https://coveralls.io/repos/github/mattn/go-isatty/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-isatty?branch=master) +[![Go Report Card](https://goreportcard.com/badge/mattn/go-isatty)](https://goreportcard.com/report/mattn/go-isatty) + +isatty for golang + +## Usage + +```go +package main + +import ( + "fmt" + "github.com/mattn/go-isatty" + "os" +) + +func main() { + if isatty.IsTerminal(os.Stdout.Fd()) { + fmt.Println("Is Terminal") + } else if isatty.IsCygwinTerminal(os.Stdout.Fd()) { + fmt.Println("Is Cygwin/MSYS2 Terminal") + } else { + fmt.Println("Is Not Terminal") + } +} +``` + +## Installation + +``` +$ go get github.com/mattn/go-isatty +``` + +## License + +MIT + +## Author + +Yasuhiro Matsumoto (a.k.a mattn) + +## Thanks + +* k-takata: base idea for IsCygwinTerminal + + https://github.com/k-takata/go-iscygpty diff --git a/vendor/github.com/admpub/go-isatty/doc.go b/vendor/github.com/admpub/go-isatty/doc.go new file mode 100644 index 0000000000..17d4f90ebc --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/doc.go @@ -0,0 +1,2 @@ +// Package isatty implements interface to isatty +package isatty diff --git a/vendor/github.com/admpub/go-isatty/go.mod b/vendor/github.com/admpub/go-isatty/go.mod new file mode 100644 index 0000000000..f310320c33 --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/go.mod @@ -0,0 +1,3 @@ +module github.com/mattn/go-isatty + +require golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 diff --git a/vendor/github.com/admpub/go-isatty/go.sum b/vendor/github.com/admpub/go-isatty/go.sum new file mode 100644 index 0000000000..426c8973c0 --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/go.sum @@ -0,0 +1,2 @@ +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/admpub/go-isatty/isatty_android.go b/vendor/github.com/admpub/go-isatty/isatty_android.go new file mode 100644 index 0000000000..d3567cb5bf --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/isatty_android.go @@ -0,0 +1,23 @@ +// +build android + +package isatty + +import ( + "syscall" + "unsafe" +) + +const ioctlReadTermios = syscall.TCGETS + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var termios syscall.Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 +} + +// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/admpub/go-isatty/isatty_bsd.go b/vendor/github.com/admpub/go-isatty/isatty_bsd.go new file mode 100644 index 0000000000..07e93039db --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/isatty_bsd.go @@ -0,0 +1,24 @@ +// +build darwin freebsd openbsd netbsd dragonfly +// +build !appengine + +package isatty + +import ( + "syscall" + "unsafe" +) + +const ioctlReadTermios = syscall.TIOCGETA + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var termios syscall.Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 +} + +// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/admpub/go-isatty/isatty_others.go b/vendor/github.com/admpub/go-isatty/isatty_others.go new file mode 100644 index 0000000000..ff714a3761 --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/isatty_others.go @@ -0,0 +1,15 @@ +// +build appengine js nacl + +package isatty + +// IsTerminal returns true if the file descriptor is terminal which +// is always false on js and appengine classic which is a sandboxed PaaS. +func IsTerminal(fd uintptr) bool { + return false +} + +// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/admpub/go-isatty/isatty_solaris.go b/vendor/github.com/admpub/go-isatty/isatty_solaris.go new file mode 100644 index 0000000000..bdd5c79a07 --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/isatty_solaris.go @@ -0,0 +1,22 @@ +// +build solaris +// +build !appengine + +package isatty + +import ( + "golang.org/x/sys/unix" +) + +// IsTerminal returns true if the given file descriptor is a terminal. +// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c +func IsTerminal(fd uintptr) bool { + var termio unix.Termio + err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio) + return err == nil +} + +// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/admpub/go-isatty/isatty_tcgets.go b/vendor/github.com/admpub/go-isatty/isatty_tcgets.go new file mode 100644 index 0000000000..453b025d0d --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/isatty_tcgets.go @@ -0,0 +1,19 @@ +// +build linux aix +// +build !appengine +// +build !android + +package isatty + +import "golang.org/x/sys/unix" + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + _, err := unix.IoctlGetTermios(int(fd), unix.TCGETS) + return err == nil +} + +// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/admpub/go-isatty/isatty_windows.go b/vendor/github.com/admpub/go-isatty/isatty_windows.go new file mode 100644 index 0000000000..af51cbcaa4 --- /dev/null +++ b/vendor/github.com/admpub/go-isatty/isatty_windows.go @@ -0,0 +1,94 @@ +// +build windows +// +build !appengine + +package isatty + +import ( + "strings" + "syscall" + "unicode/utf16" + "unsafe" +) + +const ( + fileNameInfo uintptr = 2 + fileTypePipe = 3 +) + +var ( + kernel32 = syscall.NewLazyDLL("kernel32.dll") + procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx") + procGetFileType = kernel32.NewProc("GetFileType") +) + +func init() { + // Check if GetFileInformationByHandleEx is available. + if procGetFileInformationByHandleEx.Find() != nil { + procGetFileInformationByHandleEx = nil + } +} + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var st uint32 + r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) + return r != 0 && e == 0 +} + +// Check pipe name is used for cygwin/msys2 pty. +// Cygwin/MSYS2 PTY has a name like: +// \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master +func isCygwinPipeName(name string) bool { + token := strings.Split(name, "-") + if len(token) < 5 { + return false + } + + if token[0] != `\msys` && token[0] != `\cygwin` { + return false + } + + if token[1] == "" { + return false + } + + if !strings.HasPrefix(token[2], "pty") { + return false + } + + if token[3] != `from` && token[3] != `to` { + return false + } + + if token[4] != "master" { + return false + } + + return true +} + +// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 +// terminal. +func IsCygwinTerminal(fd uintptr) bool { + if procGetFileInformationByHandleEx == nil { + return false + } + + // Cygwin/msys's pty is a pipe. + ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0) + if ft != fileTypePipe || e != 0 { + return false + } + + var buf [2 + syscall.MAX_PATH]uint16 + r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), + 4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)), + uintptr(len(buf)*2), 0, 0) + if r == 0 || e != 0 { + return false + } + + l := *(*uint32)(unsafe.Pointer(&buf)) + return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2]))) +} diff --git a/vendor/github.com/caddyserver/caddy/README.md b/vendor/github.com/caddyserver/caddy/README.md index 5139e93ef4..9cd0f5907f 100644 --- a/vendor/github.com/caddyserver/caddy/README.md +++ b/vendor/github.com/caddyserver/caddy/README.md @@ -4,7 +4,7 @@

Every Site on HTTPS

Caddy is a general-purpose HTTP/2 web server that serves HTTPS by default.

- +
diff --git a/vendor/github.com/caddyserver/caddy/caddyhttp/basicauth/basicauth.go b/vendor/github.com/caddyserver/caddy/caddyhttp/basicauth/basicauth.go index 81cd47f71b..36fc2a1365 100644 --- a/vendor/github.com/caddyserver/caddy/caddyhttp/basicauth/basicauth.go +++ b/vendor/github.com/caddyserver/caddy/caddyhttp/basicauth/basicauth.go @@ -33,8 +33,8 @@ import ( "strings" "sync" - "github.com/jimstudt/http-authentication/basic" "github.com/caddyserver/caddy/caddyhttp/httpserver" + "github.com/jimstudt/http-authentication/basic" ) // BasicAuth is middleware to protect resources with a username and password. diff --git a/vendor/github.com/caddyserver/caddy/caddyhttp/browse/browse.go b/vendor/github.com/caddyserver/caddy/caddyhttp/browse/browse.go index eab7c5e128..8cd5332814 100644 --- a/vendor/github.com/caddyserver/caddy/caddyhttp/browse/browse.go +++ b/vendor/github.com/caddyserver/caddy/caddyhttp/browse/browse.go @@ -29,9 +29,9 @@ import ( "text/template" "time" - "github.com/dustin/go-humanize" "github.com/caddyserver/caddy/caddyhttp/httpserver" "github.com/caddyserver/caddy/caddyhttp/staticfiles" + "github.com/dustin/go-humanize" ) const ( diff --git a/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/logger.go b/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/logger.go index 8db33107b6..e5c9ac0277 100644 --- a/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/logger.go +++ b/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/logger.go @@ -23,8 +23,8 @@ import ( "strings" "sync" - gsyslog "github.com/hashicorp/go-syslog" "github.com/caddyserver/caddy" + gsyslog "github.com/hashicorp/go-syslog" ) var remoteSyslogPrefixes = map[string]string{ diff --git a/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/plugin.go b/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/plugin.go index 606c71b09c..ecd9229834 100644 --- a/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/plugin.go +++ b/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/plugin.go @@ -655,6 +655,7 @@ var directives = []string{ "filter", // github.com/echocat/caddy-filter "ipfilter", // github.com/pyed/ipfilter "ratelimit", // github.com/xuqingfeng/caddy-rate-limit + "recaptcha", // github.com/defund/caddy-recaptcha "expires", // github.com/epicagency/caddy-expires "forwardproxy", // github.com/caddyserver/forwardproxy "basicauth", @@ -664,14 +665,14 @@ var directives = []string{ "s3browser", // github.com/techknowlogick/caddy-s3browser "nobots", // github.com/Xumeiquer/nobots "mime", - "login", // github.com/tarent/loginsrv/caddy - "reauth", // github.com/freman/caddy-reauth - "extauth", // github.com/BTBurke/caddy-extauth - "jwt", // github.com/BTBurke/caddy-jwt - "permission", // github.com/dhaavi/caddy-permission - "jsonp", // github.com/pschlump/caddy-jsonp - "upload", // blitznote.com/src/caddy.upload - "multipass", // github.com/namsral/multipass/caddy + "login", // github.com/tarent/loginsrv/caddy + "reauth", // github.com/freman/caddy-reauth + "extauth", // github.com/BTBurke/caddy-extauth + "jwt", // github.com/BTBurke/caddy-jwt + "permission", // github.com/dhaavi/caddy-permission + "jsonp", // github.com/pschlump/caddy-jsonp + "upload", // blitznote.com/src/caddy.upload + "multipass", // github.com/namsral/multipass/caddy "internal", "pprof", "expvar", diff --git a/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/server.go b/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/server.go index 5368407b41..3bd434c2f0 100644 --- a/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/server.go +++ b/vendor/github.com/caddyserver/caddy/caddyhttp/httpserver/server.go @@ -31,11 +31,11 @@ import ( "strings" "time" - "github.com/lucas-clemente/quic-go/h2quic" "github.com/caddyserver/caddy" "github.com/caddyserver/caddy/caddyhttp/staticfiles" "github.com/caddyserver/caddy/caddytls" "github.com/caddyserver/caddy/telemetry" + "github.com/lucas-clemente/quic-go/h2quic" ) // Server is the HTTP server implementation. diff --git a/vendor/github.com/caddyserver/caddy/caddyhttp/proxy/reverseproxy.go b/vendor/github.com/caddyserver/caddy/caddyhttp/proxy/reverseproxy.go index a223d3532e..ac126ad308 100644 --- a/vendor/github.com/caddyserver/caddy/caddyhttp/proxy/reverseproxy.go +++ b/vendor/github.com/caddyserver/caddy/caddyhttp/proxy/reverseproxy.go @@ -41,9 +41,9 @@ import ( "golang.org/x/net/http2" + "github.com/caddyserver/caddy/caddyhttp/httpserver" "github.com/lucas-clemente/quic-go" "github.com/lucas-clemente/quic-go/h2quic" - "github.com/caddyserver/caddy/caddyhttp/httpserver" ) var ( diff --git a/vendor/github.com/caddyserver/caddy/caddyhttp/requestid/requestid.go b/vendor/github.com/caddyserver/caddy/caddyhttp/requestid/requestid.go index 83d76d7ad5..fb9b7d0a1b 100644 --- a/vendor/github.com/caddyserver/caddy/caddyhttp/requestid/requestid.go +++ b/vendor/github.com/caddyserver/caddy/caddyhttp/requestid/requestid.go @@ -19,8 +19,8 @@ import ( "log" "net/http" - "github.com/google/uuid" "github.com/caddyserver/caddy/caddyhttp/httpserver" + "github.com/google/uuid" ) // Handler is a middleware handler diff --git a/vendor/github.com/caddyserver/caddy/caddyhttp/staticfiles/fileserver.go b/vendor/github.com/caddyserver/caddy/caddyhttp/staticfiles/fileserver.go index 273498553e..5690ceb934 100644 --- a/vendor/github.com/caddyserver/caddy/caddyhttp/staticfiles/fileserver.go +++ b/vendor/github.com/caddyserver/caddy/caddyhttp/staticfiles/fileserver.go @@ -184,15 +184,14 @@ func (fs FileServer) serveFile(w http.ResponseWriter, r *http.Request) (int, err return http.StatusNotFound, nil } - etag := calculateEtag(d) - + etagInfo := d // look for compressed versions of the file on disk, if the client supports that encoding for _, encoding := range staticEncodingPriority { // see if the client accepts a compressed encoding we offer acceptEncoding := strings.Split(r.Header.Get("Accept-Encoding"), ",") accepted := false for _, acc := range acceptEncoding { - if strings.TrimSpace(acc) == encoding { + if strings.TrimSpace(acc) == encoding.name { accepted = true break } @@ -204,7 +203,7 @@ func (fs FileServer) serveFile(w http.ResponseWriter, r *http.Request) (int, err } // see if the compressed version of this file exists - encodedFile, err := fs.Root.Open(reqPath + staticEncoding[encoding]) + encodedFile, err := fs.Root.Open(reqPath + encoding.ext) if err != nil { continue } @@ -222,13 +221,15 @@ func (fs FileServer) serveFile(w http.ResponseWriter, r *http.Request) (int, err // the encoded file is now what we're serving f = encodedFile - etag = calculateEtag(encodedFileInfo) + etagInfo = encodedFileInfo w.Header().Add("Vary", "Accept-Encoding") - w.Header().Set("Content-Encoding", encoding) + w.Header().Set("Content-Encoding", encoding.name) w.Header().Set("Content-Length", strconv.FormatInt(encodedFileInfo.Size(), 10)) break } + etag := calculateEtag(etagInfo) + // Set the ETag returned to the user-agent. Note that a conditional If-None-Match // request is handled in http.ServeContent below, which checks against this ETag value. w.Header().Set("ETag", etag) @@ -279,16 +280,9 @@ var DefaultIndexPages = []string{ "default.txt", } -// staticEncoding is a map of content-encoding to a file extension. -// If client accepts given encoding (via Accept-Encoding header) and compressed file with given extensions exists -// it will be served to the client instead of original one. -var staticEncoding = map[string]string{ - "gzip": ".gz", - "br": ".br", -} - // staticEncodingPriority is a list of preferred static encodings (most efficient compression to least one). -var staticEncodingPriority = []string{ - "br", - "gzip", +var staticEncodingPriority = []struct{ name, ext string }{ + {"zstd", ".zst"}, + {"br", ".br"}, + {"gzip", ".gz"}, } diff --git a/vendor/github.com/caddyserver/caddy/caddyhttp/websocket/setup.go b/vendor/github.com/caddyserver/caddy/caddyhttp/websocket/setup.go index bebd9b5b4a..9a09efea06 100644 --- a/vendor/github.com/caddyserver/caddy/caddyhttp/websocket/setup.go +++ b/vendor/github.com/caddyserver/caddy/caddyhttp/websocket/setup.go @@ -15,6 +15,8 @@ package websocket import ( + "strconv" + "github.com/caddyserver/caddy" "github.com/caddyserver/caddy/caddyhttp/httpserver" ) @@ -45,21 +47,38 @@ func setup(c *caddy.Controller) error { func webSocketParse(c *caddy.Controller) ([]Config, error) { var websocks []Config - var respawn bool - optionalBlock := func() (hadBlock bool, err error) { - for c.NextBlock() { - hadBlock = true - if c.Val() == "respawn" { - respawn = true - } else { - return true, c.Err("Expected websocket configuration parameter in block") + for c.Next() { + var respawn bool + var wsType string + var bufSize int + + optionalBlock := func() (hadBlock bool, err error) { + for c.NextBlock() { + hadBlock = true + if c.Val() == "respawn" { + respawn = true + } else if c.Val() == "type" { + arg := c.RemainingArgs() + if len(arg) > 0 { + wsType = arg[0] + } + } else if c.Val() == "bufsize" { + arg := c.RemainingArgs() + if len(arg) > 0 { + var err error + bufSize, err = strconv.Atoi(arg[0]) + if (bufSize < 0) || (err != nil) { + bufSize = 0 + } + } + } else { + return true, c.Err("Expected websocket configuration parameter in block") + } } + return } - return - } - for c.Next() { var val, path, command string // Path or command; not sure which yet @@ -97,11 +116,17 @@ func webSocketParse(c *caddy.Controller) ([]Config, error) { return nil, err } + if wsType == "" { + wsType = "lines" + } + websocks = append(websocks, Config{ Path: path, Command: cmd, Arguments: args, Respawn: respawn, // TODO: This isn't used currently + Type: wsType, + BufSize: bufSize, }) } diff --git a/vendor/github.com/caddyserver/caddy/caddyhttp/websocket/websocket.go b/vendor/github.com/caddyserver/caddy/caddyhttp/websocket/websocket.go index 69b10ca729..074623c6c7 100644 --- a/vendor/github.com/caddyserver/caddy/caddyhttp/websocket/websocket.go +++ b/vendor/github.com/caddyserver/caddy/caddyhttp/websocket/websocket.go @@ -28,9 +28,10 @@ import ( "os/exec" "strings" "time" + "unicode/utf8" - "github.com/gorilla/websocket" "github.com/caddyserver/caddy/caddyhttp/httpserver" + "github.com/gorilla/websocket" ) const ( @@ -76,6 +77,27 @@ type ( Command string Arguments []string Respawn bool // TODO: Not used, but parser supports it until we decide on it + Type string + BufSize int + } + + wsGetUpgrader interface { + GetUpgrader() wsUpgrader + } + + wsUpgrader interface { + Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (wsConn, error) + } + + wsConn interface { + Close() error + ReadMessage() (messageType int, p []byte, err error) + SetPongHandler(h func(appData string) error) + SetReadDeadline(t time.Time) error + SetReadLimit(limit int64) + SetWriteDeadline(t time.Time) error + WriteControl(messageType int, data []byte, deadline time.Time) error + WriteMessage(messageType int, data []byte) error } ) @@ -94,12 +116,19 @@ func (ws WebSocket) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, erro // serveWS is used for setting and upgrading the HTTP connection to a websocket connection. // It also spawns the child process that is associated with matched HTTP path/url. func serveWS(w http.ResponseWriter, r *http.Request, config *Config) (int, error) { - upgrader := websocket.Upgrader{ - ReadBufferSize: 1024, - WriteBufferSize: 1024, - CheckOrigin: func(r *http.Request) bool { return true }, + gu, castok := w.(wsGetUpgrader) + var u wsUpgrader + if gu != nil && castok { + u = gu.GetUpgrader() + } else { + u = &realWsUpgrader{o: &websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, + CheckOrigin: func(r *http.Request) bool { return true }, + }} } - conn, err := upgrader.Upgrade(w, r, nil) + + conn, err := u.Upgrade(w, r, nil) if err != nil { // the connection has been "handled" -- WriteHeader was called with Upgrade, // so don't return an error status code; just return an error @@ -133,8 +162,8 @@ func serveWS(w http.ResponseWriter, r *http.Request, config *Config) (int, error } done := make(chan struct{}) - go pumpStdout(conn, stdout, done) - pumpStdin(conn, stdin) + go pumpStdout(conn, stdout, done, config) + pumpStdin(conn, stdin, config) _ = stdin.Close() // close stdin to end the process @@ -220,7 +249,7 @@ func buildEnv(cmdPath string, r *http.Request) (metavars []string, err error) { // pumpStdin handles reading data from the websocket connection and writing // it to stdin of the process. -func pumpStdin(conn *websocket.Conn, stdin io.WriteCloser) { +func pumpStdin(conn wsConn, stdin io.WriteCloser, config *Config) { // Setup our connection's websocket ping/pong handlers from our const values. defer conn.Close() conn.SetReadLimit(maxMessageSize) @@ -238,7 +267,10 @@ func pumpStdin(conn *websocket.Conn, stdin io.WriteCloser) { if err != nil { break } - message = append(message, '\n') + if config.Type == "lines" { + // no '\n' from client, so append '\n' to spawned process + message = append(message, '\n') + } if _, err := stdin.Write(message); err != nil { break } @@ -247,32 +279,102 @@ func pumpStdin(conn *websocket.Conn, stdin io.WriteCloser) { // pumpStdout handles reading data from stdout of the process and writing // it to websocket connection. -func pumpStdout(conn *websocket.Conn, stdout io.Reader, done chan struct{}) { +func pumpStdout(conn wsConn, stdout io.Reader, done chan struct{}, config *Config) { go pinger(conn, done) defer func() { _ = conn.Close() close(done) // make sure to close the pinger when we are done. }() - s := bufio.NewScanner(stdout) - for s.Scan() { - if err := conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { - log.Println("[ERROR] failed to set write deadline: ", err) + if config.Type == "lines" { + // message must end with '\n' + s := bufio.NewScanner(stdout) + if config.BufSize > 0 { + s.Buffer(make([]byte, config.BufSize), config.BufSize) } - if err := conn.WriteMessage(websocket.TextMessage, bytes.TrimSpace(s.Bytes())); err != nil { - break + for s.Scan() { + if err := conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { + log.Println("[ERROR] failed to set write deadline: ", err) + } + if err := conn.WriteMessage(websocket.TextMessage, bytes.TrimSpace(s.Bytes())); err != nil { + break + } } - } - if s.Err() != nil { - err := conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseGoingAway, s.Err().Error()), time.Time{}) - if err != nil { - log.Println("[ERROR] WriteControl failed: ", err) + if s.Err() != nil { + err := conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseGoingAway, s.Err().Error()), time.Time{}) + if err != nil { + log.Println("[ERROR] WriteControl failed: ", err) + } + } + } else if config.Type == "text" { + // handle UTF-8 text message, newline is not required + r := bufio.NewReader(stdout) + var err1 error + var len int + remainBuf := make([]byte, utf8.UTFMax) + remainLen := 0 + bufSize := config.BufSize + if bufSize <= 0 { + bufSize = 2048 + } + for { + out := make([]byte, bufSize) + copy(out[:remainLen], remainBuf[:remainLen]) + len, err1 = r.Read(out[remainLen:]) + if err1 != nil { + break + } + len += remainLen + remainLen = findIncompleteRuneLength(out, len) + if remainLen > 0 { + remainBuf = out[len-remainLen : len] + } + if err := conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { + log.Println("[ERROR] failed to set write deadline: ", err) + } + if err := conn.WriteMessage(websocket.TextMessage, out[0:len-remainLen]); err != nil { + break + } + } + if err1 != nil { + err := conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseGoingAway, err1.Error()), time.Time{}) + if err != nil { + log.Println("[ERROR] WriteControl failed: ", err) + } + } + } else if config.Type == "binary" { + // treat message as binary data + r := bufio.NewReader(stdout) + var err1 error + var len int + bufSize := config.BufSize + if bufSize <= 0 { + bufSize = 2048 + } + for { + out := make([]byte, bufSize) + len, err1 = r.Read(out) + if err1 != nil { + break + } + if err := conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil { + log.Println("[ERROR] failed to set write deadline: ", err) + } + if err := conn.WriteMessage(websocket.BinaryMessage, out[0:len]); err != nil { + break + } + } + if err1 != nil { + err := conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseGoingAway, err1.Error()), time.Time{}) + if err != nil { + log.Println("[ERROR] WriteControl failed: ", err) + } } } } // pinger simulates the websocket to keep it alive with ping messages. -func pinger(conn *websocket.Conn, done chan struct{}) { +func pinger(conn wsConn, done chan struct{}) { ticker := time.NewTicker(pingPeriod) defer ticker.Stop() @@ -291,3 +393,90 @@ func pinger(conn *websocket.Conn, done chan struct{}) { } } } + +type realWsUpgrader struct { + o *websocket.Upgrader +} + +type realWsConn struct { + o *websocket.Conn +} + +func (u *realWsUpgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (wsConn, error) { + a, b := u.o.Upgrade(w, r, responseHeader) + return &realWsConn{o: a}, b +} + +func (c *realWsConn) Close() error { + return c.o.Close() +} +func (c *realWsConn) ReadMessage() (messageType int, p []byte, err error) { + return c.o.ReadMessage() +} +func (c *realWsConn) SetPongHandler(h func(appData string) error) { + c.o.SetPongHandler(h) +} +func (c *realWsConn) SetReadDeadline(t time.Time) error { + return c.o.SetReadDeadline(t) +} +func (c *realWsConn) SetReadLimit(limit int64) { + c.o.SetReadLimit(limit) +} +func (c *realWsConn) SetWriteDeadline(t time.Time) error { + return c.o.SetWriteDeadline(t) +} +func (c *realWsConn) WriteControl(messageType int, data []byte, deadline time.Time) error { + return c.o.WriteControl(messageType, data, deadline) +} +func (c *realWsConn) WriteMessage(messageType int, data []byte) error { + return c.o.WriteMessage(messageType, data) +} + +func findIncompleteRuneLength(p []byte, length int) int { + if length == 0 { + return 0 + } + if rune(p[length-1]) < utf8.RuneSelf { + // ASCII 7-bit always complete + return 0 + } + + lowest := length - utf8.UTFMax + if lowest < 0 { + lowest = 0 + } + for start := length - 1; start >= lowest; start-- { + if (p[start] >> 5) == 0x06 { + // 2-byte utf-8 start byte + if length-start >= 2 { + // enough bytes + return 0 + } + // 1 byte outstanding + return 1 + } + + if (p[start] >> 4) == 0x0E { + // 3-byte utf-8 start byte + if length-start >= 3 { + // enough bytes + return 0 + } + // some bytes outstanding + return length - start + } + + if (p[start] >> 3) == 0x1E { + // 4-byte utf-8 start byte + if length-start >= 4 { + // enough bytes + return 0 + } + // some bytes outstanding + return length - start + } + } + + // No utf-8 start byte + return 0 +} diff --git a/vendor/github.com/caddyserver/caddy/caddytls/config.go b/vendor/github.com/caddyserver/caddy/caddytls/config.go index 817fb0da85..365b54600f 100644 --- a/vendor/github.com/caddyserver/caddy/caddytls/config.go +++ b/vendor/github.com/caddyserver/caddy/caddytls/config.go @@ -23,9 +23,9 @@ import ( "github.com/go-acme/lego/challenge/tlsalpn01" + "github.com/caddyserver/caddy" "github.com/go-acme/lego/certcrypto" "github.com/klauspost/cpuid" - "github.com/caddyserver/caddy" "github.com/mholt/certmagic" ) diff --git a/vendor/github.com/caddyserver/caddy/caddytls/tls.go b/vendor/github.com/caddyserver/caddy/caddytls/tls.go index 6af8745924..9e15713aa9 100644 --- a/vendor/github.com/caddyserver/caddy/caddytls/tls.go +++ b/vendor/github.com/caddyserver/caddy/caddytls/tls.go @@ -29,8 +29,8 @@ package caddytls import ( - "github.com/go-acme/lego/challenge" "github.com/caddyserver/caddy" + "github.com/go-acme/lego/challenge" "github.com/mholt/certmagic" ) diff --git a/vendor/github.com/caddyserver/caddy/onevent/on.go b/vendor/github.com/caddyserver/caddy/onevent/on.go index 2ba99e8b70..1124d67bd3 100644 --- a/vendor/github.com/caddyserver/caddy/onevent/on.go +++ b/vendor/github.com/caddyserver/caddy/onevent/on.go @@ -3,9 +3,9 @@ package onevent import ( "strings" - "github.com/google/uuid" "github.com/caddyserver/caddy" "github.com/caddyserver/caddy/onevent/hook" + "github.com/google/uuid" ) func init() { diff --git a/vendor/github.com/cheekybits/genny/LICENSE b/vendor/github.com/cheekybits/genny/LICENSE deleted file mode 100644 index 519d7f2272..0000000000 --- a/vendor/github.com/cheekybits/genny/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 cheekybits - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/github.com/cheekybits/genny/generic/doc.go b/vendor/github.com/cheekybits/genny/generic/doc.go deleted file mode 100644 index 3bd6c869c0..0000000000 --- a/vendor/github.com/cheekybits/genny/generic/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package generic contains the generic marker types. -package generic diff --git a/vendor/github.com/cheekybits/genny/generic/generic.go b/vendor/github.com/cheekybits/genny/generic/generic.go deleted file mode 100644 index 04a2306cbf..0000000000 --- a/vendor/github.com/cheekybits/genny/generic/generic.go +++ /dev/null @@ -1,13 +0,0 @@ -package generic - -// Type is the placeholder type that indicates a generic value. -// When genny is executed, variables of this type will be replaced with -// references to the specific types. -// var GenericType generic.Type -type Type interface{} - -// Number is the placehoder type that indiccates a generic numerical value. -// When genny is executed, variables of this type will be replaced with -// references to the specific types. -// var GenericType generic.Number -type Number float64 diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/ack_eliciting.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/ack_eliciting.go deleted file mode 100644 index 23940d982e..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/ack_eliciting.go +++ /dev/null @@ -1,23 +0,0 @@ -package ackhandler - -import "github.com/lucas-clemente/quic-go/internal/wire" - -// IsFrameAckEliciting returns true if the frame is ack-eliciting. -func IsFrameAckEliciting(f wire.Frame) bool { - switch f.(type) { - case *wire.AckFrame: - return false - default: - return true - } -} - -// HasAckElicitingFrames returns true if at least one frame is ack-eliciting. -func HasAckElicitingFrames(fs []wire.Frame) bool { - for _, f := range fs { - if IsFrameAckEliciting(f) { - return true - } - } - return false -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/gen.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/gen.go deleted file mode 100644 index 32235f81ab..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/gen.go +++ /dev/null @@ -1,3 +0,0 @@ -package ackhandler - -//go:generate genny -pkg ackhandler -in ../utils/linkedlist/linkedlist.go -out packet_linkedlist.go gen Item=Packet diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/interfaces.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/interfaces.go deleted file mode 100644 index 905d628055..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/interfaces.go +++ /dev/null @@ -1,55 +0,0 @@ -package ackhandler - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - "github.com/lucas-clemente/quic-go/quictrace" -) - -// SentPacketHandler handles ACKs received for outgoing packets -type SentPacketHandler interface { - // SentPacket may modify the packet - SentPacket(packet *Packet) - SentPacketsAsRetransmission(packets []*Packet, retransmissionOf protocol.PacketNumber) - ReceivedAck(ackFrame *wire.AckFrame, withPacketNumber protocol.PacketNumber, encLevel protocol.EncryptionLevel, recvTime time.Time) error - DropPackets(protocol.EncryptionLevel) - ResetForRetry() error - - // The SendMode determines if and what kind of packets can be sent. - SendMode() SendMode - // TimeUntilSend is the time when the next packet should be sent. - // It is used for pacing packets. - TimeUntilSend() time.Time - // ShouldSendNumPackets returns the number of packets that should be sent immediately. - // It always returns a number greater or equal than 1. - // A number greater than 1 is returned when the pacing delay is smaller than the minimum pacing delay. - // Note that the number of packets is only calculated based on the pacing algorithm. - // Before sending any packet, SendingAllowed() must be called to learn if we can actually send it. - ShouldSendNumPackets() int - - // only to be called once the handshake is complete - GetLowestPacketNotConfirmedAcked() protocol.PacketNumber - DequeuePacketForRetransmission() *Packet - DequeueProbePacket() (*Packet, error) - - PeekPacketNumber(protocol.EncryptionLevel) (protocol.PacketNumber, protocol.PacketNumberLen) - PopPacketNumber(protocol.EncryptionLevel) protocol.PacketNumber - - GetAlarmTimeout() time.Time - OnAlarm() error - - // report some congestion statistics. For tracing only. - GetStats() *quictrace.TransportState -} - -// ReceivedPacketHandler handles ACKs needed to send for incoming packets -type ReceivedPacketHandler interface { - ReceivedPacket(pn protocol.PacketNumber, encLevel protocol.EncryptionLevel, rcvTime time.Time, shouldInstigateAck bool) error - IgnoreBelow(protocol.PacketNumber) - DropPackets(protocol.EncryptionLevel) - - GetAlarmTimeout() time.Time - GetAckFrame(protocol.EncryptionLevel) *wire.AckFrame -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/packet.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/packet.go deleted file mode 100644 index 5dfa608bae..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/packet.go +++ /dev/null @@ -1,30 +0,0 @@ -package ackhandler - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" -) - -// A Packet is a packet -type Packet struct { - PacketNumber protocol.PacketNumber - PacketType protocol.PacketType - Ack *wire.AckFrame - Frames []wire.Frame - Length protocol.ByteCount - EncryptionLevel protocol.EncryptionLevel - SendTime time.Time - - largestAcked protocol.PacketNumber // if the packet contains an ACK, the LargestAcked value of that ACK - - // There are two reasons why a packet cannot be retransmitted: - // * it was already retransmitted - // * this packet is a retransmission, and we already received an ACK for the original packet - canBeRetransmitted bool - includedInBytesInFlight bool - retransmittedAs []protocol.PacketNumber - isRetransmission bool // we need a separate bool here because 0 is a valid packet number - retransmissionOf protocol.PacketNumber -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/packet_linkedlist.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/packet_linkedlist.go deleted file mode 100644 index bb74f4ef93..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/packet_linkedlist.go +++ /dev/null @@ -1,217 +0,0 @@ -// This file was automatically generated by genny. -// Any changes will be lost if this file is regenerated. -// see https://github.com/cheekybits/genny - -package ackhandler - -// Linked list implementation from the Go standard library. - -// PacketElement is an element of a linked list. -type PacketElement struct { - // Next and previous pointers in the doubly-linked list of elements. - // To simplify the implementation, internally a list l is implemented - // as a ring, such that &l.root is both the next element of the last - // list element (l.Back()) and the previous element of the first list - // element (l.Front()). - next, prev *PacketElement - - // The list to which this element belongs. - list *PacketList - - // The value stored with this element. - Value Packet -} - -// Next returns the next list element or nil. -func (e *PacketElement) Next() *PacketElement { - if p := e.next; e.list != nil && p != &e.list.root { - return p - } - return nil -} - -// Prev returns the previous list element or nil. -func (e *PacketElement) Prev() *PacketElement { - if p := e.prev; e.list != nil && p != &e.list.root { - return p - } - return nil -} - -// PacketList is a linked list of Packets. -type PacketList struct { - root PacketElement // sentinel list element, only &root, root.prev, and root.next are used - len int // current list length excluding (this) sentinel element -} - -// Init initializes or clears list l. -func (l *PacketList) Init() *PacketList { - l.root.next = &l.root - l.root.prev = &l.root - l.len = 0 - return l -} - -// NewPacketList returns an initialized list. -func NewPacketList() *PacketList { return new(PacketList).Init() } - -// Len returns the number of elements of list l. -// The complexity is O(1). -func (l *PacketList) Len() int { return l.len } - -// Front returns the first element of list l or nil if the list is empty. -func (l *PacketList) Front() *PacketElement { - if l.len == 0 { - return nil - } - return l.root.next -} - -// Back returns the last element of list l or nil if the list is empty. -func (l *PacketList) Back() *PacketElement { - if l.len == 0 { - return nil - } - return l.root.prev -} - -// lazyInit lazily initializes a zero List value. -func (l *PacketList) lazyInit() { - if l.root.next == nil { - l.Init() - } -} - -// insert inserts e after at, increments l.len, and returns e. -func (l *PacketList) insert(e, at *PacketElement) *PacketElement { - n := at.next - at.next = e - e.prev = at - e.next = n - n.prev = e - e.list = l - l.len++ - return e -} - -// insertValue is a convenience wrapper for insert(&Element{Value: v}, at). -func (l *PacketList) insertValue(v Packet, at *PacketElement) *PacketElement { - return l.insert(&PacketElement{Value: v}, at) -} - -// remove removes e from its list, decrements l.len, and returns e. -func (l *PacketList) remove(e *PacketElement) *PacketElement { - e.prev.next = e.next - e.next.prev = e.prev - e.next = nil // avoid memory leaks - e.prev = nil // avoid memory leaks - e.list = nil - l.len-- - return e -} - -// Remove removes e from l if e is an element of list l. -// It returns the element value e.Value. -// The element must not be nil. -func (l *PacketList) Remove(e *PacketElement) Packet { - if e.list == l { - // if e.list == l, l must have been initialized when e was inserted - // in l or l == nil (e is a zero Element) and l.remove will crash - l.remove(e) - } - return e.Value -} - -// PushFront inserts a new element e with value v at the front of list l and returns e. -func (l *PacketList) PushFront(v Packet) *PacketElement { - l.lazyInit() - return l.insertValue(v, &l.root) -} - -// PushBack inserts a new element e with value v at the back of list l and returns e. -func (l *PacketList) PushBack(v Packet) *PacketElement { - l.lazyInit() - return l.insertValue(v, l.root.prev) -} - -// InsertBefore inserts a new element e with value v immediately before mark and returns e. -// If mark is not an element of l, the list is not modified. -// The mark must not be nil. -func (l *PacketList) InsertBefore(v Packet, mark *PacketElement) *PacketElement { - if mark.list != l { - return nil - } - // see comment in List.Remove about initialization of l - return l.insertValue(v, mark.prev) -} - -// InsertAfter inserts a new element e with value v immediately after mark and returns e. -// If mark is not an element of l, the list is not modified. -// The mark must not be nil. -func (l *PacketList) InsertAfter(v Packet, mark *PacketElement) *PacketElement { - if mark.list != l { - return nil - } - // see comment in List.Remove about initialization of l - return l.insertValue(v, mark) -} - -// MoveToFront moves element e to the front of list l. -// If e is not an element of l, the list is not modified. -// The element must not be nil. -func (l *PacketList) MoveToFront(e *PacketElement) { - if e.list != l || l.root.next == e { - return - } - // see comment in List.Remove about initialization of l - l.insert(l.remove(e), &l.root) -} - -// MoveToBack moves element e to the back of list l. -// If e is not an element of l, the list is not modified. -// The element must not be nil. -func (l *PacketList) MoveToBack(e *PacketElement) { - if e.list != l || l.root.prev == e { - return - } - // see comment in List.Remove about initialization of l - l.insert(l.remove(e), l.root.prev) -} - -// MoveBefore moves element e to its new position before mark. -// If e or mark is not an element of l, or e == mark, the list is not modified. -// The element and mark must not be nil. -func (l *PacketList) MoveBefore(e, mark *PacketElement) { - if e.list != l || e == mark || mark.list != l { - return - } - l.insert(l.remove(e), mark.prev) -} - -// MoveAfter moves element e to its new position after mark. -// If e or mark is not an element of l, or e == mark, the list is not modified. -// The element and mark must not be nil. -func (l *PacketList) MoveAfter(e, mark *PacketElement) { - if e.list != l || e == mark || mark.list != l { - return - } - l.insert(l.remove(e), mark) -} - -// PushBackList inserts a copy of an other list at the back of list l. -// The lists l and other may be the same. They must not be nil. -func (l *PacketList) PushBackList(other *PacketList) { - l.lazyInit() - for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() { - l.insertValue(e.Value, l.root.prev) - } -} - -// PushFrontList inserts a copy of an other list at the front of list l. -// The lists l and other may be the same. They must not be nil. -func (l *PacketList) PushFrontList(other *PacketList) { - l.lazyInit() - for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() { - l.insertValue(e.Value, &l.root) - } -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/packet_number_generator.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/packet_number_generator.go deleted file mode 100644 index 56fbf3d803..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/packet_number_generator.go +++ /dev/null @@ -1,78 +0,0 @@ -package ackhandler - -import ( - "crypto/rand" - "math" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" -) - -// The packetNumberGenerator generates the packet number for the next packet -// it randomly skips a packet number every averagePeriod packets (on average) -// it is guarantued to never skip two consecutive packet numbers -type packetNumberGenerator struct { - averagePeriod protocol.PacketNumber - - next protocol.PacketNumber - nextToSkip protocol.PacketNumber - - history []protocol.PacketNumber -} - -func newPacketNumberGenerator(initial, averagePeriod protocol.PacketNumber) *packetNumberGenerator { - g := &packetNumberGenerator{ - next: initial, - averagePeriod: averagePeriod, - } - g.generateNewSkip() - return g -} - -func (p *packetNumberGenerator) Peek() protocol.PacketNumber { - return p.next -} - -func (p *packetNumberGenerator) Pop() protocol.PacketNumber { - next := p.next - - // generate a new packet number for the next packet - p.next++ - - if p.next == p.nextToSkip { - if len(p.history)+1 > protocol.MaxTrackedSkippedPackets { - p.history = p.history[1:] - } - p.history = append(p.history, p.next) - p.next++ - p.generateNewSkip() - } - - return next -} - -func (p *packetNumberGenerator) generateNewSkip() { - num := p.getRandomNumber() - skip := protocol.PacketNumber(num) * (p.averagePeriod - 1) / (math.MaxUint16 / 2) - // make sure that there are never two consecutive packet numbers that are skipped - p.nextToSkip = p.next + 2 + skip -} - -// getRandomNumber() generates a cryptographically secure random number between 0 and MaxUint16 (= 65535) -// The expectation value is 65535/2 -func (p *packetNumberGenerator) getRandomNumber() uint16 { - b := make([]byte, 2) - rand.Read(b) // ignore the error here - - num := uint16(b[0])<<8 + uint16(b[1]) - return num -} - -func (p *packetNumberGenerator) Validate(ack *wire.AckFrame) bool { - for _, pn := range p.history { - if ack.AcksPacket(pn) { - return false - } - } - return true -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/received_packet_handler.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/received_packet_handler.go deleted file mode 100644 index 1035bd12fb..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/received_packet_handler.go +++ /dev/null @@ -1,123 +0,0 @@ -package ackhandler - -import ( - "fmt" - "time" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" -) - -const ( - // initial maximum number of ack-eliciting packets received before sending an ack. - initialAckElicitingPacketsBeforeAck = 2 - // number of ack-eliciting that an ACK is sent for - ackElicitingPacketsBeforeAck = 10 - // 1/5 RTT delay when doing ack decimation - ackDecimationDelay = 1.0 / 4 - // 1/8 RTT delay when doing ack decimation - shortAckDecimationDelay = 1.0 / 8 - // Minimum number of packets received before ack decimation is enabled. - // This intends to avoid the beginning of slow start, when CWNDs may be - // rapidly increasing. - minReceivedBeforeAckDecimation = 100 - // Maximum number of packets to ack immediately after a missing packet for - // fast retransmission to kick in at the sender. This limit is created to - // reduce the number of acks sent that have no benefit for fast retransmission. - // Set to the number of nacks needed for fast retransmit plus one for protection - // against an ack loss - maxPacketsAfterNewMissing = 4 -) - -type receivedPacketHandler struct { - initialPackets *receivedPacketTracker - handshakePackets *receivedPacketTracker - oneRTTPackets *receivedPacketTracker -} - -var _ ReceivedPacketHandler = &receivedPacketHandler{} - -// NewReceivedPacketHandler creates a new receivedPacketHandler -func NewReceivedPacketHandler( - rttStats *congestion.RTTStats, - logger utils.Logger, - version protocol.VersionNumber, -) ReceivedPacketHandler { - return &receivedPacketHandler{ - initialPackets: newReceivedPacketTracker(rttStats, logger, version), - handshakePackets: newReceivedPacketTracker(rttStats, logger, version), - oneRTTPackets: newReceivedPacketTracker(rttStats, logger, version), - } -} - -func (h *receivedPacketHandler) ReceivedPacket( - pn protocol.PacketNumber, - encLevel protocol.EncryptionLevel, - rcvTime time.Time, - shouldInstigateAck bool, -) error { - switch encLevel { - case protocol.EncryptionInitial: - return h.initialPackets.ReceivedPacket(pn, rcvTime, shouldInstigateAck) - case protocol.EncryptionHandshake: - return h.handshakePackets.ReceivedPacket(pn, rcvTime, shouldInstigateAck) - case protocol.Encryption1RTT: - return h.oneRTTPackets.ReceivedPacket(pn, rcvTime, shouldInstigateAck) - default: - return fmt.Errorf("received packet with unknown encryption level: %s", encLevel) - } -} - -// only to be used with 1-RTT packets -func (h *receivedPacketHandler) IgnoreBelow(pn protocol.PacketNumber) { - h.oneRTTPackets.IgnoreBelow(pn) -} - -func (h *receivedPacketHandler) DropPackets(encLevel protocol.EncryptionLevel) { - switch encLevel { - case protocol.EncryptionInitial: - h.initialPackets = nil - case protocol.EncryptionHandshake: - h.handshakePackets = nil - default: - panic(fmt.Sprintf("Cannot drop keys for encryption level %s", encLevel)) - } -} - -func (h *receivedPacketHandler) GetAlarmTimeout() time.Time { - var initialAlarm, handshakeAlarm time.Time - if h.initialPackets != nil { - initialAlarm = h.initialPackets.GetAlarmTimeout() - } - if h.handshakePackets != nil { - handshakeAlarm = h.handshakePackets.GetAlarmTimeout() - } - oneRTTAlarm := h.oneRTTPackets.GetAlarmTimeout() - return utils.MinNonZeroTime(utils.MinNonZeroTime(initialAlarm, handshakeAlarm), oneRTTAlarm) -} - -func (h *receivedPacketHandler) GetAckFrame(encLevel protocol.EncryptionLevel) *wire.AckFrame { - var ack *wire.AckFrame - switch encLevel { - case protocol.EncryptionInitial: - if h.initialPackets != nil { - ack = h.initialPackets.GetAckFrame() - } - case protocol.EncryptionHandshake: - if h.handshakePackets != nil { - ack = h.handshakePackets.GetAckFrame() - } - case protocol.Encryption1RTT: - return h.oneRTTPackets.GetAckFrame() - default: - return nil - } - // For Initial and Handshake ACKs, the delay time is ignored by the receiver. - // Set it to 0 in order to save bytes. - if ack != nil { - ack.DelayTime = 0 - } - return ack -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/received_packet_history.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/received_packet_history.go deleted file mode 100644 index 0daba413df..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/received_packet_history.go +++ /dev/null @@ -1,122 +0,0 @@ -package ackhandler - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/qerr" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" -) - -// The receivedPacketHistory stores if a packet number has already been received. -// It generates ACK ranges which can be used to assemble an ACK frame. -// It does not store packet contents. -type receivedPacketHistory struct { - ranges *utils.PacketIntervalList - - lowestInReceivedPacketNumbers protocol.PacketNumber -} - -var errTooManyOutstandingReceivedAckRanges = qerr.Error(qerr.InternalError, "Too many outstanding received ACK ranges") - -// newReceivedPacketHistory creates a new received packet history -func newReceivedPacketHistory() *receivedPacketHistory { - return &receivedPacketHistory{ - ranges: utils.NewPacketIntervalList(), - } -} - -// ReceivedPacket registers a packet with PacketNumber p and updates the ranges -func (h *receivedPacketHistory) ReceivedPacket(p protocol.PacketNumber) error { - if h.ranges.Len() >= protocol.MaxTrackedReceivedAckRanges { - return errTooManyOutstandingReceivedAckRanges - } - - if h.ranges.Len() == 0 { - h.ranges.PushBack(utils.PacketInterval{Start: p, End: p}) - return nil - } - - for el := h.ranges.Back(); el != nil; el = el.Prev() { - // p already included in an existing range. Nothing to do here - if p >= el.Value.Start && p <= el.Value.End { - return nil - } - - var rangeExtended bool - if el.Value.End == p-1 { // extend a range at the end - rangeExtended = true - el.Value.End = p - } else if el.Value.Start == p+1 { // extend a range at the beginning - rangeExtended = true - el.Value.Start = p - } - - // if a range was extended (either at the beginning or at the end, maybe it is possible to merge two ranges into one) - if rangeExtended { - prev := el.Prev() - if prev != nil && prev.Value.End+1 == el.Value.Start { // merge two ranges - prev.Value.End = el.Value.End - h.ranges.Remove(el) - return nil - } - return nil // if the two ranges were not merge, we're done here - } - - // create a new range at the end - if p > el.Value.End { - h.ranges.InsertAfter(utils.PacketInterval{Start: p, End: p}, el) - return nil - } - } - - // create a new range at the beginning - h.ranges.InsertBefore(utils.PacketInterval{Start: p, End: p}, h.ranges.Front()) - - return nil -} - -// DeleteBelow deletes all entries below (but not including) p -func (h *receivedPacketHistory) DeleteBelow(p protocol.PacketNumber) { - if p <= h.lowestInReceivedPacketNumbers { - return - } - h.lowestInReceivedPacketNumbers = p - - nextEl := h.ranges.Front() - for el := h.ranges.Front(); nextEl != nil; el = nextEl { - nextEl = el.Next() - - if p > el.Value.Start && p <= el.Value.End { - el.Value.Start = p - } else if el.Value.End < p { // delete a whole range - h.ranges.Remove(el) - } else { // no ranges affected. Nothing to do - return - } - } -} - -// GetAckRanges gets a slice of all AckRanges that can be used in an AckFrame -func (h *receivedPacketHistory) GetAckRanges() []wire.AckRange { - if h.ranges.Len() == 0 { - return nil - } - - ackRanges := make([]wire.AckRange, h.ranges.Len()) - i := 0 - for el := h.ranges.Back(); el != nil; el = el.Prev() { - ackRanges[i] = wire.AckRange{Smallest: el.Value.Start, Largest: el.Value.End} - i++ - } - return ackRanges -} - -func (h *receivedPacketHistory) GetHighestAckRange() wire.AckRange { - ackRange := wire.AckRange{} - if h.ranges.Len() > 0 { - r := h.ranges.Back().Value - ackRange.Smallest = r.Start - ackRange.Largest = r.End - } - return ackRange -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/received_packet_tracker.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/received_packet_tracker.go deleted file mode 100644 index 42f7de5943..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/received_packet_tracker.go +++ /dev/null @@ -1,191 +0,0 @@ -package ackhandler - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" -) - -type receivedPacketTracker struct { - largestObserved protocol.PacketNumber - ignoreBelow protocol.PacketNumber - largestObservedReceivedTime time.Time - - packetHistory *receivedPacketHistory - - maxAckDelay time.Duration - rttStats *congestion.RTTStats - - packetsReceivedSinceLastAck int - ackElicitingPacketsReceivedSinceLastAck int - ackQueued bool - ackAlarm time.Time - lastAck *wire.AckFrame - - logger utils.Logger - - version protocol.VersionNumber -} - -func newReceivedPacketTracker( - rttStats *congestion.RTTStats, - logger utils.Logger, - version protocol.VersionNumber, -) *receivedPacketTracker { - return &receivedPacketTracker{ - packetHistory: newReceivedPacketHistory(), - maxAckDelay: protocol.MaxAckDelay, - rttStats: rttStats, - logger: logger, - version: version, - } -} - -func (h *receivedPacketTracker) ReceivedPacket(packetNumber protocol.PacketNumber, rcvTime time.Time, shouldInstigateAck bool) error { - if packetNumber < h.ignoreBelow { - return nil - } - - isMissing := h.isMissing(packetNumber) - if packetNumber >= h.largestObserved { - h.largestObserved = packetNumber - h.largestObservedReceivedTime = rcvTime - } - - if err := h.packetHistory.ReceivedPacket(packetNumber); err != nil { - return err - } - h.maybeQueueAck(packetNumber, rcvTime, shouldInstigateAck, isMissing) - return nil -} - -// IgnoreBelow sets a lower limit for acking packets. -// Packets with packet numbers smaller than p will not be acked. -func (h *receivedPacketTracker) IgnoreBelow(p protocol.PacketNumber) { - if p <= h.ignoreBelow { - return - } - h.ignoreBelow = p - h.packetHistory.DeleteBelow(p) - if h.logger.Debug() { - h.logger.Debugf("\tIgnoring all packets below %#x.", p) - } -} - -// isMissing says if a packet was reported missing in the last ACK. -func (h *receivedPacketTracker) isMissing(p protocol.PacketNumber) bool { - if h.lastAck == nil || p < h.ignoreBelow { - return false - } - return p < h.lastAck.LargestAcked() && !h.lastAck.AcksPacket(p) -} - -func (h *receivedPacketTracker) hasNewMissingPackets() bool { - if h.lastAck == nil { - return false - } - highestRange := h.packetHistory.GetHighestAckRange() - return highestRange.Smallest >= h.lastAck.LargestAcked() && highestRange.Len() <= maxPacketsAfterNewMissing -} - -// maybeQueueAck queues an ACK, if necessary. -// It is implemented analogously to Chrome's QuicConnection::MaybeQueueAck() -// in ACK_DECIMATION_WITH_REORDERING mode. -func (h *receivedPacketTracker) maybeQueueAck(packetNumber protocol.PacketNumber, rcvTime time.Time, shouldInstigateAck, wasMissing bool) { - h.packetsReceivedSinceLastAck++ - - // always ack the first packet - if h.lastAck == nil { - h.logger.Debugf("\tQueueing ACK because the first packet should be acknowledged.") - h.ackQueued = true - return - } - - // Send an ACK if this packet was reported missing in an ACK sent before. - // Ack decimation with reordering relies on the timer to send an ACK, but if - // missing packets we reported in the previous ack, send an ACK immediately. - if wasMissing { - if h.logger.Debug() { - h.logger.Debugf("\tQueueing ACK because packet %#x was missing before.", packetNumber) - } - h.ackQueued = true - } - - if !h.ackQueued && shouldInstigateAck { - h.ackElicitingPacketsReceivedSinceLastAck++ - - if packetNumber > minReceivedBeforeAckDecimation { - // ack up to 10 packets at once - if h.ackElicitingPacketsReceivedSinceLastAck >= ackElicitingPacketsBeforeAck { - h.ackQueued = true - if h.logger.Debug() { - h.logger.Debugf("\tQueueing ACK because packet %d packets were received after the last ACK (using threshold: %d).", h.ackElicitingPacketsReceivedSinceLastAck, ackElicitingPacketsBeforeAck) - } - } else if h.ackAlarm.IsZero() { - // wait for the minimum of the ack decimation delay or the delayed ack time before sending an ack - ackDelay := utils.MinDuration(h.maxAckDelay, time.Duration(float64(h.rttStats.MinRTT())*float64(ackDecimationDelay))) - h.ackAlarm = rcvTime.Add(ackDelay) - if h.logger.Debug() { - h.logger.Debugf("\tSetting ACK timer to min(1/4 min-RTT, max ack delay): %s (%s from now)", ackDelay, time.Until(h.ackAlarm)) - } - } - } else { - // send an ACK every 2 ack-eliciting packets - if h.ackElicitingPacketsReceivedSinceLastAck >= initialAckElicitingPacketsBeforeAck { - if h.logger.Debug() { - h.logger.Debugf("\tQueueing ACK because packet %d packets were received after the last ACK (using initial threshold: %d).", h.ackElicitingPacketsReceivedSinceLastAck, initialAckElicitingPacketsBeforeAck) - } - h.ackQueued = true - } else if h.ackAlarm.IsZero() { - if h.logger.Debug() { - h.logger.Debugf("\tSetting ACK timer to max ack delay: %s", h.maxAckDelay) - } - h.ackAlarm = rcvTime.Add(h.maxAckDelay) - } - } - // If there are new missing packets to report, set a short timer to send an ACK. - if h.hasNewMissingPackets() { - // wait the minimum of 1/8 min RTT and the existing ack time - ackDelay := time.Duration(float64(h.rttStats.MinRTT()) * float64(shortAckDecimationDelay)) - ackTime := rcvTime.Add(ackDelay) - if h.ackAlarm.IsZero() || h.ackAlarm.After(ackTime) { - h.ackAlarm = ackTime - if h.logger.Debug() { - h.logger.Debugf("\tSetting ACK timer to 1/8 min-RTT: %s (%s from now)", ackDelay, time.Until(h.ackAlarm)) - } - } - } - } - - if h.ackQueued { - // cancel the ack alarm - h.ackAlarm = time.Time{} - } -} - -func (h *receivedPacketTracker) GetAckFrame() *wire.AckFrame { - now := time.Now() - if !h.ackQueued && (h.ackAlarm.IsZero() || h.ackAlarm.After(now)) { - return nil - } - if h.logger.Debug() && !h.ackQueued && !h.ackAlarm.IsZero() { - h.logger.Debugf("Sending ACK because the ACK timer expired.") - } - - ack := &wire.AckFrame{ - AckRanges: h.packetHistory.GetAckRanges(), - DelayTime: now.Sub(h.largestObservedReceivedTime), - } - - h.lastAck = ack - h.ackAlarm = time.Time{} - h.ackQueued = false - h.packetsReceivedSinceLastAck = 0 - h.ackElicitingPacketsReceivedSinceLastAck = 0 - return ack -} - -func (h *receivedPacketTracker) GetAlarmTimeout() time.Time { return h.ackAlarm } diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/send_mode.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/send_mode.go deleted file mode 100644 index 8cdaa7e6bb..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/send_mode.go +++ /dev/null @@ -1,36 +0,0 @@ -package ackhandler - -import "fmt" - -// The SendMode says what kind of packets can be sent. -type SendMode uint8 - -const ( - // SendNone means that no packets should be sent - SendNone SendMode = iota - // SendAck means an ACK-only packet should be sent - SendAck - // SendRetransmission means that retransmissions should be sent - SendRetransmission - // SendPTO means that a probe packet should be sent - SendPTO - // SendAny means that any packet should be sent - SendAny -) - -func (s SendMode) String() string { - switch s { - case SendNone: - return "none" - case SendAck: - return "ack" - case SendRetransmission: - return "retransmission" - case SendPTO: - return "pto" - case SendAny: - return "any" - default: - return fmt.Sprintf("invalid send mode: %d", s) - } -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/sent_packet_handler.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/sent_packet_handler.go deleted file mode 100644 index 2ffa77a057..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/sent_packet_handler.go +++ /dev/null @@ -1,689 +0,0 @@ -package ackhandler - -import ( - "errors" - "fmt" - "math" - "time" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/qerr" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" - "github.com/lucas-clemente/quic-go/quictrace" -) - -const ( - // Maximum reordering in time space before time based loss detection considers a packet lost. - // Specified as an RTT multiplier. - timeThreshold = 9.0 / 8 -) - -type packetNumberSpace struct { - history *sentPacketHistory - pns *packetNumberGenerator - - largestAcked protocol.PacketNumber - largestSent protocol.PacketNumber -} - -func newPacketNumberSpace(initialPN protocol.PacketNumber) *packetNumberSpace { - return &packetNumberSpace{ - history: newSentPacketHistory(), - pns: newPacketNumberGenerator(initialPN, protocol.SkipPacketAveragePeriodLength), - largestSent: protocol.InvalidPacketNumber, - largestAcked: protocol.InvalidPacketNumber, - } -} - -type sentPacketHandler struct { - lastSentAckElicitingPacketTime time.Time // only applies to the application-data packet number space - lastSentCryptoPacketTime time.Time - - nextSendTime time.Time - - initialPackets *packetNumberSpace - handshakePackets *packetNumberSpace - oneRTTPackets *packetNumberSpace - - // lowestNotConfirmedAcked is the lowest packet number that we sent an ACK for, but haven't received confirmation, that this ACK actually arrived - // example: we send an ACK for packets 90-100 with packet number 20 - // once we receive an ACK from the peer for packet 20, the lowestNotConfirmedAcked is 101 - // Only applies to the application-data packet number space. - lowestNotConfirmedAcked protocol.PacketNumber - - retransmissionQueue []*Packet - - bytesInFlight protocol.ByteCount - - congestion congestion.SendAlgorithmWithDebugInfos - rttStats *congestion.RTTStats - - // The number of times the crypto packets have been retransmitted without receiving an ack. - cryptoCount uint32 - // The number of times a PTO has been sent without receiving an ack. - ptoCount uint32 - // The number of PTO probe packets that should be sent. - // Only applies to the application-data packet number space. - numProbesToSend int - - // The time at which the next packet will be considered lost based on early transmit or exceeding the reordering window in time. - lossTime time.Time - - // The alarm timeout - alarm time.Time - - traceCallback func(quictrace.Event) - - logger utils.Logger -} - -// NewSentPacketHandler creates a new sentPacketHandler -func NewSentPacketHandler( - initialPacketNumber protocol.PacketNumber, - rttStats *congestion.RTTStats, - traceCallback func(quictrace.Event), - logger utils.Logger, -) SentPacketHandler { - congestion := congestion.NewCubicSender( - congestion.DefaultClock{}, - rttStats, - true, // use Reno - protocol.InitialCongestionWindow, - protocol.DefaultMaxCongestionWindow, - ) - - return &sentPacketHandler{ - initialPackets: newPacketNumberSpace(initialPacketNumber), - handshakePackets: newPacketNumberSpace(0), - oneRTTPackets: newPacketNumberSpace(0), - rttStats: rttStats, - congestion: congestion, - traceCallback: traceCallback, - logger: logger, - } -} - -func (h *sentPacketHandler) DropPackets(encLevel protocol.EncryptionLevel) { - // remove outstanding packets from bytes_in_flight - pnSpace := h.getPacketNumberSpace(encLevel) - pnSpace.history.Iterate(func(p *Packet) (bool, error) { - if p.includedInBytesInFlight { - h.bytesInFlight -= p.Length - } - return true, nil - }) - // remove packets from the retransmission queue - var queue []*Packet - for _, packet := range h.retransmissionQueue { - if packet.EncryptionLevel != encLevel { - queue = append(queue, packet) - } - } - h.retransmissionQueue = queue - // drop the packet history - switch encLevel { - case protocol.EncryptionInitial: - h.initialPackets = nil - case protocol.EncryptionHandshake: - h.handshakePackets = nil - default: - panic(fmt.Sprintf("Cannot drop keys for encryption level %s", encLevel)) - } -} - -func (h *sentPacketHandler) SentPacket(packet *Packet) { - if isAckEliciting := h.sentPacketImpl(packet); isAckEliciting { - h.getPacketNumberSpace(packet.EncryptionLevel).history.SentPacket(packet) - h.updateLossDetectionAlarm() - } -} - -func (h *sentPacketHandler) SentPacketsAsRetransmission(packets []*Packet, retransmissionOf protocol.PacketNumber) { - var p []*Packet - for _, packet := range packets { - if isAckEliciting := h.sentPacketImpl(packet); isAckEliciting { - p = append(p, packet) - } - } - h.getPacketNumberSpace(p[0].EncryptionLevel).history.SentPacketsAsRetransmission(p, retransmissionOf) - h.updateLossDetectionAlarm() -} - -func (h *sentPacketHandler) getPacketNumberSpace(encLevel protocol.EncryptionLevel) *packetNumberSpace { - switch encLevel { - case protocol.EncryptionInitial: - return h.initialPackets - case protocol.EncryptionHandshake: - return h.handshakePackets - case protocol.Encryption1RTT: - return h.oneRTTPackets - default: - panic("invalid packet number space") - } -} - -func (h *sentPacketHandler) sentPacketImpl(packet *Packet) bool /* is ack-eliciting */ { - pnSpace := h.getPacketNumberSpace(packet.EncryptionLevel) - - if h.logger.Debug() { - for p := utils.MaxPacketNumber(0, pnSpace.largestSent+1); p < packet.PacketNumber; p++ { - h.logger.Debugf("Skipping packet number %#x", p) - } - } - - pnSpace.largestSent = packet.PacketNumber - - packet.largestAcked = protocol.InvalidPacketNumber - if packet.Ack != nil { - packet.largestAcked = packet.Ack.LargestAcked() - } - packet.Ack = nil // no need to save the ACK - - isAckEliciting := len(packet.Frames) > 0 - - if isAckEliciting { - if packet.EncryptionLevel != protocol.Encryption1RTT { - h.lastSentCryptoPacketTime = packet.SendTime - } - h.lastSentAckElicitingPacketTime = packet.SendTime - packet.includedInBytesInFlight = true - h.bytesInFlight += packet.Length - packet.canBeRetransmitted = true - if h.numProbesToSend > 0 { - h.numProbesToSend-- - } - } - h.congestion.OnPacketSent(packet.SendTime, h.bytesInFlight, packet.PacketNumber, packet.Length, isAckEliciting) - - h.nextSendTime = utils.MaxTime(h.nextSendTime, packet.SendTime).Add(h.congestion.TimeUntilSend(h.bytesInFlight)) - return isAckEliciting -} - -func (h *sentPacketHandler) ReceivedAck(ackFrame *wire.AckFrame, withPacketNumber protocol.PacketNumber, encLevel protocol.EncryptionLevel, rcvTime time.Time) error { - pnSpace := h.getPacketNumberSpace(encLevel) - - largestAcked := ackFrame.LargestAcked() - if largestAcked > pnSpace.largestSent { - return qerr.Error(qerr.ProtocolViolation, "Received ACK for an unsent packet") - } - - pnSpace.largestAcked = utils.MaxPacketNumber(pnSpace.largestAcked, largestAcked) - - if !pnSpace.pns.Validate(ackFrame) { - return qerr.Error(qerr.ProtocolViolation, "Received an ACK for a skipped packet number") - } - - // maybe update the RTT - if p := pnSpace.history.GetPacket(ackFrame.LargestAcked()); p != nil { - // don't use the ack delay for Initial and Handshake packets - var ackDelay time.Duration - if encLevel == protocol.Encryption1RTT { - ackDelay = utils.MinDuration(ackFrame.DelayTime, h.rttStats.MaxAckDelay()) - } - h.rttStats.UpdateRTT(rcvTime.Sub(p.SendTime), ackDelay, rcvTime) - if h.logger.Debug() { - h.logger.Debugf("\tupdated RTT: %s (σ: %s)", h.rttStats.SmoothedRTT(), h.rttStats.MeanDeviation()) - } - h.congestion.MaybeExitSlowStart() - } - - ackedPackets, err := h.determineNewlyAckedPackets(ackFrame, encLevel) - if err != nil { - return err - } - if len(ackedPackets) == 0 { - return nil - } - - priorInFlight := h.bytesInFlight - for _, p := range ackedPackets { - if p.largestAcked != protocol.InvalidPacketNumber && encLevel == protocol.Encryption1RTT { - h.lowestNotConfirmedAcked = utils.MaxPacketNumber(h.lowestNotConfirmedAcked, p.largestAcked+1) - } - if err := h.onPacketAcked(p, rcvTime); err != nil { - return err - } - if p.includedInBytesInFlight { - h.congestion.OnPacketAcked(p.PacketNumber, p.Length, priorInFlight, rcvTime) - } - } - - if err := h.detectLostPackets(rcvTime, encLevel, priorInFlight); err != nil { - return err - } - - h.ptoCount = 0 - h.cryptoCount = 0 - h.numProbesToSend = 0 - - h.updateLossDetectionAlarm() - return nil -} - -func (h *sentPacketHandler) GetLowestPacketNotConfirmedAcked() protocol.PacketNumber { - return h.lowestNotConfirmedAcked -} - -func (h *sentPacketHandler) determineNewlyAckedPackets( - ackFrame *wire.AckFrame, - encLevel protocol.EncryptionLevel, -) ([]*Packet, error) { - pnSpace := h.getPacketNumberSpace(encLevel) - var ackedPackets []*Packet - ackRangeIndex := 0 - lowestAcked := ackFrame.LowestAcked() - largestAcked := ackFrame.LargestAcked() - err := pnSpace.history.Iterate(func(p *Packet) (bool, error) { - // Ignore packets below the lowest acked - if p.PacketNumber < lowestAcked { - return true, nil - } - // Break after largest acked is reached - if p.PacketNumber > largestAcked { - return false, nil - } - - if ackFrame.HasMissingRanges() { - ackRange := ackFrame.AckRanges[len(ackFrame.AckRanges)-1-ackRangeIndex] - - for p.PacketNumber > ackRange.Largest && ackRangeIndex < len(ackFrame.AckRanges)-1 { - ackRangeIndex++ - ackRange = ackFrame.AckRanges[len(ackFrame.AckRanges)-1-ackRangeIndex] - } - - if p.PacketNumber >= ackRange.Smallest { // packet i contained in ACK range - if p.PacketNumber > ackRange.Largest { - return false, fmt.Errorf("BUG: ackhandler would have acked wrong packet 0x%x, while evaluating range 0x%x -> 0x%x", p.PacketNumber, ackRange.Smallest, ackRange.Largest) - } - ackedPackets = append(ackedPackets, p) - } - } else { - ackedPackets = append(ackedPackets, p) - } - return true, nil - }) - if h.logger.Debug() && len(ackedPackets) > 0 { - pns := make([]protocol.PacketNumber, len(ackedPackets)) - for i, p := range ackedPackets { - pns[i] = p.PacketNumber - } - h.logger.Debugf("\tnewly acked packets (%d): %#x", len(pns), pns) - } - return ackedPackets, err -} - -func (h *sentPacketHandler) hasOutstandingCryptoPackets() bool { - var hasInitial, hasHandshake bool - if h.initialPackets != nil { - hasInitial = h.initialPackets.history.HasOutstandingPackets() - } - if h.handshakePackets != nil { - hasHandshake = h.handshakePackets.history.HasOutstandingPackets() - } - return hasInitial || hasHandshake -} - -func (h *sentPacketHandler) hasOutstandingPackets() bool { - return h.oneRTTPackets.history.HasOutstandingPackets() || h.hasOutstandingCryptoPackets() -} - -func (h *sentPacketHandler) updateLossDetectionAlarm() { - // Cancel the alarm if no packets are outstanding - if !h.hasOutstandingPackets() { - h.alarm = time.Time{} - return - } - - if h.hasOutstandingCryptoPackets() { - h.alarm = h.lastSentCryptoPacketTime.Add(h.computeCryptoTimeout()) - } else if !h.lossTime.IsZero() { - // Early retransmit timer or time loss detection. - h.alarm = h.lossTime - } else { // PTO alarm - h.alarm = h.lastSentAckElicitingPacketTime.Add(h.rttStats.PTO() << h.ptoCount) - } -} - -func (h *sentPacketHandler) detectLostPackets( - now time.Time, - encLevel protocol.EncryptionLevel, - priorInFlight protocol.ByteCount, -) error { - if encLevel == protocol.Encryption1RTT { - h.lossTime = time.Time{} - } - pnSpace := h.getPacketNumberSpace(encLevel) - - maxRTT := float64(utils.MaxDuration(h.rttStats.LatestRTT(), h.rttStats.SmoothedRTT())) - lossDelay := time.Duration(timeThreshold * maxRTT) - - // Minimum time of granularity before packets are deemed lost. - lossDelay = utils.MaxDuration(lossDelay, protocol.TimerGranularity) - - var lostPackets []*Packet - pnSpace.history.Iterate(func(packet *Packet) (bool, error) { - if packet.PacketNumber > pnSpace.largestAcked { - return false, nil - } - - timeSinceSent := now.Sub(packet.SendTime) - if timeSinceSent > lossDelay { - lostPackets = append(lostPackets, packet) - } else if h.lossTime.IsZero() && encLevel == protocol.Encryption1RTT { - if h.logger.Debug() { - h.logger.Debugf("\tsetting loss timer for packet %#x to %s (in %s)", packet.PacketNumber, lossDelay, lossDelay-timeSinceSent) - } - // Note: This conditional is only entered once per call - h.lossTime = now.Add(lossDelay - timeSinceSent) - } - return true, nil - }) - - if h.logger.Debug() && len(lostPackets) > 0 { - pns := make([]protocol.PacketNumber, len(lostPackets)) - for i, p := range lostPackets { - pns[i] = p.PacketNumber - } - h.logger.Debugf("\tlost packets (%d): %#x", len(pns), pns) - } - - for _, p := range lostPackets { - // the bytes in flight need to be reduced no matter if this packet will be retransmitted - if p.includedInBytesInFlight { - h.bytesInFlight -= p.Length - h.congestion.OnPacketLost(p.PacketNumber, p.Length, priorInFlight) - } - if p.canBeRetransmitted { - // queue the packet for retransmission, and report the loss to the congestion controller - if err := h.queuePacketForRetransmission(p, pnSpace); err != nil { - return err - } - } - pnSpace.history.Remove(p.PacketNumber) - if h.traceCallback != nil { - h.traceCallback(quictrace.Event{ - Time: now, - EventType: quictrace.PacketLost, - EncryptionLevel: p.EncryptionLevel, - PacketNumber: p.PacketNumber, - PacketSize: p.Length, - Frames: p.Frames, - TransportState: h.GetStats(), - }) - } - } - return nil -} - -func (h *sentPacketHandler) OnAlarm() error { - // When all outstanding are acknowledged, the alarm is canceled in - // updateLossDetectionAlarm. This doesn't reset the timer in the session though. - // When OnAlarm is called, we therefore need to make sure that there are - // actually packets outstanding. - if h.hasOutstandingPackets() { - if err := h.onVerifiedAlarm(); err != nil { - return err - } - } - h.updateLossDetectionAlarm() - return nil -} - -func (h *sentPacketHandler) onVerifiedAlarm() error { - var err error - if h.hasOutstandingCryptoPackets() { - if h.logger.Debug() { - h.logger.Debugf("Loss detection alarm fired in crypto mode. Crypto count: %d", h.cryptoCount) - } - h.cryptoCount++ - err = h.queueCryptoPacketsForRetransmission() - } else if !h.lossTime.IsZero() { - if h.logger.Debug() { - h.logger.Debugf("Loss detection alarm fired in loss timer mode. Loss time: %s", h.lossTime) - } - // Early retransmit or time loss detection - err = h.detectLostPackets(time.Now(), protocol.Encryption1RTT, h.bytesInFlight) - } else { // PTO - if h.logger.Debug() { - h.logger.Debugf("Loss detection alarm fired in PTO mode. PTO count: %d", h.ptoCount) - } - h.ptoCount++ - h.numProbesToSend += 2 - } - return err -} - -func (h *sentPacketHandler) GetAlarmTimeout() time.Time { - return h.alarm -} - -func (h *sentPacketHandler) onPacketAcked(p *Packet, rcvTime time.Time) error { - pnSpace := h.getPacketNumberSpace(p.EncryptionLevel) - // This happens if a packet and its retransmissions is acked in the same ACK. - // As soon as we process the first one, this will remove all the retransmissions, - // so we won't find the retransmitted packet number later. - if packet := pnSpace.history.GetPacket(p.PacketNumber); packet == nil { - return nil - } - - // only report the acking of this packet to the congestion controller if: - // * it is an ack-eliciting packet - // * this packet wasn't retransmitted yet - if p.isRetransmission { - // that the parent doesn't exist is expected to happen every time the original packet was already acked - if parent := pnSpace.history.GetPacket(p.retransmissionOf); parent != nil { - if len(parent.retransmittedAs) == 1 { - parent.retransmittedAs = nil - } else { - // remove this packet from the slice of retransmission - retransmittedAs := make([]protocol.PacketNumber, 0, len(parent.retransmittedAs)-1) - for _, pn := range parent.retransmittedAs { - if pn != p.PacketNumber { - retransmittedAs = append(retransmittedAs, pn) - } - } - parent.retransmittedAs = retransmittedAs - } - } - } - // this also applies to packets that have been retransmitted as probe packets - if p.includedInBytesInFlight { - h.bytesInFlight -= p.Length - } - if err := h.stopRetransmissionsFor(p, pnSpace); err != nil { - return err - } - return pnSpace.history.Remove(p.PacketNumber) -} - -func (h *sentPacketHandler) stopRetransmissionsFor(p *Packet, pnSpace *packetNumberSpace) error { - if err := pnSpace.history.MarkCannotBeRetransmitted(p.PacketNumber); err != nil { - return err - } - for _, r := range p.retransmittedAs { - packet := pnSpace.history.GetPacket(r) - if packet == nil { - return fmt.Errorf("sent packet handler BUG: marking packet as not retransmittable %d (retransmission of %d) not found in history", r, p.PacketNumber) - } - h.stopRetransmissionsFor(packet, pnSpace) - } - return nil -} - -func (h *sentPacketHandler) DequeuePacketForRetransmission() *Packet { - if len(h.retransmissionQueue) == 0 { - return nil - } - packet := h.retransmissionQueue[0] - // Shift the slice and don't retain anything that isn't needed. - copy(h.retransmissionQueue, h.retransmissionQueue[1:]) - h.retransmissionQueue[len(h.retransmissionQueue)-1] = nil - h.retransmissionQueue = h.retransmissionQueue[:len(h.retransmissionQueue)-1] - return packet -} - -func (h *sentPacketHandler) DequeueProbePacket() (*Packet, error) { - pnSpace := h.getPacketNumberSpace(protocol.Encryption1RTT) - if len(h.retransmissionQueue) == 0 { - p := pnSpace.history.FirstOutstanding() - if p == nil { - return nil, errors.New("cannot dequeue a probe packet. No outstanding packets") - } - if err := h.queuePacketForRetransmission(p, pnSpace); err != nil { - return nil, err - } - } - return h.DequeuePacketForRetransmission(), nil -} - -func (h *sentPacketHandler) PeekPacketNumber(encLevel protocol.EncryptionLevel) (protocol.PacketNumber, protocol.PacketNumberLen) { - pnSpace := h.getPacketNumberSpace(encLevel) - - var lowestUnacked protocol.PacketNumber - if p := pnSpace.history.FirstOutstanding(); p != nil { - lowestUnacked = p.PacketNumber - } else { - lowestUnacked = pnSpace.largestAcked + 1 - } - - pn := pnSpace.pns.Peek() - return pn, protocol.GetPacketNumberLengthForHeader(pn, lowestUnacked) -} - -func (h *sentPacketHandler) PopPacketNumber(encLevel protocol.EncryptionLevel) protocol.PacketNumber { - return h.getPacketNumberSpace(encLevel).pns.Pop() -} - -func (h *sentPacketHandler) SendMode() SendMode { - numTrackedPackets := len(h.retransmissionQueue) + h.oneRTTPackets.history.Len() - if h.initialPackets != nil { - numTrackedPackets += h.initialPackets.history.Len() - } - if h.handshakePackets != nil { - numTrackedPackets += h.handshakePackets.history.Len() - } - - // Don't send any packets if we're keeping track of the maximum number of packets. - // Note that since MaxOutstandingSentPackets is smaller than MaxTrackedSentPackets, - // we will stop sending out new data when reaching MaxOutstandingSentPackets, - // but still allow sending of retransmissions and ACKs. - if numTrackedPackets >= protocol.MaxTrackedSentPackets { - if h.logger.Debug() { - h.logger.Debugf("Limited by the number of tracked packets: tracking %d packets, maximum %d", numTrackedPackets, protocol.MaxTrackedSentPackets) - } - return SendNone - } - if h.numProbesToSend > 0 { - return SendPTO - } - // Only send ACKs if we're congestion limited. - if !h.congestion.CanSend(h.bytesInFlight) { - if h.logger.Debug() { - h.logger.Debugf("Congestion limited: bytes in flight %d, window %d", h.bytesInFlight, h.congestion.GetCongestionWindow()) - } - return SendAck - } - // Send retransmissions first, if there are any. - if len(h.retransmissionQueue) > 0 { - return SendRetransmission - } - if numTrackedPackets >= protocol.MaxOutstandingSentPackets { - if h.logger.Debug() { - h.logger.Debugf("Max outstanding limited: tracking %d packets, maximum: %d", numTrackedPackets, protocol.MaxOutstandingSentPackets) - } - return SendAck - } - return SendAny -} - -func (h *sentPacketHandler) TimeUntilSend() time.Time { - return h.nextSendTime -} - -func (h *sentPacketHandler) ShouldSendNumPackets() int { - if h.numProbesToSend > 0 { - // RTO probes should not be paced, but must be sent immediately. - return h.numProbesToSend - } - delay := h.congestion.TimeUntilSend(h.bytesInFlight) - if delay == 0 || delay > protocol.MinPacingDelay { - return 1 - } - return int(math.Ceil(float64(protocol.MinPacingDelay) / float64(delay))) -} - -func (h *sentPacketHandler) queueCryptoPacketsForRetransmission() error { - if err := h.queueAllPacketsForRetransmission(protocol.EncryptionInitial); err != nil { - return err - } - return h.queueAllPacketsForRetransmission(protocol.EncryptionHandshake) -} - -func (h *sentPacketHandler) queueAllPacketsForRetransmission(encLevel protocol.EncryptionLevel) error { - var packets []*Packet - pnSpace := h.getPacketNumberSpace(encLevel) - pnSpace.history.Iterate(func(p *Packet) (bool, error) { - if p.canBeRetransmitted { - packets = append(packets, p) - } - return true, nil - }) - for _, p := range packets { - h.logger.Debugf("Queueing packet %#x (%s) as a crypto retransmission", p.PacketNumber, encLevel) - if err := h.queuePacketForRetransmission(p, pnSpace); err != nil { - return err - } - } - return nil -} - -func (h *sentPacketHandler) queuePacketForRetransmission(p *Packet, pnSpace *packetNumberSpace) error { - if !p.canBeRetransmitted { - return fmt.Errorf("sent packet handler BUG: packet %d already queued for retransmission", p.PacketNumber) - } - if err := pnSpace.history.MarkCannotBeRetransmitted(p.PacketNumber); err != nil { - return err - } - h.retransmissionQueue = append(h.retransmissionQueue, p) - return nil -} - -func (h *sentPacketHandler) computeCryptoTimeout() time.Duration { - duration := utils.MaxDuration(2*h.rttStats.SmoothedOrInitialRTT(), protocol.TimerGranularity) - // exponential backoff - // There's an implicit limit to this set by the crypto timeout. - return duration << h.cryptoCount -} - -func (h *sentPacketHandler) ResetForRetry() error { - h.cryptoCount = 0 - h.bytesInFlight = 0 - var packets []*Packet - h.initialPackets.history.Iterate(func(p *Packet) (bool, error) { - if p.canBeRetransmitted { - packets = append(packets, p) - } - return true, nil - }) - for _, p := range packets { - h.logger.Debugf("Queueing packet %#x for retransmission.", p.PacketNumber) - h.retransmissionQueue = append(h.retransmissionQueue, p) - } - h.initialPackets = newPacketNumberSpace(h.initialPackets.pns.Pop()) - h.updateLossDetectionAlarm() - return nil -} - -func (h *sentPacketHandler) GetStats() *quictrace.TransportState { - return &quictrace.TransportState{ - MinRTT: h.rttStats.MinRTT(), - SmoothedRTT: h.rttStats.SmoothedOrInitialRTT(), - LatestRTT: h.rttStats.LatestRTT(), - BytesInFlight: h.bytesInFlight, - CongestionWindow: h.congestion.GetCongestionWindow(), - InSlowStart: h.congestion.InSlowStart(), - InRecovery: h.congestion.InRecovery(), - } -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/sent_packet_history.go b/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/sent_packet_history.go deleted file mode 100644 index 393ebba61f..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/ackhandler/sent_packet_history.go +++ /dev/null @@ -1,148 +0,0 @@ -package ackhandler - -import ( - "fmt" - - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -type sentPacketHistory struct { - packetList *PacketList - packetMap map[protocol.PacketNumber]*PacketElement - - numOutstandingPackets int - - firstOutstanding *PacketElement -} - -func newSentPacketHistory() *sentPacketHistory { - return &sentPacketHistory{ - packetList: NewPacketList(), - packetMap: make(map[protocol.PacketNumber]*PacketElement), - } -} - -func (h *sentPacketHistory) SentPacket(p *Packet) { - h.sentPacketImpl(p) -} - -func (h *sentPacketHistory) sentPacketImpl(p *Packet) *PacketElement { - el := h.packetList.PushBack(*p) - h.packetMap[p.PacketNumber] = el - if h.firstOutstanding == nil { - h.firstOutstanding = el - } - if p.canBeRetransmitted { - h.numOutstandingPackets++ - } - return el -} - -func (h *sentPacketHistory) SentPacketsAsRetransmission(packets []*Packet, retransmissionOf protocol.PacketNumber) { - retransmission, ok := h.packetMap[retransmissionOf] - // The retransmitted packet is not present anymore. - // This can happen if it was acked in between dequeueing of the retransmission and sending. - // Just treat the retransmissions as normal packets. - // TODO: This won't happen if we clear packets queued for retransmission on new ACKs. - if !ok { - for _, packet := range packets { - h.sentPacketImpl(packet) - } - return - } - retransmission.Value.retransmittedAs = make([]protocol.PacketNumber, len(packets)) - for i, packet := range packets { - retransmission.Value.retransmittedAs[i] = packet.PacketNumber - el := h.sentPacketImpl(packet) - el.Value.isRetransmission = true - el.Value.retransmissionOf = retransmissionOf - } -} - -func (h *sentPacketHistory) GetPacket(p protocol.PacketNumber) *Packet { - if el, ok := h.packetMap[p]; ok { - return &el.Value - } - return nil -} - -// Iterate iterates through all packets. -// The callback must not modify the history. -func (h *sentPacketHistory) Iterate(cb func(*Packet) (cont bool, err error)) error { - cont := true - for el := h.packetList.Front(); cont && el != nil; el = el.Next() { - var err error - cont, err = cb(&el.Value) - if err != nil { - return err - } - } - return nil -} - -// FirstOutStanding returns the first outstanding packet. -// It must not be modified (e.g. retransmitted). -// Use DequeueFirstPacketForRetransmission() to retransmit it. -func (h *sentPacketHistory) FirstOutstanding() *Packet { - if h.firstOutstanding == nil { - return nil - } - return &h.firstOutstanding.Value -} - -// QueuePacketForRetransmission marks a packet for retransmission. -// A packet can only be queued once. -func (h *sentPacketHistory) MarkCannotBeRetransmitted(pn protocol.PacketNumber) error { - el, ok := h.packetMap[pn] - if !ok { - return fmt.Errorf("sent packet history: packet %d not found", pn) - } - if el.Value.canBeRetransmitted { - h.numOutstandingPackets-- - if h.numOutstandingPackets < 0 { - panic("numOutstandingHandshakePackets negative") - } - } - el.Value.canBeRetransmitted = false - if el == h.firstOutstanding { - h.readjustFirstOutstanding() - } - return nil -} - -// readjustFirstOutstanding readjusts the pointer to the first outstanding packet. -// This is necessary every time the first outstanding packet is deleted or retransmitted. -func (h *sentPacketHistory) readjustFirstOutstanding() { - el := h.firstOutstanding.Next() - for el != nil && !el.Value.canBeRetransmitted { - el = el.Next() - } - h.firstOutstanding = el -} - -func (h *sentPacketHistory) Len() int { - return len(h.packetMap) -} - -func (h *sentPacketHistory) Remove(p protocol.PacketNumber) error { - el, ok := h.packetMap[p] - if !ok { - return fmt.Errorf("packet %d not found in sent packet history", p) - } - if el == h.firstOutstanding { - h.readjustFirstOutstanding() - } - if el.Value.canBeRetransmitted { - h.numOutstandingPackets-- - if h.numOutstandingPackets < 0 { - panic("numOutstandingHandshakePackets negative") - } - } - h.packetList.Remove(el) - delete(h.packetMap, p) - return nil -} - -func (h *sentPacketHistory) HasOutstandingPackets() bool { - return h.numOutstandingPackets > 0 -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/bandwidth.go b/vendor/github.com/lucas-clemente/quic-go/internal/congestion/bandwidth.go deleted file mode 100644 index 54269c5679..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/bandwidth.go +++ /dev/null @@ -1,22 +0,0 @@ -package congestion - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// Bandwidth of a connection -type Bandwidth uint64 - -const ( - // BitsPerSecond is 1 bit per second - BitsPerSecond Bandwidth = 1 - // BytesPerSecond is 1 byte per second - BytesPerSecond = 8 * BitsPerSecond -) - -// BandwidthFromDelta calculates the bandwidth from a number of bytes and a time delta -func BandwidthFromDelta(bytes protocol.ByteCount, delta time.Duration) Bandwidth { - return Bandwidth(bytes) * Bandwidth(time.Second) / Bandwidth(delta) * BytesPerSecond -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/clock.go b/vendor/github.com/lucas-clemente/quic-go/internal/congestion/clock.go deleted file mode 100644 index 405fae70f9..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/clock.go +++ /dev/null @@ -1,18 +0,0 @@ -package congestion - -import "time" - -// A Clock returns the current time -type Clock interface { - Now() time.Time -} - -// DefaultClock implements the Clock interface using the Go stdlib clock. -type DefaultClock struct{} - -var _ Clock = DefaultClock{} - -// Now gets the current time -func (DefaultClock) Now() time.Time { - return time.Now() -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/cubic.go b/vendor/github.com/lucas-clemente/quic-go/internal/congestion/cubic.go deleted file mode 100644 index dcf91fc6d5..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/cubic.go +++ /dev/null @@ -1,210 +0,0 @@ -package congestion - -import ( - "math" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// This cubic implementation is based on the one found in Chromiums's QUIC -// implementation, in the files net/quic/congestion_control/cubic.{hh,cc}. - -// Constants based on TCP defaults. -// The following constants are in 2^10 fractions of a second instead of ms to -// allow a 10 shift right to divide. - -// 1024*1024^3 (first 1024 is from 0.100^3) -// where 0.100 is 100 ms which is the scaling round trip time. -const cubeScale = 40 -const cubeCongestionWindowScale = 410 -const cubeFactor protocol.ByteCount = 1 << cubeScale / cubeCongestionWindowScale / protocol.DefaultTCPMSS - -const defaultNumConnections = 2 - -// Default Cubic backoff factor -const beta float32 = 0.7 - -// Additional backoff factor when loss occurs in the concave part of the Cubic -// curve. This additional backoff factor is expected to give up bandwidth to -// new concurrent flows and speed up convergence. -const betaLastMax float32 = 0.85 - -// Cubic implements the cubic algorithm from TCP -type Cubic struct { - clock Clock - - // Number of connections to simulate. - numConnections int - - // Time when this cycle started, after last loss event. - epoch time.Time - - // Max congestion window used just before last loss event. - // Note: to improve fairness to other streams an additional back off is - // applied to this value if the new value is below our latest value. - lastMaxCongestionWindow protocol.ByteCount - - // Number of acked bytes since the cycle started (epoch). - ackedBytesCount protocol.ByteCount - - // TCP Reno equivalent congestion window in packets. - estimatedTCPcongestionWindow protocol.ByteCount - - // Origin point of cubic function. - originPointCongestionWindow protocol.ByteCount - - // Time to origin point of cubic function in 2^10 fractions of a second. - timeToOriginPoint uint32 - - // Last congestion window in packets computed by cubic function. - lastTargetCongestionWindow protocol.ByteCount -} - -// NewCubic returns a new Cubic instance -func NewCubic(clock Clock) *Cubic { - c := &Cubic{ - clock: clock, - numConnections: defaultNumConnections, - } - c.Reset() - return c -} - -// Reset is called after a timeout to reset the cubic state -func (c *Cubic) Reset() { - c.epoch = time.Time{} - c.lastMaxCongestionWindow = 0 - c.ackedBytesCount = 0 - c.estimatedTCPcongestionWindow = 0 - c.originPointCongestionWindow = 0 - c.timeToOriginPoint = 0 - c.lastTargetCongestionWindow = 0 -} - -func (c *Cubic) alpha() float32 { - // TCPFriendly alpha is described in Section 3.3 of the CUBIC paper. Note that - // beta here is a cwnd multiplier, and is equal to 1-beta from the paper. - // We derive the equivalent alpha for an N-connection emulation as: - b := c.beta() - return 3 * float32(c.numConnections) * float32(c.numConnections) * (1 - b) / (1 + b) -} - -func (c *Cubic) beta() float32 { - // kNConnectionBeta is the backoff factor after loss for our N-connection - // emulation, which emulates the effective backoff of an ensemble of N - // TCP-Reno connections on a single loss event. The effective multiplier is - // computed as: - return (float32(c.numConnections) - 1 + beta) / float32(c.numConnections) -} - -func (c *Cubic) betaLastMax() float32 { - // betaLastMax is the additional backoff factor after loss for our - // N-connection emulation, which emulates the additional backoff of - // an ensemble of N TCP-Reno connections on a single loss event. The - // effective multiplier is computed as: - return (float32(c.numConnections) - 1 + betaLastMax) / float32(c.numConnections) -} - -// OnApplicationLimited is called on ack arrival when sender is unable to use -// the available congestion window. Resets Cubic state during quiescence. -func (c *Cubic) OnApplicationLimited() { - // When sender is not using the available congestion window, the window does - // not grow. But to be RTT-independent, Cubic assumes that the sender has been - // using the entire window during the time since the beginning of the current - // "epoch" (the end of the last loss recovery period). Since - // application-limited periods break this assumption, we reset the epoch when - // in such a period. This reset effectively freezes congestion window growth - // through application-limited periods and allows Cubic growth to continue - // when the entire window is being used. - c.epoch = time.Time{} -} - -// CongestionWindowAfterPacketLoss computes a new congestion window to use after -// a loss event. Returns the new congestion window in packets. The new -// congestion window is a multiplicative decrease of our current window. -func (c *Cubic) CongestionWindowAfterPacketLoss(currentCongestionWindow protocol.ByteCount) protocol.ByteCount { - if currentCongestionWindow+protocol.DefaultTCPMSS < c.lastMaxCongestionWindow { - // We never reached the old max, so assume we are competing with another - // flow. Use our extra back off factor to allow the other flow to go up. - c.lastMaxCongestionWindow = protocol.ByteCount(c.betaLastMax() * float32(currentCongestionWindow)) - } else { - c.lastMaxCongestionWindow = currentCongestionWindow - } - c.epoch = time.Time{} // Reset time. - return protocol.ByteCount(float32(currentCongestionWindow) * c.beta()) -} - -// CongestionWindowAfterAck computes a new congestion window to use after a received ACK. -// Returns the new congestion window in packets. The new congestion window -// follows a cubic function that depends on the time passed since last -// packet loss. -func (c *Cubic) CongestionWindowAfterAck( - ackedBytes protocol.ByteCount, - currentCongestionWindow protocol.ByteCount, - delayMin time.Duration, - eventTime time.Time, -) protocol.ByteCount { - c.ackedBytesCount += ackedBytes - - if c.epoch.IsZero() { - // First ACK after a loss event. - c.epoch = eventTime // Start of epoch. - c.ackedBytesCount = ackedBytes // Reset count. - // Reset estimated_tcp_congestion_window_ to be in sync with cubic. - c.estimatedTCPcongestionWindow = currentCongestionWindow - if c.lastMaxCongestionWindow <= currentCongestionWindow { - c.timeToOriginPoint = 0 - c.originPointCongestionWindow = currentCongestionWindow - } else { - c.timeToOriginPoint = uint32(math.Cbrt(float64(cubeFactor * (c.lastMaxCongestionWindow - currentCongestionWindow)))) - c.originPointCongestionWindow = c.lastMaxCongestionWindow - } - } - - // Change the time unit from microseconds to 2^10 fractions per second. Take - // the round trip time in account. This is done to allow us to use shift as a - // divide operator. - elapsedTime := int64(eventTime.Add(delayMin).Sub(c.epoch)/time.Microsecond) << 10 / (1000 * 1000) - - // Right-shifts of negative, signed numbers have implementation-dependent - // behavior, so force the offset to be positive, as is done in the kernel. - offset := int64(c.timeToOriginPoint) - elapsedTime - if offset < 0 { - offset = -offset - } - - deltaCongestionWindow := protocol.ByteCount(cubeCongestionWindowScale*offset*offset*offset) * protocol.DefaultTCPMSS >> cubeScale - var targetCongestionWindow protocol.ByteCount - if elapsedTime > int64(c.timeToOriginPoint) { - targetCongestionWindow = c.originPointCongestionWindow + deltaCongestionWindow - } else { - targetCongestionWindow = c.originPointCongestionWindow - deltaCongestionWindow - } - // Limit the CWND increase to half the acked bytes. - targetCongestionWindow = utils.MinByteCount(targetCongestionWindow, currentCongestionWindow+c.ackedBytesCount/2) - - // Increase the window by approximately Alpha * 1 MSS of bytes every - // time we ack an estimated tcp window of bytes. For small - // congestion windows (less than 25), the formula below will - // increase slightly slower than linearly per estimated tcp window - // of bytes. - c.estimatedTCPcongestionWindow += protocol.ByteCount(float32(c.ackedBytesCount) * c.alpha() * float32(protocol.DefaultTCPMSS) / float32(c.estimatedTCPcongestionWindow)) - c.ackedBytesCount = 0 - - // We have a new cubic congestion window. - c.lastTargetCongestionWindow = targetCongestionWindow - - // Compute target congestion_window based on cubic target and estimated TCP - // congestion_window, use highest (fastest). - if targetCongestionWindow < c.estimatedTCPcongestionWindow { - targetCongestionWindow = c.estimatedTCPcongestionWindow - } - return targetCongestionWindow -} - -// SetNumConnections sets the number of emulated connections -func (c *Cubic) SetNumConnections(n int) { - c.numConnections = n -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/cubic_sender.go b/vendor/github.com/lucas-clemente/quic-go/internal/congestion/cubic_sender.go deleted file mode 100644 index 71bebe71af..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/cubic_sender.go +++ /dev/null @@ -1,329 +0,0 @@ -package congestion - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -const ( - maxBurstBytes = 3 * protocol.DefaultTCPMSS - renoBeta float32 = 0.7 // Reno backoff factor. - defaultMinimumCongestionWindow protocol.ByteCount = 2 * protocol.DefaultTCPMSS -) - -type cubicSender struct { - hybridSlowStart HybridSlowStart - prr PrrSender - rttStats *RTTStats - stats connectionStats - cubic *Cubic - - noPRR bool - reno bool - - // Track the largest packet that has been sent. - largestSentPacketNumber protocol.PacketNumber - - // Track the largest packet that has been acked. - largestAckedPacketNumber protocol.PacketNumber - - // Track the largest packet number outstanding when a CWND cutback occurs. - largestSentAtLastCutback protocol.PacketNumber - - // Whether the last loss event caused us to exit slowstart. - // Used for stats collection of slowstartPacketsLost - lastCutbackExitedSlowstart bool - - // When true, exit slow start with large cutback of congestion window. - slowStartLargeReduction bool - - // Congestion window in packets. - congestionWindow protocol.ByteCount - - // Minimum congestion window in packets. - minCongestionWindow protocol.ByteCount - - // Maximum congestion window. - maxCongestionWindow protocol.ByteCount - - // Slow start congestion window in bytes, aka ssthresh. - slowstartThreshold protocol.ByteCount - - // Number of connections to simulate. - numConnections int - - // ACK counter for the Reno implementation. - numAckedPackets uint64 - - initialCongestionWindow protocol.ByteCount - initialMaxCongestionWindow protocol.ByteCount - - minSlowStartExitWindow protocol.ByteCount -} - -var _ SendAlgorithm = &cubicSender{} -var _ SendAlgorithmWithDebugInfos = &cubicSender{} - -// NewCubicSender makes a new cubic sender -func NewCubicSender(clock Clock, rttStats *RTTStats, reno bool, initialCongestionWindow, initialMaxCongestionWindow protocol.ByteCount) *cubicSender { - return &cubicSender{ - rttStats: rttStats, - largestSentPacketNumber: protocol.InvalidPacketNumber, - largestAckedPacketNumber: protocol.InvalidPacketNumber, - largestSentAtLastCutback: protocol.InvalidPacketNumber, - initialCongestionWindow: initialCongestionWindow, - initialMaxCongestionWindow: initialMaxCongestionWindow, - congestionWindow: initialCongestionWindow, - minCongestionWindow: defaultMinimumCongestionWindow, - slowstartThreshold: initialMaxCongestionWindow, - maxCongestionWindow: initialMaxCongestionWindow, - numConnections: defaultNumConnections, - cubic: NewCubic(clock), - reno: reno, - } -} - -// TimeUntilSend returns when the next packet should be sent. -func (c *cubicSender) TimeUntilSend(bytesInFlight protocol.ByteCount) time.Duration { - if !c.noPRR && c.InRecovery() { - // PRR is used when in recovery. - if c.prr.CanSend(c.GetCongestionWindow(), bytesInFlight, c.GetSlowStartThreshold()) { - return 0 - } - } - return c.rttStats.SmoothedRTT() * time.Duration(protocol.DefaultTCPMSS) / time.Duration(2*c.GetCongestionWindow()) -} - -func (c *cubicSender) OnPacketSent( - sentTime time.Time, - bytesInFlight protocol.ByteCount, - packetNumber protocol.PacketNumber, - bytes protocol.ByteCount, - isRetransmittable bool, -) { - if !isRetransmittable { - return - } - if c.InRecovery() { - // PRR is used when in recovery. - c.prr.OnPacketSent(bytes) - } - c.largestSentPacketNumber = packetNumber - c.hybridSlowStart.OnPacketSent(packetNumber) -} - -func (c *cubicSender) CanSend(bytesInFlight protocol.ByteCount) bool { - if !c.noPRR && c.InRecovery() { - return c.prr.CanSend(c.GetCongestionWindow(), bytesInFlight, c.GetSlowStartThreshold()) - } - return bytesInFlight < c.GetCongestionWindow() -} - -func (c *cubicSender) InRecovery() bool { - return c.largestAckedPacketNumber != protocol.InvalidPacketNumber && c.largestAckedPacketNumber <= c.largestSentAtLastCutback -} - -func (c *cubicSender) InSlowStart() bool { - return c.GetCongestionWindow() < c.GetSlowStartThreshold() -} - -func (c *cubicSender) GetCongestionWindow() protocol.ByteCount { - return c.congestionWindow -} - -func (c *cubicSender) GetSlowStartThreshold() protocol.ByteCount { - return c.slowstartThreshold -} - -func (c *cubicSender) ExitSlowstart() { - c.slowstartThreshold = c.congestionWindow -} - -func (c *cubicSender) SlowstartThreshold() protocol.ByteCount { - return c.slowstartThreshold -} - -func (c *cubicSender) MaybeExitSlowStart() { - if c.InSlowStart() && c.hybridSlowStart.ShouldExitSlowStart(c.rttStats.LatestRTT(), c.rttStats.MinRTT(), c.GetCongestionWindow()/protocol.DefaultTCPMSS) { - c.ExitSlowstart() - } -} - -func (c *cubicSender) OnPacketAcked( - ackedPacketNumber protocol.PacketNumber, - ackedBytes protocol.ByteCount, - priorInFlight protocol.ByteCount, - eventTime time.Time, -) { - c.largestAckedPacketNumber = utils.MaxPacketNumber(ackedPacketNumber, c.largestAckedPacketNumber) - if c.InRecovery() { - // PRR is used when in recovery. - if !c.noPRR { - c.prr.OnPacketAcked(ackedBytes) - } - return - } - c.maybeIncreaseCwnd(ackedPacketNumber, ackedBytes, priorInFlight, eventTime) - if c.InSlowStart() { - c.hybridSlowStart.OnPacketAcked(ackedPacketNumber) - } -} - -func (c *cubicSender) OnPacketLost( - packetNumber protocol.PacketNumber, - lostBytes protocol.ByteCount, - priorInFlight protocol.ByteCount, -) { - // TCP NewReno (RFC6582) says that once a loss occurs, any losses in packets - // already sent should be treated as a single loss event, since it's expected. - if packetNumber <= c.largestSentAtLastCutback { - if c.lastCutbackExitedSlowstart { - c.stats.slowstartPacketsLost++ - c.stats.slowstartBytesLost += lostBytes - if c.slowStartLargeReduction { - // Reduce congestion window by lost_bytes for every loss. - c.congestionWindow = utils.MaxByteCount(c.congestionWindow-lostBytes, c.minSlowStartExitWindow) - c.slowstartThreshold = c.congestionWindow - } - } - return - } - c.lastCutbackExitedSlowstart = c.InSlowStart() - if c.InSlowStart() { - c.stats.slowstartPacketsLost++ - } - - if !c.noPRR { - c.prr.OnPacketLost(priorInFlight) - } - - // TODO(chromium): Separate out all of slow start into a separate class. - if c.slowStartLargeReduction && c.InSlowStart() { - if c.congestionWindow >= 2*c.initialCongestionWindow { - c.minSlowStartExitWindow = c.congestionWindow / 2 - } - c.congestionWindow -= protocol.DefaultTCPMSS - } else if c.reno { - c.congestionWindow = protocol.ByteCount(float32(c.congestionWindow) * c.RenoBeta()) - } else { - c.congestionWindow = c.cubic.CongestionWindowAfterPacketLoss(c.congestionWindow) - } - if c.congestionWindow < c.minCongestionWindow { - c.congestionWindow = c.minCongestionWindow - } - c.slowstartThreshold = c.congestionWindow - c.largestSentAtLastCutback = c.largestSentPacketNumber - // reset packet count from congestion avoidance mode. We start - // counting again when we're out of recovery. - c.numAckedPackets = 0 -} - -func (c *cubicSender) RenoBeta() float32 { - // kNConnectionBeta is the backoff factor after loss for our N-connection - // emulation, which emulates the effective backoff of an ensemble of N - // TCP-Reno connections on a single loss event. The effective multiplier is - // computed as: - return (float32(c.numConnections) - 1. + renoBeta) / float32(c.numConnections) -} - -// Called when we receive an ack. Normal TCP tracks how many packets one ack -// represents, but quic has a separate ack for each packet. -func (c *cubicSender) maybeIncreaseCwnd( - ackedPacketNumber protocol.PacketNumber, - ackedBytes protocol.ByteCount, - priorInFlight protocol.ByteCount, - eventTime time.Time, -) { - // Do not increase the congestion window unless the sender is close to using - // the current window. - if !c.isCwndLimited(priorInFlight) { - c.cubic.OnApplicationLimited() - return - } - if c.congestionWindow >= c.maxCongestionWindow { - return - } - if c.InSlowStart() { - // TCP slow start, exponential growth, increase by one for each ACK. - c.congestionWindow += protocol.DefaultTCPMSS - return - } - // Congestion avoidance - if c.reno { - // Classic Reno congestion avoidance. - c.numAckedPackets++ - // Divide by num_connections to smoothly increase the CWND at a faster - // rate than conventional Reno. - if c.numAckedPackets*uint64(c.numConnections) >= uint64(c.congestionWindow)/uint64(protocol.DefaultTCPMSS) { - c.congestionWindow += protocol.DefaultTCPMSS - c.numAckedPackets = 0 - } - } else { - c.congestionWindow = utils.MinByteCount(c.maxCongestionWindow, c.cubic.CongestionWindowAfterAck(ackedBytes, c.congestionWindow, c.rttStats.MinRTT(), eventTime)) - } -} - -func (c *cubicSender) isCwndLimited(bytesInFlight protocol.ByteCount) bool { - congestionWindow := c.GetCongestionWindow() - if bytesInFlight >= congestionWindow { - return true - } - availableBytes := congestionWindow - bytesInFlight - slowStartLimited := c.InSlowStart() && bytesInFlight > congestionWindow/2 - return slowStartLimited || availableBytes <= maxBurstBytes -} - -// BandwidthEstimate returns the current bandwidth estimate -func (c *cubicSender) BandwidthEstimate() Bandwidth { - srtt := c.rttStats.SmoothedRTT() - if srtt == 0 { - // If we haven't measured an rtt, the bandwidth estimate is unknown. - return 0 - } - return BandwidthFromDelta(c.GetCongestionWindow(), srtt) -} - -// HybridSlowStart returns the hybrid slow start instance for testing -func (c *cubicSender) HybridSlowStart() *HybridSlowStart { - return &c.hybridSlowStart -} - -// SetNumEmulatedConnections sets the number of emulated connections -func (c *cubicSender) SetNumEmulatedConnections(n int) { - c.numConnections = utils.Max(n, 1) - c.cubic.SetNumConnections(c.numConnections) -} - -// OnRetransmissionTimeout is called on an retransmission timeout -func (c *cubicSender) OnRetransmissionTimeout(packetsRetransmitted bool) { - c.largestSentAtLastCutback = protocol.InvalidPacketNumber - if !packetsRetransmitted { - return - } - c.hybridSlowStart.Restart() - c.cubic.Reset() - c.slowstartThreshold = c.congestionWindow / 2 - c.congestionWindow = c.minCongestionWindow -} - -// OnConnectionMigration is called when the connection is migrated (?) -func (c *cubicSender) OnConnectionMigration() { - c.hybridSlowStart.Restart() - c.prr = PrrSender{} - c.largestSentPacketNumber = protocol.InvalidPacketNumber - c.largestAckedPacketNumber = protocol.InvalidPacketNumber - c.largestSentAtLastCutback = protocol.InvalidPacketNumber - c.lastCutbackExitedSlowstart = false - c.cubic.Reset() - c.numAckedPackets = 0 - c.congestionWindow = c.initialCongestionWindow - c.slowstartThreshold = c.initialMaxCongestionWindow - c.maxCongestionWindow = c.initialMaxCongestionWindow -} - -// SetSlowStartLargeReduction allows enabling the SSLR experiment -func (c *cubicSender) SetSlowStartLargeReduction(enabled bool) { - c.slowStartLargeReduction = enabled -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/hybrid_slow_start.go b/vendor/github.com/lucas-clemente/quic-go/internal/congestion/hybrid_slow_start.go deleted file mode 100644 index f41c1e5c32..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/hybrid_slow_start.go +++ /dev/null @@ -1,111 +0,0 @@ -package congestion - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// Note(pwestin): the magic clamping numbers come from the original code in -// tcp_cubic.c. -const hybridStartLowWindow = protocol.ByteCount(16) - -// Number of delay samples for detecting the increase of delay. -const hybridStartMinSamples = uint32(8) - -// Exit slow start if the min rtt has increased by more than 1/8th. -const hybridStartDelayFactorExp = 3 // 2^3 = 8 -// The original paper specifies 2 and 8ms, but those have changed over time. -const hybridStartDelayMinThresholdUs = int64(4000) -const hybridStartDelayMaxThresholdUs = int64(16000) - -// HybridSlowStart implements the TCP hybrid slow start algorithm -type HybridSlowStart struct { - endPacketNumber protocol.PacketNumber - lastSentPacketNumber protocol.PacketNumber - started bool - currentMinRTT time.Duration - rttSampleCount uint32 - hystartFound bool -} - -// StartReceiveRound is called for the start of each receive round (burst) in the slow start phase. -func (s *HybridSlowStart) StartReceiveRound(lastSent protocol.PacketNumber) { - s.endPacketNumber = lastSent - s.currentMinRTT = 0 - s.rttSampleCount = 0 - s.started = true -} - -// IsEndOfRound returns true if this ack is the last packet number of our current slow start round. -func (s *HybridSlowStart) IsEndOfRound(ack protocol.PacketNumber) bool { - return s.endPacketNumber < ack -} - -// ShouldExitSlowStart should be called on every new ack frame, since a new -// RTT measurement can be made then. -// rtt: the RTT for this ack packet. -// minRTT: is the lowest delay (RTT) we have seen during the session. -// congestionWindow: the congestion window in packets. -func (s *HybridSlowStart) ShouldExitSlowStart(latestRTT time.Duration, minRTT time.Duration, congestionWindow protocol.ByteCount) bool { - if !s.started { - // Time to start the hybrid slow start. - s.StartReceiveRound(s.lastSentPacketNumber) - } - if s.hystartFound { - return true - } - // Second detection parameter - delay increase detection. - // Compare the minimum delay (s.currentMinRTT) of the current - // burst of packets relative to the minimum delay during the session. - // Note: we only look at the first few(8) packets in each burst, since we - // only want to compare the lowest RTT of the burst relative to previous - // bursts. - s.rttSampleCount++ - if s.rttSampleCount <= hybridStartMinSamples { - if s.currentMinRTT == 0 || s.currentMinRTT > latestRTT { - s.currentMinRTT = latestRTT - } - } - // We only need to check this once per round. - if s.rttSampleCount == hybridStartMinSamples { - // Divide minRTT by 8 to get a rtt increase threshold for exiting. - minRTTincreaseThresholdUs := int64(minRTT / time.Microsecond >> hybridStartDelayFactorExp) - // Ensure the rtt threshold is never less than 2ms or more than 16ms. - minRTTincreaseThresholdUs = utils.MinInt64(minRTTincreaseThresholdUs, hybridStartDelayMaxThresholdUs) - minRTTincreaseThreshold := time.Duration(utils.MaxInt64(minRTTincreaseThresholdUs, hybridStartDelayMinThresholdUs)) * time.Microsecond - - if s.currentMinRTT > (minRTT + minRTTincreaseThreshold) { - s.hystartFound = true - } - } - // Exit from slow start if the cwnd is greater than 16 and - // increasing delay is found. - return congestionWindow >= hybridStartLowWindow && s.hystartFound -} - -// OnPacketSent is called when a packet was sent -func (s *HybridSlowStart) OnPacketSent(packetNumber protocol.PacketNumber) { - s.lastSentPacketNumber = packetNumber -} - -// OnPacketAcked gets invoked after ShouldExitSlowStart, so it's best to end -// the round when the final packet of the burst is received and start it on -// the next incoming ack. -func (s *HybridSlowStart) OnPacketAcked(ackedPacketNumber protocol.PacketNumber) { - if s.IsEndOfRound(ackedPacketNumber) { - s.started = false - } -} - -// Started returns true if started -func (s *HybridSlowStart) Started() bool { - return s.started -} - -// Restart the slow start phase -func (s *HybridSlowStart) Restart() { - s.started = false - s.hystartFound = false -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/interface.go b/vendor/github.com/lucas-clemente/quic-go/internal/congestion/interface.go deleted file mode 100644 index 7f09246e60..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/interface.go +++ /dev/null @@ -1,26 +0,0 @@ -package congestion - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// A SendAlgorithm performs congestion control -type SendAlgorithm interface { - TimeUntilSend(bytesInFlight protocol.ByteCount) time.Duration - OnPacketSent(sentTime time.Time, bytesInFlight protocol.ByteCount, packetNumber protocol.PacketNumber, bytes protocol.ByteCount, isRetransmittable bool) - CanSend(bytesInFlight protocol.ByteCount) bool - MaybeExitSlowStart() - OnPacketAcked(number protocol.PacketNumber, ackedBytes protocol.ByteCount, priorInFlight protocol.ByteCount, eventTime time.Time) - OnPacketLost(number protocol.PacketNumber, lostBytes protocol.ByteCount, priorInFlight protocol.ByteCount) - OnRetransmissionTimeout(packetsRetransmitted bool) -} - -// A SendAlgorithmWithDebugInfos is a SendAlgorithm that exposes some debug infos -type SendAlgorithmWithDebugInfos interface { - SendAlgorithm - InSlowStart() bool - InRecovery() bool - GetCongestionWindow() protocol.ByteCount -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/prr_sender.go b/vendor/github.com/lucas-clemente/quic-go/internal/congestion/prr_sender.go deleted file mode 100644 index 5c807d1905..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/prr_sender.go +++ /dev/null @@ -1,54 +0,0 @@ -package congestion - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// PrrSender implements the Proportional Rate Reduction (PRR) per RFC 6937 -type PrrSender struct { - bytesSentSinceLoss protocol.ByteCount - bytesDeliveredSinceLoss protocol.ByteCount - ackCountSinceLoss protocol.ByteCount - bytesInFlightBeforeLoss protocol.ByteCount -} - -// OnPacketSent should be called after a packet was sent -func (p *PrrSender) OnPacketSent(sentBytes protocol.ByteCount) { - p.bytesSentSinceLoss += sentBytes -} - -// OnPacketLost should be called on the first loss that triggers a recovery -// period and all other methods in this class should only be called when in -// recovery. -func (p *PrrSender) OnPacketLost(priorInFlight protocol.ByteCount) { - p.bytesSentSinceLoss = 0 - p.bytesInFlightBeforeLoss = priorInFlight - p.bytesDeliveredSinceLoss = 0 - p.ackCountSinceLoss = 0 -} - -// OnPacketAcked should be called after a packet was acked -func (p *PrrSender) OnPacketAcked(ackedBytes protocol.ByteCount) { - p.bytesDeliveredSinceLoss += ackedBytes - p.ackCountSinceLoss++ -} - -// CanSend returns if packets can be sent -func (p *PrrSender) CanSend(congestionWindow, bytesInFlight, slowstartThreshold protocol.ByteCount) bool { - // Return QuicTime::Zero In order to ensure limited transmit always works. - if p.bytesSentSinceLoss == 0 || bytesInFlight < protocol.DefaultTCPMSS { - return true - } - if congestionWindow > bytesInFlight { - // During PRR-SSRB, limit outgoing packets to 1 extra MSS per ack, instead - // of sending the entire available window. This prevents burst retransmits - // when more packets are lost than the CWND reduction. - // limit = MAX(prr_delivered - prr_out, DeliveredData) + MSS - return p.bytesDeliveredSinceLoss+p.ackCountSinceLoss*protocol.DefaultTCPMSS > p.bytesSentSinceLoss - } - // Implement Proportional Rate Reduction (RFC6937). - // Checks a simplified version of the PRR formula that doesn't use division: - // AvailableSendWindow = - // CEIL(prr_delivered * ssthresh / BytesInFlightAtLoss) - prr_sent - return p.bytesDeliveredSinceLoss*slowstartThreshold > p.bytesSentSinceLoss*p.bytesInFlightBeforeLoss -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/rtt_stats.go b/vendor/github.com/lucas-clemente/quic-go/internal/congestion/rtt_stats.go deleted file mode 100644 index a44d799133..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/rtt_stats.go +++ /dev/null @@ -1,114 +0,0 @@ -package congestion - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -const ( - rttAlpha float32 = 0.125 - oneMinusAlpha float32 = (1 - rttAlpha) - rttBeta float32 = 0.25 - oneMinusBeta float32 = (1 - rttBeta) - // The default RTT used before an RTT sample is taken. - defaultInitialRTT = 100 * time.Millisecond -) - -// RTTStats provides round-trip statistics -type RTTStats struct { - minRTT time.Duration - latestRTT time.Duration - smoothedRTT time.Duration - meanDeviation time.Duration - - maxAckDelay time.Duration -} - -// NewRTTStats makes a properly initialized RTTStats object -func NewRTTStats() *RTTStats { - return &RTTStats{} -} - -// MinRTT Returns the minRTT for the entire connection. -// May return Zero if no valid updates have occurred. -func (r *RTTStats) MinRTT() time.Duration { return r.minRTT } - -// LatestRTT returns the most recent rtt measurement. -// May return Zero if no valid updates have occurred. -func (r *RTTStats) LatestRTT() time.Duration { return r.latestRTT } - -// SmoothedRTT returns the EWMA smoothed RTT for the connection. -// May return Zero if no valid updates have occurred. -func (r *RTTStats) SmoothedRTT() time.Duration { return r.smoothedRTT } - -// SmoothedOrInitialRTT returns the EWMA smoothed RTT for the connection. -// If no valid updates have occurred, it returns the initial RTT. -func (r *RTTStats) SmoothedOrInitialRTT() time.Duration { - if r.smoothedRTT != 0 { - return r.smoothedRTT - } - return defaultInitialRTT -} - -// MeanDeviation gets the mean deviation -func (r *RTTStats) MeanDeviation() time.Duration { return r.meanDeviation } - -func (r *RTTStats) MaxAckDelay() time.Duration { return r.maxAckDelay } - -func (r *RTTStats) PTO() time.Duration { - return r.SmoothedOrInitialRTT() + utils.MaxDuration(4*r.MeanDeviation(), protocol.TimerGranularity) + r.MaxAckDelay() -} - -// UpdateRTT updates the RTT based on a new sample. -func (r *RTTStats) UpdateRTT(sendDelta, ackDelay time.Duration, now time.Time) { - if sendDelta == utils.InfDuration || sendDelta <= 0 { - return - } - - // Update r.minRTT first. r.minRTT does not use an rttSample corrected for - // ackDelay but the raw observed sendDelta, since poor clock granularity at - // the client may cause a high ackDelay to result in underestimation of the - // r.minRTT. - if r.minRTT == 0 || r.minRTT > sendDelta { - r.minRTT = sendDelta - } - - // Correct for ackDelay if information received from the peer results in a - // an RTT sample at least as large as minRTT. Otherwise, only use the - // sendDelta. - sample := sendDelta - if sample-r.minRTT >= ackDelay { - sample -= ackDelay - } - r.latestRTT = sample - // First time call. - if r.smoothedRTT == 0 { - r.smoothedRTT = sample - r.meanDeviation = sample / 2 - } else { - r.meanDeviation = time.Duration(oneMinusBeta*float32(r.meanDeviation/time.Microsecond)+rttBeta*float32(utils.AbsDuration(r.smoothedRTT-sample)/time.Microsecond)) * time.Microsecond - r.smoothedRTT = time.Duration((float32(r.smoothedRTT/time.Microsecond)*oneMinusAlpha)+(float32(sample/time.Microsecond)*rttAlpha)) * time.Microsecond - } -} - -func (r *RTTStats) SetMaxAckDelay(mad time.Duration) { - r.maxAckDelay = mad -} - -// OnConnectionMigration is called when connection migrates and rtt measurement needs to be reset. -func (r *RTTStats) OnConnectionMigration() { - r.latestRTT = 0 - r.minRTT = 0 - r.smoothedRTT = 0 - r.meanDeviation = 0 -} - -// ExpireSmoothedMetrics causes the smoothed_rtt to be increased to the latest_rtt if the latest_rtt -// is larger. The mean deviation is increased to the most recent deviation if -// it's larger. -func (r *RTTStats) ExpireSmoothedMetrics() { - r.meanDeviation = utils.MaxDuration(r.meanDeviation, utils.AbsDuration(r.smoothedRTT-r.latestRTT)) - r.smoothedRTT = utils.MaxDuration(r.smoothedRTT, r.latestRTT) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/stats.go b/vendor/github.com/lucas-clemente/quic-go/internal/congestion/stats.go deleted file mode 100644 index ed669c1465..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/congestion/stats.go +++ /dev/null @@ -1,8 +0,0 @@ -package congestion - -import "github.com/lucas-clemente/quic-go/internal/protocol" - -type connectionStats struct { - slowstartPacketsLost protocol.PacketNumber - slowstartBytesLost protocol.ByteCount -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/base_flow_controller.go b/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/base_flow_controller.go deleted file mode 100644 index 6a0aa3c58d..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/base_flow_controller.go +++ /dev/null @@ -1,122 +0,0 @@ -package flowcontrol - -import ( - "sync" - "time" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -type baseFlowController struct { - // for sending data - bytesSent protocol.ByteCount - sendWindow protocol.ByteCount - lastBlockedAt protocol.ByteCount - - // for receiving data - mutex sync.RWMutex - bytesRead protocol.ByteCount - highestReceived protocol.ByteCount - receiveWindow protocol.ByteCount - receiveWindowSize protocol.ByteCount - maxReceiveWindowSize protocol.ByteCount - - epochStartTime time.Time - epochStartOffset protocol.ByteCount - rttStats *congestion.RTTStats - - logger utils.Logger -} - -// IsNewlyBlocked says if it is newly blocked by flow control. -// For every offset, it only returns true once. -// If it is blocked, the offset is returned. -func (c *baseFlowController) IsNewlyBlocked() (bool, protocol.ByteCount) { - if c.sendWindowSize() != 0 || c.sendWindow == c.lastBlockedAt { - return false, 0 - } - c.lastBlockedAt = c.sendWindow - return true, c.sendWindow -} - -func (c *baseFlowController) AddBytesSent(n protocol.ByteCount) { - c.bytesSent += n -} - -// UpdateSendWindow should be called after receiving a WindowUpdateFrame -// it returns true if the window was actually updated -func (c *baseFlowController) UpdateSendWindow(offset protocol.ByteCount) { - if offset > c.sendWindow { - c.sendWindow = offset - } -} - -func (c *baseFlowController) sendWindowSize() protocol.ByteCount { - // this only happens during connection establishment, when data is sent before we receive the peer's transport parameters - if c.bytesSent > c.sendWindow { - return 0 - } - return c.sendWindow - c.bytesSent -} - -func (c *baseFlowController) AddBytesRead(n protocol.ByteCount) { - c.mutex.Lock() - defer c.mutex.Unlock() - - // pretend we sent a WindowUpdate when reading the first byte - // this way auto-tuning of the window size already works for the first WindowUpdate - if c.bytesRead == 0 { - c.startNewAutoTuningEpoch() - } - c.bytesRead += n -} - -func (c *baseFlowController) hasWindowUpdate() bool { - bytesRemaining := c.receiveWindow - c.bytesRead - // update the window when more than the threshold was consumed - return bytesRemaining <= protocol.ByteCount((float64(c.receiveWindowSize) * float64((1 - protocol.WindowUpdateThreshold)))) -} - -// getWindowUpdate updates the receive window, if necessary -// it returns the new offset -func (c *baseFlowController) getWindowUpdate() protocol.ByteCount { - if !c.hasWindowUpdate() { - return 0 - } - - c.maybeAdjustWindowSize() - c.receiveWindow = c.bytesRead + c.receiveWindowSize - return c.receiveWindow -} - -// maybeAdjustWindowSize increases the receiveWindowSize if we're sending updates too often. -// For details about auto-tuning, see https://docs.google.com/document/d/1SExkMmGiz8VYzV3s9E35JQlJ73vhzCekKkDi85F1qCE/edit?usp=sharing. -func (c *baseFlowController) maybeAdjustWindowSize() { - bytesReadInEpoch := c.bytesRead - c.epochStartOffset - // don't do anything if less than half the window has been consumed - if bytesReadInEpoch <= c.receiveWindowSize/2 { - return - } - rtt := c.rttStats.SmoothedRTT() - if rtt == 0 { - return - } - - fraction := float64(bytesReadInEpoch) / float64(c.receiveWindowSize) - if time.Since(c.epochStartTime) < time.Duration(4*fraction*float64(rtt)) { - // window is consumed too fast, try to increase the window size - c.receiveWindowSize = utils.MinByteCount(2*c.receiveWindowSize, c.maxReceiveWindowSize) - } - c.startNewAutoTuningEpoch() -} - -func (c *baseFlowController) startNewAutoTuningEpoch() { - c.epochStartTime = time.Now() - c.epochStartOffset = c.bytesRead -} - -func (c *baseFlowController) checkFlowControlViolation() bool { - return c.highestReceived > c.receiveWindow -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/connection_flow_controller.go b/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/connection_flow_controller.go deleted file mode 100644 index 1393335b06..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/connection_flow_controller.go +++ /dev/null @@ -1,92 +0,0 @@ -package flowcontrol - -import ( - "fmt" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/qerr" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -type connectionFlowController struct { - baseFlowController - - queueWindowUpdate func() -} - -var _ ConnectionFlowController = &connectionFlowController{} - -// NewConnectionFlowController gets a new flow controller for the connection -// It is created before we receive the peer's transport paramenters, thus it starts with a sendWindow of 0. -func NewConnectionFlowController( - receiveWindow protocol.ByteCount, - maxReceiveWindow protocol.ByteCount, - queueWindowUpdate func(), - rttStats *congestion.RTTStats, - logger utils.Logger, -) ConnectionFlowController { - return &connectionFlowController{ - baseFlowController: baseFlowController{ - rttStats: rttStats, - receiveWindow: receiveWindow, - receiveWindowSize: receiveWindow, - maxReceiveWindowSize: maxReceiveWindow, - logger: logger, - }, - queueWindowUpdate: queueWindowUpdate, - } -} - -func (c *connectionFlowController) SendWindowSize() protocol.ByteCount { - return c.baseFlowController.sendWindowSize() -} - -// IncrementHighestReceived adds an increment to the highestReceived value -func (c *connectionFlowController) IncrementHighestReceived(increment protocol.ByteCount) error { - c.mutex.Lock() - defer c.mutex.Unlock() - - c.highestReceived += increment - if c.checkFlowControlViolation() { - return qerr.Error(qerr.FlowControlError, fmt.Sprintf("Received %d bytes for the connection, allowed %d bytes", c.highestReceived, c.receiveWindow)) - } - return nil -} - -func (c *connectionFlowController) AddBytesRead(n protocol.ByteCount) { - c.baseFlowController.AddBytesRead(n) - c.maybeQueueWindowUpdate() -} - -func (c *connectionFlowController) maybeQueueWindowUpdate() { - c.mutex.Lock() - hasWindowUpdate := c.hasWindowUpdate() - c.mutex.Unlock() - if hasWindowUpdate { - c.queueWindowUpdate() - } -} - -func (c *connectionFlowController) GetWindowUpdate() protocol.ByteCount { - c.mutex.Lock() - oldWindowSize := c.receiveWindowSize - offset := c.baseFlowController.getWindowUpdate() - if oldWindowSize < c.receiveWindowSize { - c.logger.Debugf("Increasing receive flow control window for the connection to %d kB", c.receiveWindowSize/(1<<10)) - } - c.mutex.Unlock() - return offset -} - -// EnsureMinimumWindowSize sets a minimum window size -// it should make sure that the connection-level window is increased when a stream-level window grows -func (c *connectionFlowController) EnsureMinimumWindowSize(inc protocol.ByteCount) { - c.mutex.Lock() - if inc > c.receiveWindowSize { - c.logger.Debugf("Increasing receive flow control window for the connection to %d kB, in response to stream flow control window increase", c.receiveWindowSize/(1<<10)) - c.receiveWindowSize = utils.MinByteCount(inc, c.maxReceiveWindowSize) - c.startNewAutoTuningEpoch() - } - c.mutex.Unlock() -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/interface.go b/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/interface.go deleted file mode 100644 index a47e7cd766..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/interface.go +++ /dev/null @@ -1,41 +0,0 @@ -package flowcontrol - -import "github.com/lucas-clemente/quic-go/internal/protocol" - -type flowController interface { - // for sending - SendWindowSize() protocol.ByteCount - UpdateSendWindow(protocol.ByteCount) - AddBytesSent(protocol.ByteCount) - // for receiving - AddBytesRead(protocol.ByteCount) - GetWindowUpdate() protocol.ByteCount // returns 0 if no update is necessary - IsNewlyBlocked() (bool, protocol.ByteCount) -} - -// A StreamFlowController is a flow controller for a QUIC stream. -type StreamFlowController interface { - flowController - // for receiving - // UpdateHighestReceived should be called when a new highest offset is received - // final has to be to true if this is the final offset of the stream, - // as contained in a STREAM frame with FIN bit, and the RESET_STREAM frame - UpdateHighestReceived(offset protocol.ByteCount, final bool) error - // Abandon should be called when reading from the stream is aborted early, - // and there won't be any further calls to AddBytesRead. - Abandon() -} - -// The ConnectionFlowController is the flow controller for the connection. -type ConnectionFlowController interface { - flowController -} - -type connectionFlowControllerI interface { - ConnectionFlowController - // The following two methods are not supposed to be called from outside this packet, but are needed internally - // for sending - EnsureMinimumWindowSize(protocol.ByteCount) - // for receiving - IncrementHighestReceived(protocol.ByteCount) error -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/stream_flow_controller.go b/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/stream_flow_controller.go deleted file mode 100644 index bb22337df0..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/flowcontrol/stream_flow_controller.go +++ /dev/null @@ -1,139 +0,0 @@ -package flowcontrol - -import ( - "fmt" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/qerr" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -type streamFlowController struct { - baseFlowController - - streamID protocol.StreamID - - queueWindowUpdate func() - - connection connectionFlowControllerI - - receivedFinalOffset bool -} - -var _ StreamFlowController = &streamFlowController{} - -// NewStreamFlowController gets a new flow controller for a stream -func NewStreamFlowController( - streamID protocol.StreamID, - cfc ConnectionFlowController, - receiveWindow protocol.ByteCount, - maxReceiveWindow protocol.ByteCount, - initialSendWindow protocol.ByteCount, - queueWindowUpdate func(protocol.StreamID), - rttStats *congestion.RTTStats, - logger utils.Logger, -) StreamFlowController { - return &streamFlowController{ - streamID: streamID, - connection: cfc.(connectionFlowControllerI), - queueWindowUpdate: func() { queueWindowUpdate(streamID) }, - baseFlowController: baseFlowController{ - rttStats: rttStats, - receiveWindow: receiveWindow, - receiveWindowSize: receiveWindow, - maxReceiveWindowSize: maxReceiveWindow, - sendWindow: initialSendWindow, - logger: logger, - }, - } -} - -// UpdateHighestReceived updates the highestReceived value, if the offset is higher. -func (c *streamFlowController) UpdateHighestReceived(offset protocol.ByteCount, final bool) error { - c.mutex.Lock() - defer c.mutex.Unlock() - - // If the final offset for this stream is already known, check for consistency. - if c.receivedFinalOffset { - // If we receive another final offset, check that it's the same. - if final && offset != c.highestReceived { - return qerr.Error(qerr.FinalSizeError, fmt.Sprintf("Received inconsistent final offset for stream %d (old: %#x, new: %#x bytes)", c.streamID, c.highestReceived, offset)) - } - // Check that the offset is below the final offset. - if offset > c.highestReceived { - return qerr.Error(qerr.FinalSizeError, fmt.Sprintf("Received offset %#x for stream %d. Final offset was already received at %#x", offset, c.streamID, c.highestReceived)) - } - } - - if final { - c.receivedFinalOffset = true - } - if offset == c.highestReceived { - return nil - } - // A higher offset was received before. - // This can happen due to reordering. - if offset <= c.highestReceived { - if final { - return qerr.Error(qerr.FinalSizeError, fmt.Sprintf("Received final offset %#x for stream %d, but already received offset %#x before", offset, c.streamID, c.highestReceived)) - } - return nil - } - - increment := offset - c.highestReceived - c.highestReceived = offset - if c.checkFlowControlViolation() { - return qerr.Error(qerr.FlowControlError, fmt.Sprintf("Received %#x bytes on stream %d, allowed %#x bytes", offset, c.streamID, c.receiveWindow)) - } - return c.connection.IncrementHighestReceived(increment) -} - -func (c *streamFlowController) AddBytesRead(n protocol.ByteCount) { - c.baseFlowController.AddBytesRead(n) - c.maybeQueueWindowUpdate() - c.connection.AddBytesRead(n) -} - -func (c *streamFlowController) Abandon() { - if unread := c.highestReceived - c.bytesRead; unread > 0 { - c.connection.AddBytesRead(unread) - } -} - -func (c *streamFlowController) AddBytesSent(n protocol.ByteCount) { - c.baseFlowController.AddBytesSent(n) - c.connection.AddBytesSent(n) -} - -func (c *streamFlowController) SendWindowSize() protocol.ByteCount { - return utils.MinByteCount(c.baseFlowController.sendWindowSize(), c.connection.SendWindowSize()) -} - -func (c *streamFlowController) maybeQueueWindowUpdate() { - c.mutex.Lock() - hasWindowUpdate := !c.receivedFinalOffset && c.hasWindowUpdate() - c.mutex.Unlock() - if hasWindowUpdate { - c.queueWindowUpdate() - } -} - -func (c *streamFlowController) GetWindowUpdate() protocol.ByteCount { - // don't use defer for unlocking the mutex here, GetWindowUpdate() is called frequently and defer shows up in the profiler - c.mutex.Lock() - // if we already received the final offset for this stream, the peer won't need any additional flow control credit - if c.receivedFinalOffset { - c.mutex.Unlock() - return 0 - } - - oldWindowSize := c.receiveWindowSize - offset := c.baseFlowController.getWindowUpdate() - if c.receiveWindowSize > oldWindowSize { // auto-tuning enlarged the window size - c.logger.Debugf("Increasing receive flow control window for stream %d to %d kB", c.streamID, c.receiveWindowSize/(1<<10)) - c.connection.EnsureMinimumWindowSize(protocol.ByteCount(float64(c.receiveWindowSize) * protocol.ConnectionFlowControlMultiplier)) - } - c.mutex.Unlock() - return offset -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/aead.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/aead.go deleted file mode 100644 index d5d71c9bcf..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/aead.go +++ /dev/null @@ -1,110 +0,0 @@ -package handshake - -import ( - "crypto/aes" - "crypto/cipher" - "encoding/binary" - "fmt" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/marten-seemann/qtls" -) - -type sealer struct { - aead cipher.AEAD - hpEncrypter cipher.Block - - // use a single slice to avoid allocations - nonceBuf []byte - hpMask []byte -} - -var _ LongHeaderSealer = &sealer{} - -func newLongHeaderSealer(aead cipher.AEAD, hpEncrypter cipher.Block) LongHeaderSealer { - return &sealer{ - aead: aead, - nonceBuf: make([]byte, aead.NonceSize()), - hpEncrypter: hpEncrypter, - hpMask: make([]byte, hpEncrypter.BlockSize()), - } -} - -func (s *sealer) Seal(dst, src []byte, pn protocol.PacketNumber, ad []byte) []byte { - binary.BigEndian.PutUint64(s.nonceBuf[len(s.nonceBuf)-8:], uint64(pn)) - // The AEAD we're using here will be the qtls.aeadAESGCM13. - // It uses the nonce provided here and XOR it with the IV. - return s.aead.Seal(dst, s.nonceBuf, src, ad) -} - -func (s *sealer) EncryptHeader(sample []byte, firstByte *byte, pnBytes []byte) { - if len(sample) != s.hpEncrypter.BlockSize() { - panic("invalid sample size") - } - s.hpEncrypter.Encrypt(s.hpMask, sample) - *firstByte ^= s.hpMask[0] & 0xf - for i := range pnBytes { - pnBytes[i] ^= s.hpMask[i+1] - } -} - -func (s *sealer) Overhead() int { - return s.aead.Overhead() -} - -type longHeaderOpener struct { - aead cipher.AEAD - pnDecrypter cipher.Block - - // use a single slice to avoid allocations - nonceBuf []byte - hpMask []byte -} - -var _ LongHeaderOpener = &longHeaderOpener{} - -func newLongHeaderOpener(aead cipher.AEAD, pnDecrypter cipher.Block) LongHeaderOpener { - return &longHeaderOpener{ - aead: aead, - nonceBuf: make([]byte, aead.NonceSize()), - pnDecrypter: pnDecrypter, - hpMask: make([]byte, pnDecrypter.BlockSize()), - } -} - -func (o *longHeaderOpener) Open(dst, src []byte, pn protocol.PacketNumber, ad []byte) ([]byte, error) { - binary.BigEndian.PutUint64(o.nonceBuf[len(o.nonceBuf)-8:], uint64(pn)) - // The AEAD we're using here will be the qtls.aeadAESGCM13. - // It uses the nonce provided here and XOR it with the IV. - dec, err := o.aead.Open(dst, o.nonceBuf, src, ad) - if err != nil { - err = ErrDecryptionFailed - } - return dec, err -} - -func (o *longHeaderOpener) DecryptHeader(sample []byte, firstByte *byte, pnBytes []byte) { - if len(sample) != o.pnDecrypter.BlockSize() { - panic("invalid sample size") - } - o.pnDecrypter.Encrypt(o.hpMask, sample) - *firstByte ^= o.hpMask[0] & 0xf - for i := range pnBytes { - pnBytes[i] ^= o.hpMask[i+1] - } -} - -func createAEAD(suite cipherSuite, trafficSecret []byte) cipher.AEAD { - key := qtls.HkdfExpandLabel(suite.Hash(), trafficSecret, []byte{}, "quic key", suite.KeyLen()) - iv := qtls.HkdfExpandLabel(suite.Hash(), trafficSecret, []byte{}, "quic iv", suite.IVLen()) - return suite.AEAD(key, iv) -} - -func createHeaderProtector(suite cipherSuite, trafficSecret []byte) cipher.Block { - hpKey := qtls.HkdfExpandLabel(suite.Hash(), trafficSecret, []byte{}, "quic hp", suite.KeyLen()) - hp, err := aes.NewCipher(hpKey) - if err != nil { - panic(fmt.Sprintf("error creating new AES cipher: %s", err)) - } - return hp -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/crypto_setup.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/crypto_setup.go deleted file mode 100644 index ef14753ab7..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/crypto_setup.go +++ /dev/null @@ -1,632 +0,0 @@ -package handshake - -import ( - "crypto/tls" - "errors" - "fmt" - "io" - "net" - "sync" - "unsafe" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/qerr" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/marten-seemann/qtls" -) - -// TLS unexpected_message alert -const alertUnexpectedMessage uint8 = 10 - -type messageType uint8 - -// TLS handshake message types. -const ( - typeClientHello messageType = 1 - typeServerHello messageType = 2 - typeNewSessionTicket messageType = 4 - typeEncryptedExtensions messageType = 8 - typeCertificate messageType = 11 - typeCertificateRequest messageType = 13 - typeCertificateVerify messageType = 15 - typeFinished messageType = 20 -) - -func (m messageType) String() string { - switch m { - case typeClientHello: - return "ClientHello" - case typeServerHello: - return "ServerHello" - case typeNewSessionTicket: - return "NewSessionTicket" - case typeEncryptedExtensions: - return "EncryptedExtensions" - case typeCertificate: - return "Certificate" - case typeCertificateRequest: - return "CertificateRequest" - case typeCertificateVerify: - return "CertificateVerify" - case typeFinished: - return "Finished" - default: - return fmt.Sprintf("unknown message type: %d", m) - } -} - -type cryptoSetup struct { - tlsConf *qtls.Config - conn *qtls.Conn - - messageChan chan []byte - - paramsChan <-chan []byte - - runner handshakeRunner - - closed bool - alertChan chan uint8 - // handshakeDone is closed as soon as the go routine running qtls.Handshake() returns - handshakeDone chan struct{} - // is closed when Close() is called - closeChan chan struct{} - - clientHelloWritten bool - clientHelloWrittenChan chan struct{} - - receivedWriteKey chan struct{} - receivedReadKey chan struct{} - // WriteRecord does a non-blocking send on this channel. - // This way, handleMessage can see if qtls tries to write a message. - // This is necessary: - // for servers: to see if a HelloRetryRequest should be sent in response to a ClientHello - // for clients: to see if a ServerHello is a HelloRetryRequest - writeRecord chan struct{} - - logger utils.Logger - - perspective protocol.Perspective - - mutex sync.Mutex // protects all members below - - readEncLevel protocol.EncryptionLevel - writeEncLevel protocol.EncryptionLevel - - initialStream io.Writer - initialOpener LongHeaderOpener - initialSealer LongHeaderSealer - - handshakeStream io.Writer - handshakeOpener LongHeaderOpener - handshakeSealer LongHeaderSealer - - oneRTTStream io.Writer - aead *updatableAEAD - has1RTTSealer bool - has1RTTOpener bool -} - -var _ qtls.RecordLayer = &cryptoSetup{} -var _ CryptoSetup = &cryptoSetup{} - -// NewCryptoSetupClient creates a new crypto setup for the client -func NewCryptoSetupClient( - initialStream io.Writer, - handshakeStream io.Writer, - oneRTTStream io.Writer, - connID protocol.ConnectionID, - remoteAddr net.Addr, - tp *TransportParameters, - runner handshakeRunner, - tlsConf *tls.Config, - rttStats *congestion.RTTStats, - logger utils.Logger, -) (CryptoSetup, <-chan struct{} /* ClientHello written */, error) { - cs, clientHelloWritten, err := newCryptoSetup( - initialStream, - handshakeStream, - oneRTTStream, - connID, - tp, - runner, - tlsConf, - rttStats, - logger, - protocol.PerspectiveClient, - ) - if err != nil { - return nil, nil, err - } - cs.conn = qtls.Client(newConn(remoteAddr), cs.tlsConf) - return cs, clientHelloWritten, nil -} - -// NewCryptoSetupServer creates a new crypto setup for the server -func NewCryptoSetupServer( - initialStream io.Writer, - handshakeStream io.Writer, - oneRTTStream io.Writer, - connID protocol.ConnectionID, - remoteAddr net.Addr, - tp *TransportParameters, - runner handshakeRunner, - tlsConf *tls.Config, - rttStats *congestion.RTTStats, - logger utils.Logger, -) (CryptoSetup, error) { - cs, _, err := newCryptoSetup( - initialStream, - handshakeStream, - oneRTTStream, - connID, - tp, - runner, - tlsConf, - rttStats, - logger, - protocol.PerspectiveServer, - ) - if err != nil { - return nil, err - } - cs.conn = qtls.Server(newConn(remoteAddr), cs.tlsConf) - return cs, nil -} - -func newCryptoSetup( - initialStream io.Writer, - handshakeStream io.Writer, - oneRTTStream io.Writer, - connID protocol.ConnectionID, - tp *TransportParameters, - runner handshakeRunner, - tlsConf *tls.Config, - rttStats *congestion.RTTStats, - logger utils.Logger, - perspective protocol.Perspective, -) (*cryptoSetup, <-chan struct{} /* ClientHello written */, error) { - initialSealer, initialOpener, err := NewInitialAEAD(connID, perspective) - if err != nil { - return nil, nil, err - } - extHandler := newExtensionHandler(tp.Marshal(), perspective) - cs := &cryptoSetup{ - initialStream: initialStream, - initialSealer: initialSealer, - initialOpener: initialOpener, - handshakeStream: handshakeStream, - oneRTTStream: oneRTTStream, - aead: newUpdatableAEAD(rttStats, logger), - readEncLevel: protocol.EncryptionInitial, - writeEncLevel: protocol.EncryptionInitial, - runner: runner, - paramsChan: extHandler.TransportParameters(), - logger: logger, - perspective: perspective, - handshakeDone: make(chan struct{}), - alertChan: make(chan uint8), - clientHelloWrittenChan: make(chan struct{}), - messageChan: make(chan []byte, 100), - receivedReadKey: make(chan struct{}), - receivedWriteKey: make(chan struct{}), - writeRecord: make(chan struct{}, 1), - closeChan: make(chan struct{}), - } - qtlsConf := tlsConfigToQtlsConfig(tlsConf, cs, extHandler) - cs.tlsConf = qtlsConf - return cs, cs.clientHelloWrittenChan, nil -} - -func (h *cryptoSetup) ChangeConnectionID(id protocol.ConnectionID) error { - initialSealer, initialOpener, err := NewInitialAEAD(id, h.perspective) - if err != nil { - return err - } - h.initialSealer = initialSealer - h.initialOpener = initialOpener - return nil -} - -func (h *cryptoSetup) SetLargest1RTTAcked(pn protocol.PacketNumber) { - h.aead.SetLargestAcked(pn) - // drop initial keys - // TODO: do this earlier - if h.initialOpener != nil { - h.initialOpener = nil - h.initialSealer = nil - h.runner.DropKeys(protocol.EncryptionInitial) - h.logger.Debugf("Dropping Initial keys.") - } - // drop handshake keys - if h.handshakeOpener != nil { - h.handshakeOpener = nil - h.handshakeSealer = nil - h.logger.Debugf("Dropping Handshake keys.") - h.runner.DropKeys(protocol.EncryptionHandshake) - } -} - -func (h *cryptoSetup) RunHandshake() { - // Handle errors that might occur when HandleData() is called. - handshakeComplete := make(chan struct{}) - handshakeErrChan := make(chan error, 1) - go func() { - defer close(h.handshakeDone) - if err := h.conn.Handshake(); err != nil { - handshakeErrChan <- err - return - } - close(handshakeComplete) - }() - - select { - case <-handshakeComplete: // return when the handshake is done - h.runner.OnHandshakeComplete() - case <-h.closeChan: - close(h.messageChan) - // wait until the Handshake() go routine has returned - <-h.handshakeDone - case alert := <-h.alertChan: - handshakeErr := <-handshakeErrChan - h.onError(alert, handshakeErr.Error()) - } -} - -func (h *cryptoSetup) onError(alert uint8, message string) { - - h.runner.OnError(qerr.CryptoError(alert, message)) -} - -func (h *cryptoSetup) Close() error { - h.mutex.Lock() - defer h.mutex.Unlock() - - if h.closed { - return nil - } - h.closed = true - - close(h.closeChan) - // wait until qtls.Handshake() actually returned - <-h.handshakeDone - return nil -} - -// handleMessage handles a TLS handshake message. -// It is called by the crypto streams when a new message is available. -// It returns if it is done with messages on the same encryption level. -func (h *cryptoSetup) HandleMessage(data []byte, encLevel protocol.EncryptionLevel) bool /* stream finished */ { - msgType := messageType(data[0]) - h.logger.Debugf("Received %s message (%d bytes, encryption level: %s)", msgType, len(data), encLevel) - if err := h.checkEncryptionLevel(msgType, encLevel); err != nil { - h.onError(alertUnexpectedMessage, err.Error()) - return false - } - h.messageChan <- data - if encLevel == protocol.Encryption1RTT { - h.handlePostHandshakeMessage(data) - } - switch h.perspective { - case protocol.PerspectiveClient: - return h.handleMessageForClient(msgType) - case protocol.PerspectiveServer: - return h.handleMessageForServer(msgType) - default: - panic("") - } -} - -func (h *cryptoSetup) checkEncryptionLevel(msgType messageType, encLevel protocol.EncryptionLevel) error { - var expected protocol.EncryptionLevel - switch msgType { - case typeClientHello, - typeServerHello: - expected = protocol.EncryptionInitial - case typeEncryptedExtensions, - typeCertificate, - typeCertificateRequest, - typeCertificateVerify, - typeFinished: - expected = protocol.EncryptionHandshake - case typeNewSessionTicket: - expected = protocol.Encryption1RTT - default: - return fmt.Errorf("unexpected handshake message: %d", msgType) - } - if encLevel != expected { - return fmt.Errorf("expected handshake message %s to have encryption level %s, has %s", msgType, expected, encLevel) - } - return nil -} - -func (h *cryptoSetup) handleMessageForServer(msgType messageType) bool { - switch msgType { - case typeClientHello: - select { - case <-h.writeRecord: - // If qtls sends a HelloRetryRequest, it will only write the record. - // If it accepts the ClientHello, it will first read the transport parameters. - h.logger.Debugf("Sending HelloRetryRequest") - return false - case data := <-h.paramsChan: - h.runner.OnReceivedParams(data) - case <-h.handshakeDone: - return false - } - // get the handshake read key - select { - case <-h.receivedReadKey: - case <-h.handshakeDone: - return false - } - // get the handshake write key - select { - case <-h.receivedWriteKey: - case <-h.handshakeDone: - return false - } - // get the 1-RTT write key - select { - case <-h.receivedWriteKey: - case <-h.handshakeDone: - return false - } - return true - case typeCertificate, typeCertificateVerify: - // nothing to do - return false - case typeFinished: - // get the 1-RTT read key - select { - case <-h.receivedReadKey: - case <-h.handshakeDone: - return false - } - return true - default: - // unexpected message - return false - } -} - -func (h *cryptoSetup) handleMessageForClient(msgType messageType) bool { - switch msgType { - case typeServerHello: - // get the handshake write key - select { - case <-h.writeRecord: - // If qtls writes in response to a ServerHello, this means that this ServerHello - // is a HelloRetryRequest. - // Otherwise, we'd just wait for the Certificate message. - h.logger.Debugf("ServerHello is a HelloRetryRequest") - return false - case <-h.receivedWriteKey: - case <-h.handshakeDone: - return false - } - // get the handshake read key - select { - case <-h.receivedReadKey: - case <-h.handshakeDone: - return false - } - return true - case typeEncryptedExtensions: - select { - case data := <-h.paramsChan: - h.runner.OnReceivedParams(data) - case <-h.handshakeDone: - return false - } - return false - case typeCertificateRequest, typeCertificate, typeCertificateVerify: - // nothing to do - return false - case typeFinished: - // get the 1-RTT read key - select { - case <-h.receivedReadKey: - case <-h.handshakeDone: - return false - } - // get the handshake write key - select { - case <-h.receivedWriteKey: - case <-h.handshakeDone: - return false - } - return true - default: - return false - } -} - -func (h *cryptoSetup) handlePostHandshakeMessage(data []byte) { - // make sure the handshake has already completed - <-h.handshakeDone - - done := make(chan struct{}) - defer close(done) - - // h.alertChan is an unbuffered channel. - // If an error occurs during conn.HandlePostHandshakeMessage, - // it will be sent on this channel. - // Read it from a go-routine so that HandlePostHandshakeMessage doesn't deadlock. - alertChan := make(chan uint8, 1) - go func() { - select { - case alert := <-h.alertChan: - alertChan <- alert - case <-done: - } - }() - - if err := h.conn.HandlePostHandshakeMessage(); err != nil { - h.onError(<-alertChan, err.Error()) - } -} - -// ReadHandshakeMessage is called by TLS. -// It blocks until a new handshake message is available. -func (h *cryptoSetup) ReadHandshakeMessage() ([]byte, error) { - msg, ok := <-h.messageChan - if !ok { - return nil, errors.New("error while handling the handshake message") - } - return msg, nil -} - -func (h *cryptoSetup) SetReadKey(suite *qtls.CipherSuite, trafficSecret []byte) { - h.mutex.Lock() - switch h.readEncLevel { - case protocol.EncryptionInitial: - h.readEncLevel = protocol.EncryptionHandshake - h.handshakeOpener = newLongHeaderOpener( - createAEAD(suite, trafficSecret), - createHeaderProtector(suite, trafficSecret), - ) - h.logger.Debugf("Installed Handshake Read keys") - case protocol.EncryptionHandshake: - h.readEncLevel = protocol.Encryption1RTT - h.aead.SetReadKey(suite, trafficSecret) - h.has1RTTOpener = true - h.logger.Debugf("Installed 1-RTT Read keys") - default: - panic("unexpected read encryption level") - } - h.mutex.Unlock() - h.receivedReadKey <- struct{}{} -} - -func (h *cryptoSetup) SetWriteKey(suite *qtls.CipherSuite, trafficSecret []byte) { - h.mutex.Lock() - switch h.writeEncLevel { - case protocol.EncryptionInitial: - h.writeEncLevel = protocol.EncryptionHandshake - h.handshakeSealer = newLongHeaderSealer( - createAEAD(suite, trafficSecret), - createHeaderProtector(suite, trafficSecret), - ) - h.logger.Debugf("Installed Handshake Write keys") - case protocol.EncryptionHandshake: - h.writeEncLevel = protocol.Encryption1RTT - h.aead.SetWriteKey(suite, trafficSecret) - h.has1RTTSealer = true - h.logger.Debugf("Installed 1-RTT Write keys") - default: - panic("unexpected write encryption level") - } - h.mutex.Unlock() - h.receivedWriteKey <- struct{}{} -} - -// WriteRecord is called when TLS writes data -func (h *cryptoSetup) WriteRecord(p []byte) (int, error) { - h.mutex.Lock() - defer h.mutex.Unlock() - - switch h.writeEncLevel { - case protocol.EncryptionInitial: - // assume that the first WriteRecord call contains the ClientHello - n, err := h.initialStream.Write(p) - if !h.clientHelloWritten && h.perspective == protocol.PerspectiveClient { - h.clientHelloWritten = true - close(h.clientHelloWrittenChan) - } else { - // We need additional signaling to properly detect HelloRetryRequests. - // For servers: when the ServerHello is written. - // For clients: when a reply is sent in response to a ServerHello. - h.writeRecord <- struct{}{} - } - return n, err - case protocol.EncryptionHandshake: - return h.handshakeStream.Write(p) - case protocol.Encryption1RTT: - return h.oneRTTStream.Write(p) - default: - panic(fmt.Sprintf("unexpected write encryption level: %s", h.writeEncLevel)) - } -} - -func (h *cryptoSetup) SendAlert(alert uint8) { - h.alertChan <- alert -} - -func (h *cryptoSetup) GetInitialSealer() (LongHeaderSealer, error) { - h.mutex.Lock() - defer h.mutex.Unlock() - - if h.initialSealer == nil { - return nil, ErrKeysDropped - } - return h.initialSealer, nil -} - -func (h *cryptoSetup) GetHandshakeSealer() (LongHeaderSealer, error) { - h.mutex.Lock() - defer h.mutex.Unlock() - - if h.handshakeSealer == nil { - if h.initialSealer == nil { - return nil, ErrKeysDropped - } - return nil, errors.New("CryptoSetup: no sealer with encryption level Handshake") - } - return h.handshakeSealer, nil -} - -func (h *cryptoSetup) Get1RTTSealer() (ShortHeaderSealer, error) { - h.mutex.Lock() - defer h.mutex.Unlock() - - if !h.has1RTTSealer { - return nil, errors.New("CryptoSetup: no sealer with encryption level 1-RTT") - } - return h.aead, nil -} - -func (h *cryptoSetup) GetInitialOpener() (LongHeaderOpener, error) { - h.mutex.Lock() - defer h.mutex.Unlock() - - if h.initialOpener == nil { - return nil, ErrKeysDropped - } - return h.initialOpener, nil -} - -func (h *cryptoSetup) GetHandshakeOpener() (LongHeaderOpener, error) { - h.mutex.Lock() - defer h.mutex.Unlock() - - if h.handshakeOpener == nil { - if h.initialOpener != nil { - return nil, ErrOpenerNotYetAvailable - } - // if the initial opener is also not available, the keys were already dropped - return nil, ErrKeysDropped - } - return h.handshakeOpener, nil -} - -func (h *cryptoSetup) Get1RTTOpener() (ShortHeaderOpener, error) { - h.mutex.Lock() - defer h.mutex.Unlock() - - if !h.has1RTTOpener { - return nil, ErrOpenerNotYetAvailable - } - return h.aead, nil -} - -func (h *cryptoSetup) ConnectionState() tls.ConnectionState { - cs := h.conn.ConnectionState() - // h.conn is a qtls.Conn, which returns a qtls.ConnectionState. - // qtls.ConnectionState is identical to the tls.ConnectionState. - // It contains an unexported field which is used ExportKeyingMaterial(). - // The only way to return a tls.ConnectionState is to use unsafe. - // In unsafe.go we check that the two objects are actually identical. - return *(*tls.ConnectionState)(unsafe.Pointer(&cs)) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/initial_aead.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/initial_aead.go deleted file mode 100644 index 28ea2a951a..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/initial_aead.go +++ /dev/null @@ -1,52 +0,0 @@ -package handshake - -import ( - "crypto" - "crypto/aes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/marten-seemann/qtls" -) - -var quicVersion1Salt = []byte{0xef, 0x4f, 0xb0, 0xab, 0xb4, 0x74, 0x70, 0xc4, 0x1b, 0xef, 0xcf, 0x80, 0x31, 0x33, 0x4f, 0xae, 0x48, 0x5e, 0x09, 0xa0} - -// NewInitialAEAD creates a new AEAD for Initial encryption / decryption. -func NewInitialAEAD(connID protocol.ConnectionID, pers protocol.Perspective) (LongHeaderSealer, LongHeaderOpener, error) { - clientSecret, serverSecret := computeSecrets(connID) - var mySecret, otherSecret []byte - if pers == protocol.PerspectiveClient { - mySecret = clientSecret - otherSecret = serverSecret - } else { - mySecret = serverSecret - otherSecret = clientSecret - } - myKey, myHPKey, myIV := computeInitialKeyAndIV(mySecret) - otherKey, otherHPKey, otherIV := computeInitialKeyAndIV(otherSecret) - - encrypter := qtls.AEADAESGCMTLS13(myKey, myIV) - hpEncrypter, err := aes.NewCipher(myHPKey) - if err != nil { - return nil, nil, err - } - decrypter := qtls.AEADAESGCMTLS13(otherKey, otherIV) - hpDecrypter, err := aes.NewCipher(otherHPKey) - if err != nil { - return nil, nil, err - } - return newLongHeaderSealer(encrypter, hpEncrypter), newLongHeaderOpener(decrypter, hpDecrypter), nil -} - -func computeSecrets(connID protocol.ConnectionID) (clientSecret, serverSecret []byte) { - initialSecret := qtls.HkdfExtract(crypto.SHA256, connID, quicVersion1Salt) - clientSecret = qtls.HkdfExpandLabel(crypto.SHA256, initialSecret, []byte{}, "client in", crypto.SHA256.Size()) - serverSecret = qtls.HkdfExpandLabel(crypto.SHA256, initialSecret, []byte{}, "server in", crypto.SHA256.Size()) - return -} - -func computeInitialKeyAndIV(secret []byte) (key, hpKey, iv []byte) { - key = qtls.HkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic key", 16) - hpKey = qtls.HkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic hp", 16) - iv = qtls.HkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic iv", 12) - return -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/interface.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/interface.go deleted file mode 100644 index 34cf78557e..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/interface.go +++ /dev/null @@ -1,84 +0,0 @@ -package handshake - -import ( - "crypto/tls" - "errors" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/marten-seemann/qtls" -) - -var ( - // ErrOpenerNotYetAvailable is returned when an opener is requested for an encryption level, - // but the corresponding opener has not yet been initialized - // This can happen when packets arrive out of order. - ErrOpenerNotYetAvailable = errors.New("CryptoSetup: opener at this encryption level not yet available") - // ErrKeysDropped is returned when an opener or a sealer is requested for an encryption level, - // but the corresponding keys have already been dropped. - ErrKeysDropped = errors.New("CryptoSetup: keys were already dropped") - // ErrDecryptionFailed is returned when the AEAD fails to open the packet. - ErrDecryptionFailed = errors.New("decryption failed") -) - -type headerDecryptor interface { - DecryptHeader(sample []byte, firstByte *byte, pnBytes []byte) -} - -// LongHeaderOpener opens a long header packet -type LongHeaderOpener interface { - headerDecryptor - Open(dst, src []byte, pn protocol.PacketNumber, associatedData []byte) ([]byte, error) -} - -// ShortHeaderOpener opens a short header packet -type ShortHeaderOpener interface { - headerDecryptor - Open(dst, src []byte, pn protocol.PacketNumber, kp protocol.KeyPhaseBit, associatedData []byte) ([]byte, error) -} - -// LongHeaderSealer seals a long header packet -type LongHeaderSealer interface { - Seal(dst, src []byte, packetNumber protocol.PacketNumber, associatedData []byte) []byte - EncryptHeader(sample []byte, firstByte *byte, pnBytes []byte) - Overhead() int -} - -// ShortHeaderSealer seals a short header packet -type ShortHeaderSealer interface { - LongHeaderSealer - KeyPhase() protocol.KeyPhaseBit -} - -// A tlsExtensionHandler sends and received the QUIC TLS extension. -type tlsExtensionHandler interface { - GetExtensions(msgType uint8) []qtls.Extension - ReceivedExtensions(msgType uint8, exts []qtls.Extension) - TransportParameters() <-chan []byte -} - -type handshakeRunner interface { - OnReceivedParams([]byte) - OnHandshakeComplete() - OnError(error) - DropKeys(protocol.EncryptionLevel) -} - -// CryptoSetup handles the handshake and protecting / unprotecting packets -type CryptoSetup interface { - RunHandshake() - io.Closer - ChangeConnectionID(protocol.ConnectionID) error - - HandleMessage([]byte, protocol.EncryptionLevel) bool - SetLargest1RTTAcked(protocol.PacketNumber) - ConnectionState() tls.ConnectionState - - GetInitialOpener() (LongHeaderOpener, error) - GetHandshakeOpener() (LongHeaderOpener, error) - Get1RTTOpener() (ShortHeaderOpener, error) - - GetInitialSealer() (LongHeaderSealer, error) - GetHandshakeSealer() (LongHeaderSealer, error) - Get1RTTSealer() (ShortHeaderSealer, error) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/mockgen.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/mockgen.go deleted file mode 100644 index 1c3b24b013..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/mockgen.go +++ /dev/null @@ -1,3 +0,0 @@ -package handshake - -//go:generate sh -c "../mockgen_internal.sh handshake mock_handshake_runner_test.go github.com/lucas-clemente/quic-go/internal/handshake handshakeRunner" diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/qtls.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/qtls.go deleted file mode 100644 index 52d0723fec..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/qtls.go +++ /dev/null @@ -1,142 +0,0 @@ -package handshake - -import ( - "crypto" - "crypto/cipher" - "crypto/tls" - "net" - "time" - "unsafe" - - "github.com/marten-seemann/qtls" -) - -type cipherSuite interface { - Hash() crypto.Hash - KeyLen() int - IVLen() int - AEAD(key, nonce []byte) cipher.AEAD -} - -type conn struct { - remoteAddr net.Addr -} - -func newConn(remote net.Addr) net.Conn { - return &conn{remoteAddr: remote} -} - -var _ net.Conn = &conn{} - -func (c *conn) Read([]byte) (int, error) { return 0, nil } -func (c *conn) Write([]byte) (int, error) { return 0, nil } -func (c *conn) Close() error { return nil } -func (c *conn) RemoteAddr() net.Addr { return c.remoteAddr } -func (c *conn) LocalAddr() net.Addr { return nil } -func (c *conn) SetReadDeadline(time.Time) error { return nil } -func (c *conn) SetWriteDeadline(time.Time) error { return nil } -func (c *conn) SetDeadline(time.Time) error { return nil } - -type clientSessionCache struct { - tls.ClientSessionCache -} - -var _ qtls.ClientSessionCache = &clientSessionCache{} - -func (c *clientSessionCache) Get(sessionKey string) (*qtls.ClientSessionState, bool) { - sess, ok := c.ClientSessionCache.Get(sessionKey) - if sess == nil { - return nil, ok - } - // qtls.ClientSessionState is identical to the tls.ClientSessionState. - // In order to allow users of quic-go to use a tls.Config, - // we need this workaround to use the ClientSessionCache. - // In unsafe.go we check that the two structs are actually identical. - usess := (*[unsafe.Sizeof(*sess)]byte)(unsafe.Pointer(sess))[:] - var session qtls.ClientSessionState - usession := (*[unsafe.Sizeof(session)]byte)(unsafe.Pointer(&session))[:] - copy(usession, usess) - return &session, ok -} - -func (c *clientSessionCache) Put(sessionKey string, cs *qtls.ClientSessionState) { - // qtls.ClientSessionState is identical to the tls.ClientSessionState. - // In order to allow users of quic-go to use a tls.Config, - // we need this workaround to use the ClientSessionCache. - // In unsafe.go we check that the two structs are actually identical. - usess := (*[unsafe.Sizeof(*cs)]byte)(unsafe.Pointer(cs))[:] - var session tls.ClientSessionState - usession := (*[unsafe.Sizeof(session)]byte)(unsafe.Pointer(&session))[:] - copy(usession, usess) - c.ClientSessionCache.Put(sessionKey, &session) -} - -func tlsConfigToQtlsConfig( - c *tls.Config, - recordLayer qtls.RecordLayer, - extHandler tlsExtensionHandler, -) *qtls.Config { - if c == nil { - c = &tls.Config{} - } - // Clone the config first. This executes the tls.Config.serverInit(). - // This sets the SessionTicketKey, if the user didn't supply one. - c = c.Clone() - // QUIC requires TLS 1.3 or newer - minVersion := c.MinVersion - if minVersion < qtls.VersionTLS13 { - minVersion = qtls.VersionTLS13 - } - maxVersion := c.MaxVersion - if maxVersion < qtls.VersionTLS13 { - maxVersion = qtls.VersionTLS13 - } - var getConfigForClient func(ch *tls.ClientHelloInfo) (*qtls.Config, error) - if c.GetConfigForClient != nil { - getConfigForClient = func(ch *tls.ClientHelloInfo) (*qtls.Config, error) { - tlsConf, err := c.GetConfigForClient(ch) - if err != nil { - return nil, err - } - if tlsConf == nil { - return nil, nil - } - return tlsConfigToQtlsConfig(tlsConf, recordLayer, extHandler), nil - } - } - var csc qtls.ClientSessionCache - if c.ClientSessionCache != nil { - csc = &clientSessionCache{c.ClientSessionCache} - } - return &qtls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - GetClientCertificate: c.GetClientCertificate, - GetConfigForClient: getConfigForClient, - VerifyPeerCertificate: c.VerifyPeerCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - EnforceNextProtoSelection: true, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: csc, - MinVersion: minVersion, - MaxVersion: maxVersion, - CurvePreferences: c.CurvePreferences, - DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, - // no need to copy Renegotiation, it's not supported by TLS 1.3 - KeyLogWriter: c.KeyLogWriter, - AlternativeRecordLayer: recordLayer, - GetExtensions: extHandler.GetExtensions, - ReceivedExtensions: extHandler.ReceivedExtensions, - } -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/tls_extension_handler.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/tls_extension_handler.go deleted file mode 100644 index 590aafd1ac..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/tls_extension_handler.go +++ /dev/null @@ -1,58 +0,0 @@ -package handshake - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/marten-seemann/qtls" -) - -const quicTLSExtensionType = 0xffa5 - -type extensionHandler struct { - ourParams []byte - paramsChan chan []byte - - perspective protocol.Perspective -} - -var _ tlsExtensionHandler = &extensionHandler{} - -// newExtensionHandler creates a new extension handler -func newExtensionHandler(params []byte, pers protocol.Perspective) tlsExtensionHandler { - return &extensionHandler{ - ourParams: params, - paramsChan: make(chan []byte), - perspective: pers, - } -} - -func (h *extensionHandler) GetExtensions(msgType uint8) []qtls.Extension { - if (h.perspective == protocol.PerspectiveClient && messageType(msgType) != typeClientHello) || - (h.perspective == protocol.PerspectiveServer && messageType(msgType) != typeEncryptedExtensions) { - return nil - } - return []qtls.Extension{{ - Type: quicTLSExtensionType, - Data: h.ourParams, - }} -} - -func (h *extensionHandler) ReceivedExtensions(msgType uint8, exts []qtls.Extension) { - if (h.perspective == protocol.PerspectiveClient && messageType(msgType) != typeEncryptedExtensions) || - (h.perspective == protocol.PerspectiveServer && messageType(msgType) != typeClientHello) { - return - } - - var data []byte - for _, ext := range exts { - if ext.Type == quicTLSExtensionType { - data = ext.Data - break - } - } - - h.paramsChan <- data -} - -func (h *extensionHandler) TransportParameters() <-chan []byte { - return h.paramsChan -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/token_generator.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/token_generator.go deleted file mode 100644 index 7c36e47b12..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/token_generator.go +++ /dev/null @@ -1,125 +0,0 @@ -package handshake - -import ( - "encoding/asn1" - "fmt" - "net" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -const ( - tokenPrefixIP byte = iota - tokenPrefixString -) - -// A Token is derived from the client address and can be used to verify the ownership of this address. -type Token struct { - IsRetryToken bool - RemoteAddr string - SentTime time.Time - // only set for retry tokens - OriginalDestConnectionID protocol.ConnectionID -} - -// token is the struct that is used for ASN1 serialization and deserialization -type token struct { - IsRetryToken bool - RemoteAddr []byte - Timestamp int64 - OriginalDestConnectionID []byte -} - -// A TokenGenerator generates tokens -type TokenGenerator struct { - tokenProtector tokenProtector -} - -// NewTokenGenerator initializes a new TookenGenerator -func NewTokenGenerator() (*TokenGenerator, error) { - tokenProtector, err := newTokenProtector() - if err != nil { - return nil, err - } - return &TokenGenerator{ - tokenProtector: tokenProtector, - }, nil -} - -// NewRetryToken generates a new token for a Retry for a given source address -func (g *TokenGenerator) NewRetryToken(raddr net.Addr, origConnID protocol.ConnectionID) ([]byte, error) { - data, err := asn1.Marshal(token{ - IsRetryToken: true, - RemoteAddr: encodeRemoteAddr(raddr), - OriginalDestConnectionID: origConnID, - Timestamp: time.Now().UnixNano(), - }) - if err != nil { - return nil, err - } - return g.tokenProtector.NewToken(data) -} - -// NewToken generates a new token to be sent in a NEW_TOKEN frame -func (g *TokenGenerator) NewToken(raddr net.Addr) ([]byte, error) { - data, err := asn1.Marshal(token{ - RemoteAddr: encodeRemoteAddr(raddr), - Timestamp: time.Now().UnixNano(), - }) - if err != nil { - return nil, err - } - return g.tokenProtector.NewToken(data) -} - -// DecodeToken decodes a token -func (g *TokenGenerator) DecodeToken(encrypted []byte) (*Token, error) { - // if the client didn't send any token, DecodeToken will be called with a nil-slice - if len(encrypted) == 0 { - return nil, nil - } - - data, err := g.tokenProtector.DecodeToken(encrypted) - if err != nil { - return nil, err - } - t := &token{} - rest, err := asn1.Unmarshal(data, t) - if err != nil { - return nil, err - } - if len(rest) != 0 { - return nil, fmt.Errorf("rest when unpacking token: %d", len(rest)) - } - token := &Token{ - IsRetryToken: t.IsRetryToken, - RemoteAddr: decodeRemoteAddr(t.RemoteAddr), - SentTime: time.Unix(0, t.Timestamp), - } - if len(t.OriginalDestConnectionID) > 0 { - token.OriginalDestConnectionID = protocol.ConnectionID(t.OriginalDestConnectionID) - } - return token, nil -} - -// encodeRemoteAddr encodes a remote address such that it can be saved in the token -func encodeRemoteAddr(remoteAddr net.Addr) []byte { - if udpAddr, ok := remoteAddr.(*net.UDPAddr); ok { - return append([]byte{tokenPrefixIP}, udpAddr.IP...) - } - return append([]byte{tokenPrefixString}, []byte(remoteAddr.String())...) -} - -// decodeRemoteAddr decodes the remote address saved in the token -func decodeRemoteAddr(data []byte) string { - // data will never be empty for a token that we generated. - // Check it to be on the safe side - if len(data) == 0 { - return "" - } - if data[0] == tokenPrefixIP { - return net.IP(data[1:]).String() - } - return string(data[1:]) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/token_protector.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/token_protector.go deleted file mode 100644 index 238b984d44..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/token_protector.go +++ /dev/null @@ -1,86 +0,0 @@ -package handshake - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "crypto/sha256" - "fmt" - "io" - - "golang.org/x/crypto/hkdf" -) - -// TokenProtector is used to create and verify a token -type tokenProtector interface { - // NewToken creates a new token - NewToken([]byte) ([]byte, error) - // DecodeToken decodes a token - DecodeToken([]byte) ([]byte, error) -} - -const ( - tokenSecretSize = 32 - tokenNonceSize = 32 -) - -// tokenProtector is used to create and verify a token -type tokenProtectorImpl struct { - secret []byte -} - -// newTokenProtector creates a source for source address tokens -func newTokenProtector() (tokenProtector, error) { - secret := make([]byte, tokenSecretSize) - if _, err := rand.Read(secret); err != nil { - return nil, err - } - return &tokenProtectorImpl{secret: secret}, nil -} - -// NewToken encodes data into a new token. -func (s *tokenProtectorImpl) NewToken(data []byte) ([]byte, error) { - nonce := make([]byte, tokenNonceSize) - if _, err := rand.Read(nonce); err != nil { - return nil, err - } - aead, aeadNonce, err := s.createAEAD(nonce) - if err != nil { - return nil, err - } - return append(nonce, aead.Seal(nil, aeadNonce, data, nil)...), nil -} - -// DecodeToken decodes a token. -func (s *tokenProtectorImpl) DecodeToken(p []byte) ([]byte, error) { - if len(p) < tokenNonceSize { - return nil, fmt.Errorf("Token too short: %d", len(p)) - } - nonce := p[:tokenNonceSize] - aead, aeadNonce, err := s.createAEAD(nonce) - if err != nil { - return nil, err - } - return aead.Open(nil, aeadNonce, p[tokenNonceSize:], nil) -} - -func (s *tokenProtectorImpl) createAEAD(nonce []byte) (cipher.AEAD, []byte, error) { - h := hkdf.New(sha256.New, s.secret, nonce, []byte("quic-go token source")) - key := make([]byte, 32) // use a 32 byte key, in order to select AES-256 - if _, err := io.ReadFull(h, key); err != nil { - return nil, nil, err - } - aeadNonce := make([]byte, 12) - if _, err := io.ReadFull(h, aeadNonce); err != nil { - return nil, nil, err - } - c, err := aes.NewCipher(key) - if err != nil { - return nil, nil, err - } - aead, err := cipher.NewGCM(c) - if err != nil { - return nil, nil, err - } - return aead, aeadNonce, nil -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/transport_parameters.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/transport_parameters.go deleted file mode 100644 index 724c3586eb..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/transport_parameters.go +++ /dev/null @@ -1,271 +0,0 @@ -package handshake - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "sort" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -type transportParameterID uint16 - -const ( - originalConnectionIDParameterID transportParameterID = 0x0 - idleTimeoutParameterID transportParameterID = 0x1 - statelessResetTokenParameterID transportParameterID = 0x2 - maxPacketSizeParameterID transportParameterID = 0x3 - initialMaxDataParameterID transportParameterID = 0x4 - initialMaxStreamDataBidiLocalParameterID transportParameterID = 0x5 - initialMaxStreamDataBidiRemoteParameterID transportParameterID = 0x6 - initialMaxStreamDataUniParameterID transportParameterID = 0x7 - initialMaxStreamsBidiParameterID transportParameterID = 0x8 - initialMaxStreamsUniParameterID transportParameterID = 0x9 - ackDelayExponentParameterID transportParameterID = 0xa - maxAckDelayParameterID transportParameterID = 0xb - disableMigrationParameterID transportParameterID = 0xc -) - -// TransportParameters are parameters sent to the peer during the handshake -type TransportParameters struct { - InitialMaxStreamDataBidiLocal protocol.ByteCount - InitialMaxStreamDataBidiRemote protocol.ByteCount - InitialMaxStreamDataUni protocol.ByteCount - InitialMaxData protocol.ByteCount - - MaxAckDelay time.Duration - AckDelayExponent uint8 - - MaxPacketSize protocol.ByteCount - - MaxUniStreamNum protocol.StreamNum - MaxBidiStreamNum protocol.StreamNum - - IdleTimeout time.Duration - DisableMigration bool - - StatelessResetToken *[16]byte - OriginalConnectionID protocol.ConnectionID -} - -// Unmarshal the transport parameters -func (p *TransportParameters) Unmarshal(data []byte, sentBy protocol.Perspective) error { - if len(data) < 2 { - return errors.New("transport parameter data too short") - } - length := binary.BigEndian.Uint16(data[:2]) - if len(data)-2 < int(length) { - return fmt.Errorf("expected transport parameters to be %d bytes long, have %d", length, len(data)-2) - } - - // needed to check that every parameter is only sent at most once - var parameterIDs []transportParameterID - - var readAckDelayExponent bool - var readMaxAckDelay bool - - r := bytes.NewReader(data[2:]) - for r.Len() >= 4 { - paramIDInt, _ := utils.BigEndian.ReadUint16(r) - paramID := transportParameterID(paramIDInt) - paramLen, _ := utils.BigEndian.ReadUint16(r) - parameterIDs = append(parameterIDs, paramID) - switch paramID { - case ackDelayExponentParameterID: - readAckDelayExponent = true - if err := p.readNumericTransportParameter(r, paramID, int(paramLen)); err != nil { - return err - } - case maxAckDelayParameterID: - readMaxAckDelay = true - if err := p.readNumericTransportParameter(r, paramID, int(paramLen)); err != nil { - return err - } - case initialMaxStreamDataBidiLocalParameterID, - initialMaxStreamDataBidiRemoteParameterID, - initialMaxStreamDataUniParameterID, - initialMaxDataParameterID, - initialMaxStreamsBidiParameterID, - initialMaxStreamsUniParameterID, - idleTimeoutParameterID, - maxPacketSizeParameterID: - if err := p.readNumericTransportParameter(r, paramID, int(paramLen)); err != nil { - return err - } - default: - if r.Len() < int(paramLen) { - return fmt.Errorf("remaining length (%d) smaller than parameter length (%d)", r.Len(), paramLen) - } - switch paramID { - case disableMigrationParameterID: - if paramLen != 0 { - return fmt.Errorf("wrong length for disable_migration: %d (expected empty)", paramLen) - } - p.DisableMigration = true - case statelessResetTokenParameterID: - if sentBy == protocol.PerspectiveClient { - return errors.New("client sent a stateless_reset_token") - } - if paramLen != 16 { - return fmt.Errorf("wrong length for stateless_reset_token: %d (expected 16)", paramLen) - } - var token [16]byte - r.Read(token[:]) - p.StatelessResetToken = &token - case originalConnectionIDParameterID: - if sentBy == protocol.PerspectiveClient { - return errors.New("client sent an original_connection_id") - } - p.OriginalConnectionID, _ = protocol.ReadConnectionID(r, int(paramLen)) - default: - r.Seek(int64(paramLen), io.SeekCurrent) - } - } - } - - if !readAckDelayExponent { - p.AckDelayExponent = protocol.DefaultAckDelayExponent - } - if !readMaxAckDelay { - p.MaxAckDelay = protocol.DefaultMaxAckDelay - } - - // check that every transport parameter was sent at most once - sort.Slice(parameterIDs, func(i, j int) bool { return parameterIDs[i] < parameterIDs[j] }) - for i := 0; i < len(parameterIDs)-1; i++ { - if parameterIDs[i] == parameterIDs[i+1] { - return fmt.Errorf("received duplicate transport parameter %#x", parameterIDs[i]) - } - } - - if r.Len() != 0 { - return fmt.Errorf("should have read all data. Still have %d bytes", r.Len()) - } - return nil -} - -func (p *TransportParameters) readNumericTransportParameter( - r *bytes.Reader, - paramID transportParameterID, - expectedLen int, -) error { - remainingLen := r.Len() - val, err := utils.ReadVarInt(r) - if err != nil { - return fmt.Errorf("error while reading transport parameter %d: %s", paramID, err) - } - if remainingLen-r.Len() != expectedLen { - return fmt.Errorf("inconsistent transport parameter length for %d", paramID) - } - switch paramID { - case initialMaxStreamDataBidiLocalParameterID: - p.InitialMaxStreamDataBidiLocal = protocol.ByteCount(val) - case initialMaxStreamDataBidiRemoteParameterID: - p.InitialMaxStreamDataBidiRemote = protocol.ByteCount(val) - case initialMaxStreamDataUniParameterID: - p.InitialMaxStreamDataUni = protocol.ByteCount(val) - case initialMaxDataParameterID: - p.InitialMaxData = protocol.ByteCount(val) - case initialMaxStreamsBidiParameterID: - p.MaxBidiStreamNum = protocol.StreamNum(val) - case initialMaxStreamsUniParameterID: - p.MaxUniStreamNum = protocol.StreamNum(val) - case idleTimeoutParameterID: - p.IdleTimeout = utils.MaxDuration(protocol.MinRemoteIdleTimeout, time.Duration(val)*time.Millisecond) - case maxPacketSizeParameterID: - if val < 1200 { - return fmt.Errorf("invalid value for max_packet_size: %d (minimum 1200)", val) - } - p.MaxPacketSize = protocol.ByteCount(val) - case ackDelayExponentParameterID: - if val > protocol.MaxAckDelayExponent { - return fmt.Errorf("invalid value for ack_delay_exponent: %d (maximum %d)", val, protocol.MaxAckDelayExponent) - } - p.AckDelayExponent = uint8(val) - case maxAckDelayParameterID: - maxAckDelay := time.Duration(val) * time.Millisecond - if maxAckDelay >= protocol.MaxMaxAckDelay { - return fmt.Errorf("invalid value for max_ack_delay: %dms (maximum %dms)", maxAckDelay/time.Millisecond, (protocol.MaxMaxAckDelay-time.Millisecond)/time.Millisecond) - } - p.MaxAckDelay = maxAckDelay - default: - return fmt.Errorf("TransportParameter BUG: transport parameter %d not found", paramID) - } - return nil -} - -// Marshal the transport parameters -func (p *TransportParameters) Marshal() []byte { - b := &bytes.Buffer{} - b.Write([]byte{0, 0}) // length. Will be replaced later - - // initial_max_stream_data_bidi_local - p.marshalVarintParam(b, initialMaxStreamDataBidiLocalParameterID, uint64(p.InitialMaxStreamDataBidiLocal)) - // initial_max_stream_data_bidi_remote - p.marshalVarintParam(b, initialMaxStreamDataBidiRemoteParameterID, uint64(p.InitialMaxStreamDataBidiRemote)) - // initial_max_stream_data_uni - p.marshalVarintParam(b, initialMaxStreamDataUniParameterID, uint64(p.InitialMaxStreamDataUni)) - // initial_max_data - p.marshalVarintParam(b, initialMaxDataParameterID, uint64(p.InitialMaxData)) - // initial_max_bidi_streams - p.marshalVarintParam(b, initialMaxStreamsBidiParameterID, uint64(p.MaxBidiStreamNum)) - // initial_max_uni_streams - p.marshalVarintParam(b, initialMaxStreamsUniParameterID, uint64(p.MaxUniStreamNum)) - // idle_timeout - p.marshalVarintParam(b, idleTimeoutParameterID, uint64(p.IdleTimeout/time.Millisecond)) - // max_packet_size - p.marshalVarintParam(b, maxPacketSizeParameterID, uint64(protocol.MaxReceivePacketSize)) - // max_ack_delay - // Only send it if is different from the default value. - if p.MaxAckDelay != protocol.DefaultMaxAckDelay { - p.marshalVarintParam(b, maxAckDelayParameterID, uint64(p.MaxAckDelay/time.Millisecond)) - } - // ack_delay_exponent - // Only send it if is different from the default value. - if p.AckDelayExponent != protocol.DefaultAckDelayExponent { - p.marshalVarintParam(b, ackDelayExponentParameterID, uint64(p.AckDelayExponent)) - } - // disable_migration - if p.DisableMigration { - utils.BigEndian.WriteUint16(b, uint16(disableMigrationParameterID)) - utils.BigEndian.WriteUint16(b, 0) - } - if p.StatelessResetToken != nil { - utils.BigEndian.WriteUint16(b, uint16(statelessResetTokenParameterID)) - utils.BigEndian.WriteUint16(b, 16) - b.Write(p.StatelessResetToken[:]) - } - // original_connection_id - if p.OriginalConnectionID.Len() > 0 { - utils.BigEndian.WriteUint16(b, uint16(originalConnectionIDParameterID)) - utils.BigEndian.WriteUint16(b, uint16(p.OriginalConnectionID.Len())) - b.Write(p.OriginalConnectionID.Bytes()) - } - - data := b.Bytes() - binary.BigEndian.PutUint16(data[:2], uint16(b.Len()-2)) - return data -} - -func (p *TransportParameters) marshalVarintParam(b *bytes.Buffer, id transportParameterID, val uint64) { - utils.BigEndian.WriteUint16(b, uint16(id)) - utils.BigEndian.WriteUint16(b, uint16(utils.VarIntLen(val))) - utils.WriteVarInt(b, val) -} - -// String returns a string representation, intended for logging. -func (p *TransportParameters) String() string { - logString := "&handshake.TransportParameters{OriginalConnectionID: %s, InitialMaxStreamDataBidiLocal: %#x, InitialMaxStreamDataBidiRemote: %#x, InitialMaxStreamDataUni: %#x, InitialMaxData: %#x, MaxBidiStreamNum: %d, MaxUniStreamNum: %d, IdleTimeout: %s, AckDelayExponent: %d, MaxAckDelay: %s" - logParams := []interface{}{p.OriginalConnectionID, p.InitialMaxStreamDataBidiLocal, p.InitialMaxStreamDataBidiRemote, p.InitialMaxStreamDataUni, p.InitialMaxData, p.MaxBidiStreamNum, p.MaxUniStreamNum, p.IdleTimeout, p.AckDelayExponent, p.MaxAckDelay} - if p.StatelessResetToken != nil { // the client never sends a stateless reset token - logString += ", StatelessResetToken: %#x" - logParams = append(logParams, *p.StatelessResetToken) - } - logString += "}" - return fmt.Sprintf(logString, logParams...) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/unsafe.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/unsafe.go deleted file mode 100644 index fb051aebf2..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/unsafe.go +++ /dev/null @@ -1,38 +0,0 @@ -package handshake - -// This package uses unsafe to convert between: -// * qtls.ConnectionState and tls.ConnectionState -// * qtls.ClientSessionState and tls.ClientSessionState -// We check in init() that this conversion actually is safe. - -import ( - "crypto/tls" - "reflect" - - "github.com/marten-seemann/qtls" -) - -func init() { - if !structsEqual(&tls.ConnectionState{}, &qtls.ConnectionState{}) { - panic("qtls.ConnectionState not compatible with tls.ConnectionState") - } - if !structsEqual(&tls.ClientSessionState{}, &qtls.ClientSessionState{}) { - panic("qtls.ClientSessionState not compatible with tls.ClientSessionState") - } -} - -func structsEqual(a, b interface{}) bool { - sa := reflect.ValueOf(a).Elem() - sb := reflect.ValueOf(b).Elem() - if sa.NumField() != sb.NumField() { - return false - } - for i := 0; i < sa.NumField(); i++ { - fa := sa.Type().Field(i) - fb := sb.Type().Field(i) - if !reflect.DeepEqual(fa.Index, fb.Index) || fa.Name != fb.Name || fa.Anonymous != fb.Anonymous || fa.Offset != fb.Offset || !reflect.DeepEqual(fa.Type, fb.Type) { - return false - } - } - return true -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/updatable_aead.go b/vendor/github.com/lucas-clemente/quic-go/internal/handshake/updatable_aead.go deleted file mode 100644 index 65ea365adc..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/handshake/updatable_aead.go +++ /dev/null @@ -1,264 +0,0 @@ -package handshake - -import ( - "crypto" - "crypto/cipher" - "encoding/binary" - "fmt" - "os" - "strconv" - "time" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/qerr" - "github.com/lucas-clemente/quic-go/internal/utils" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/marten-seemann/qtls" -) - -// By setting this environment variable, the key update interval can be adjusted. -// This is not needed in production, but useful for integration and interop testing. -// Note that no mattter what value is set, a key update is only initiated once it is -// permitted (i.e. once an ACK for a packet sent at the current key phase has been received). -const keyUpdateEnv = "QUIC_GO_KEY_UPDATE_INTERVAL" - -var keyUpdateInterval uint64 - -func init() { - setKeyUpdateInterval() -} - -func setKeyUpdateInterval() { - env := os.Getenv(keyUpdateEnv) - if env == "" { - keyUpdateInterval = protocol.KeyUpdateInterval - return - } - interval, err := strconv.ParseUint(env, 10, 64) - if err != nil { - panic(fmt.Sprintf("Cannot parse %s: %s", keyUpdateEnv, err)) - } - keyUpdateInterval = interval -} - -type updatableAEAD struct { - suite cipherSuite - - keyPhase protocol.KeyPhase - largestAcked protocol.PacketNumber - keyUpdateInterval uint64 - - // Time when the keys should be dropped. Keys are dropped on the next call to Open(). - prevRcvAEADExpiry time.Time - prevRcvAEAD cipher.AEAD - - firstRcvdWithCurrentKey protocol.PacketNumber - firstSentWithCurrentKey protocol.PacketNumber - numRcvdWithCurrentKey uint64 - numSentWithCurrentKey uint64 - rcvAEAD cipher.AEAD - sendAEAD cipher.AEAD - - nextRcvAEAD cipher.AEAD - nextSendAEAD cipher.AEAD - nextRcvTrafficSecret []byte - nextSendTrafficSecret []byte - - hpDecrypter cipher.Block - hpEncrypter cipher.Block - - rttStats *congestion.RTTStats - - logger utils.Logger - - // use a single slice to avoid allocations - nonceBuf []byte - hpMask []byte -} - -var _ ShortHeaderOpener = &updatableAEAD{} -var _ ShortHeaderSealer = &updatableAEAD{} - -func newUpdatableAEAD(rttStats *congestion.RTTStats, logger utils.Logger) *updatableAEAD { - return &updatableAEAD{ - largestAcked: protocol.InvalidPacketNumber, - firstRcvdWithCurrentKey: protocol.InvalidPacketNumber, - firstSentWithCurrentKey: protocol.InvalidPacketNumber, - keyUpdateInterval: keyUpdateInterval, - rttStats: rttStats, - logger: logger, - } -} - -func (a *updatableAEAD) rollKeys() { - a.keyPhase++ - a.firstRcvdWithCurrentKey = protocol.InvalidPacketNumber - a.firstSentWithCurrentKey = protocol.InvalidPacketNumber - a.numRcvdWithCurrentKey = 0 - a.numSentWithCurrentKey = 0 - a.prevRcvAEAD = a.rcvAEAD - a.prevRcvAEADExpiry = time.Now().Add(3 * a.rttStats.PTO()) - a.rcvAEAD = a.nextRcvAEAD - a.sendAEAD = a.nextSendAEAD - - a.nextRcvTrafficSecret = a.getNextTrafficSecret(a.suite.Hash(), a.nextRcvTrafficSecret) - a.nextSendTrafficSecret = a.getNextTrafficSecret(a.suite.Hash(), a.nextSendTrafficSecret) - a.nextRcvAEAD = createAEAD(a.suite, a.nextRcvTrafficSecret) - a.nextSendAEAD = createAEAD(a.suite, a.nextSendTrafficSecret) -} - -func (a *updatableAEAD) getNextTrafficSecret(hash crypto.Hash, ts []byte) []byte { - return qtls.HkdfExpandLabel(hash, ts, []byte{}, "traffic upd", hash.Size()) -} - -// For the client, this function is called before SetWriteKey. -// For the server, this function is called after SetWriteKey. -func (a *updatableAEAD) SetReadKey(suite cipherSuite, trafficSecret []byte) { - a.rcvAEAD = createAEAD(suite, trafficSecret) - a.hpDecrypter = createHeaderProtector(suite, trafficSecret) - if a.suite == nil { - a.nonceBuf = make([]byte, a.rcvAEAD.NonceSize()) - a.hpMask = make([]byte, a.hpDecrypter.BlockSize()) - a.suite = suite - } - - a.nextRcvTrafficSecret = a.getNextTrafficSecret(suite.Hash(), trafficSecret) - a.nextRcvAEAD = createAEAD(suite, a.nextRcvTrafficSecret) -} - -// For the client, this function is called after SetReadKey. -// For the server, this function is called before SetWriteKey. -func (a *updatableAEAD) SetWriteKey(suite cipherSuite, trafficSecret []byte) { - a.sendAEAD = createAEAD(suite, trafficSecret) - a.hpEncrypter = createHeaderProtector(suite, trafficSecret) - if a.suite == nil { - a.nonceBuf = make([]byte, a.sendAEAD.NonceSize()) - a.hpMask = make([]byte, a.hpEncrypter.BlockSize()) - a.suite = suite - } - - a.nextSendTrafficSecret = a.getNextTrafficSecret(suite.Hash(), trafficSecret) - a.nextSendAEAD = createAEAD(suite, a.nextSendTrafficSecret) -} - -func (a *updatableAEAD) Open(dst, src []byte, pn protocol.PacketNumber, kp protocol.KeyPhaseBit, ad []byte) ([]byte, error) { - if a.prevRcvAEAD != nil && time.Now().After(a.prevRcvAEADExpiry) { - a.prevRcvAEAD = nil - a.prevRcvAEADExpiry = time.Time{} - } - binary.BigEndian.PutUint64(a.nonceBuf[len(a.nonceBuf)-8:], uint64(pn)) - if kp != a.keyPhase.Bit() { - if a.firstRcvdWithCurrentKey == protocol.InvalidPacketNumber || pn < a.firstRcvdWithCurrentKey { - if a.keyPhase == 0 { - // This can only occur when the first packet received has key phase 1. - // This is an error, since the key phase starts at 0, - // and peers are only allowed to update keys after the handshake is confirmed. - return nil, qerr.Error(qerr.ProtocolViolation, "wrong initial keyphase") - } - if a.prevRcvAEAD == nil { - return nil, ErrKeysDropped - } - // we updated the key, but the peer hasn't updated yet - dec, err := a.prevRcvAEAD.Open(dst, a.nonceBuf, src, ad) - if err != nil { - err = ErrDecryptionFailed - } - return dec, err - } - // try opening the packet with the next key phase - dec, err := a.nextRcvAEAD.Open(dst, a.nonceBuf, src, ad) - if err != nil { - return nil, ErrDecryptionFailed - } - // Opening succeeded. Check if the peer was allowed to update. - if a.firstSentWithCurrentKey == protocol.InvalidPacketNumber { - return nil, qerr.Error(qerr.ProtocolViolation, "keys updated too quickly") - } - a.rollKeys() - a.logger.Debugf("Peer updated keys to %s", a.keyPhase) - a.firstRcvdWithCurrentKey = pn - return dec, err - } - // The AEAD we're using here will be the qtls.aeadAESGCM13. - // It uses the nonce provided here and XOR it with the IV. - dec, err := a.rcvAEAD.Open(dst, a.nonceBuf, src, ad) - if err != nil { - err = ErrDecryptionFailed - } else { - a.numRcvdWithCurrentKey++ - if a.firstRcvdWithCurrentKey == protocol.InvalidPacketNumber { - a.firstRcvdWithCurrentKey = pn - } - } - return dec, err -} - -func (a *updatableAEAD) Seal(dst, src []byte, pn protocol.PacketNumber, ad []byte) []byte { - if a.firstSentWithCurrentKey == protocol.InvalidPacketNumber { - a.firstSentWithCurrentKey = pn - } - a.numSentWithCurrentKey++ - binary.BigEndian.PutUint64(a.nonceBuf[len(a.nonceBuf)-8:], uint64(pn)) - // The AEAD we're using here will be the qtls.aeadAESGCM13. - // It uses the nonce provided here and XOR it with the IV. - return a.sendAEAD.Seal(dst, a.nonceBuf, src, ad) -} - -func (a *updatableAEAD) SetLargestAcked(pn protocol.PacketNumber) { - a.largestAcked = pn -} - -func (a *updatableAEAD) updateAllowed() bool { - return a.firstSentWithCurrentKey != protocol.InvalidPacketNumber && - a.largestAcked != protocol.InvalidPacketNumber && - a.largestAcked >= a.firstSentWithCurrentKey -} - -func (a *updatableAEAD) shouldInitiateKeyUpdate() bool { - if !a.updateAllowed() { - return false - } - if a.numRcvdWithCurrentKey >= a.keyUpdateInterval { - a.logger.Debugf("Received %d packets with current key phase. Initiating key update to the next key phase: %s", a.numRcvdWithCurrentKey, a.keyPhase+1) - return true - } - if a.numSentWithCurrentKey >= a.keyUpdateInterval { - a.logger.Debugf("Sent %d packets with current key phase. Initiating key update to the next key phase: %s", a.numSentWithCurrentKey, a.keyPhase+1) - return true - } - return false -} - -func (a *updatableAEAD) KeyPhase() protocol.KeyPhaseBit { - if a.shouldInitiateKeyUpdate() { - a.rollKeys() - } - return a.keyPhase.Bit() -} - -func (a *updatableAEAD) Overhead() int { - return a.sendAEAD.Overhead() -} - -func (a *updatableAEAD) EncryptHeader(sample []byte, firstByte *byte, pnBytes []byte) { - if len(sample) != a.hpEncrypter.BlockSize() { - panic("invalid sample size") - } - a.hpEncrypter.Encrypt(a.hpMask, sample) - *firstByte ^= a.hpMask[0] & 0x1f - for i := range pnBytes { - pnBytes[i] ^= a.hpMask[i+1] - } -} - -func (a *updatableAEAD) DecryptHeader(sample []byte, firstByte *byte, pnBytes []byte) { - if len(sample) != a.hpDecrypter.BlockSize() { - panic("invalid sample size") - } - a.hpDecrypter.Encrypt(a.hpMask, sample) - *firstByte ^= a.hpMask[0] & 0x1f - for i := range pnBytes { - pnBytes[i] ^= a.hpMask[i+1] - } -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/connection_id.go b/vendor/github.com/lucas-clemente/quic-go/internal/protocol/connection_id.go deleted file mode 100644 index f99461b2cf..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/connection_id.go +++ /dev/null @@ -1,69 +0,0 @@ -package protocol - -import ( - "bytes" - "crypto/rand" - "fmt" - "io" -) - -// A ConnectionID in QUIC -type ConnectionID []byte - -const maxConnectionIDLen = 18 - -// GenerateConnectionID generates a connection ID using cryptographic random -func GenerateConnectionID(len int) (ConnectionID, error) { - b := make([]byte, len) - if _, err := rand.Read(b); err != nil { - return nil, err - } - return ConnectionID(b), nil -} - -// GenerateConnectionIDForInitial generates a connection ID for the Initial packet. -// It uses a length randomly chosen between 8 and 18 bytes. -func GenerateConnectionIDForInitial() (ConnectionID, error) { - r := make([]byte, 1) - if _, err := rand.Read(r); err != nil { - return nil, err - } - len := MinConnectionIDLenInitial + int(r[0])%(maxConnectionIDLen-MinConnectionIDLenInitial+1) - return GenerateConnectionID(len) -} - -// ReadConnectionID reads a connection ID of length len from the given io.Reader. -// It returns io.EOF if there are not enough bytes to read. -func ReadConnectionID(r io.Reader, len int) (ConnectionID, error) { - if len == 0 { - return nil, nil - } - c := make(ConnectionID, len) - _, err := io.ReadFull(r, c) - if err == io.ErrUnexpectedEOF { - return nil, io.EOF - } - return c, err -} - -// Equal says if two connection IDs are equal -func (c ConnectionID) Equal(other ConnectionID) bool { - return bytes.Equal(c, other) -} - -// Len returns the length of the connection ID in bytes -func (c ConnectionID) Len() int { - return len(c) -} - -// Bytes returns the byte representation -func (c ConnectionID) Bytes() []byte { - return []byte(c) -} - -func (c ConnectionID) String() string { - if c.Len() == 0 { - return "(empty)" - } - return fmt.Sprintf("%#x", c.Bytes()) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/encryption_level.go b/vendor/github.com/lucas-clemente/quic-go/internal/protocol/encryption_level.go deleted file mode 100644 index 4b059b3a89..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/encryption_level.go +++ /dev/null @@ -1,28 +0,0 @@ -package protocol - -// EncryptionLevel is the encryption level -// Default value is Unencrypted -type EncryptionLevel int - -const ( - // EncryptionUnspecified is a not specified encryption level - EncryptionUnspecified EncryptionLevel = iota - // EncryptionInitial is the Initial encryption level - EncryptionInitial - // EncryptionHandshake is the Handshake encryption level - EncryptionHandshake - // Encryption1RTT is the 1-RTT encryption level - Encryption1RTT -) - -func (e EncryptionLevel) String() string { - switch e { - case EncryptionInitial: - return "Initial" - case EncryptionHandshake: - return "Handshake" - case Encryption1RTT: - return "1-RTT" - } - return "unknown" -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/key_phase.go b/vendor/github.com/lucas-clemente/quic-go/internal/protocol/key_phase.go deleted file mode 100644 index 2ebc3f926d..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/key_phase.go +++ /dev/null @@ -1,25 +0,0 @@ -package protocol - -// KeyPhase is the key phase -type KeyPhase uint64 - -func (p KeyPhase) Bit() KeyPhaseBit { - return p%2 == 1 -} - -// KeyPhaseBit is the key phase bit -type KeyPhaseBit bool - -const ( - // KeyPhaseZero is key phase 0 - KeyPhaseZero KeyPhaseBit = false - // KeyPhaseOne is key phase 1 - KeyPhaseOne KeyPhaseBit = true -) - -func (p KeyPhaseBit) String() string { - if p == KeyPhaseZero { - return "0" - } - return "1" -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/packet_number.go b/vendor/github.com/lucas-clemente/quic-go/internal/protocol/packet_number.go deleted file mode 100644 index 0fa62ff3d5..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/packet_number.go +++ /dev/null @@ -1,81 +0,0 @@ -package protocol - -// A PacketNumber in QUIC -type PacketNumber int64 - -// InvalidPacketNumber is a packet number that is never sent. -// In QUIC, 0 is a valid packet number. -const InvalidPacketNumber = -1 - -// PacketNumberLen is the length of the packet number in bytes -type PacketNumberLen uint8 - -const ( - // PacketNumberLenInvalid is the default value and not a valid length for a packet number - PacketNumberLenInvalid PacketNumberLen = 0 - // PacketNumberLen1 is a packet number length of 1 byte - PacketNumberLen1 PacketNumberLen = 1 - // PacketNumberLen2 is a packet number length of 2 bytes - PacketNumberLen2 PacketNumberLen = 2 - // PacketNumberLen3 is a packet number length of 3 bytes - PacketNumberLen3 PacketNumberLen = 3 - // PacketNumberLen4 is a packet number length of 4 bytes - PacketNumberLen4 PacketNumberLen = 4 -) - -// DecodePacketNumber calculates the packet number based on the received packet number, its length and the last seen packet number -func DecodePacketNumber( - packetNumberLength PacketNumberLen, - lastPacketNumber PacketNumber, - wirePacketNumber PacketNumber, -) PacketNumber { - var epochDelta PacketNumber - switch packetNumberLength { - case PacketNumberLen1: - epochDelta = PacketNumber(1) << 8 - case PacketNumberLen2: - epochDelta = PacketNumber(1) << 16 - case PacketNumberLen3: - epochDelta = PacketNumber(1) << 24 - case PacketNumberLen4: - epochDelta = PacketNumber(1) << 32 - } - epoch := lastPacketNumber & ^(epochDelta - 1) - var prevEpochBegin PacketNumber - if epoch > epochDelta { - prevEpochBegin = epoch - epochDelta - } - nextEpochBegin := epoch + epochDelta - return closestTo( - lastPacketNumber+1, - epoch+wirePacketNumber, - closestTo(lastPacketNumber+1, prevEpochBegin+wirePacketNumber, nextEpochBegin+wirePacketNumber), - ) -} - -func closestTo(target, a, b PacketNumber) PacketNumber { - if delta(target, a) < delta(target, b) { - return a - } - return b -} - -func delta(a, b PacketNumber) PacketNumber { - if a < b { - return b - a - } - return a - b -} - -// GetPacketNumberLengthForHeader gets the length of the packet number for the public header -// it never chooses a PacketNumberLen of 1 byte, since this is too short under certain circumstances -func GetPacketNumberLengthForHeader(packetNumber, leastUnacked PacketNumber) PacketNumberLen { - diff := uint64(packetNumber - leastUnacked) - if diff < (1 << (16 - 1)) { - return PacketNumberLen2 - } - if diff < (1 << (24 - 1)) { - return PacketNumberLen3 - } - return PacketNumberLen4 -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/params.go b/vendor/github.com/lucas-clemente/quic-go/internal/protocol/params.go deleted file mode 100644 index 8a6d3444f6..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/params.go +++ /dev/null @@ -1,144 +0,0 @@ -package protocol - -import "time" - -// MaxPacketSizeIPv4 is the maximum packet size that we use for sending IPv4 packets. -const MaxPacketSizeIPv4 = 1252 - -// MaxPacketSizeIPv6 is the maximum packet size that we use for sending IPv6 packets. -const MaxPacketSizeIPv6 = 1232 - -const defaultMaxCongestionWindowPackets = 1000 - -// DefaultMaxCongestionWindow is the default for the max congestion window -const DefaultMaxCongestionWindow ByteCount = defaultMaxCongestionWindowPackets * DefaultTCPMSS - -// InitialCongestionWindow is the initial congestion window in QUIC packets -const InitialCongestionWindow ByteCount = 32 * DefaultTCPMSS - -// MaxUndecryptablePackets limits the number of undecryptable packets that are queued in the session. -const MaxUndecryptablePackets = 10 - -// ConnectionFlowControlMultiplier determines how much larger the connection flow control windows needs to be relative to any stream's flow control window -// This is the value that Chromium is using -const ConnectionFlowControlMultiplier = 1.5 - -// InitialMaxStreamData is the stream-level flow control window for receiving data -const InitialMaxStreamData = (1 << 10) * 512 // 512 kb - -// InitialMaxData is the connection-level flow control window for receiving data -const InitialMaxData = ConnectionFlowControlMultiplier * InitialMaxStreamData - -// DefaultMaxReceiveStreamFlowControlWindow is the default maximum stream-level flow control window for receiving data, for the server -const DefaultMaxReceiveStreamFlowControlWindow = 6 * (1 << 20) // 6 MB - -// DefaultMaxReceiveConnectionFlowControlWindow is the default connection-level flow control window for receiving data, for the server -const DefaultMaxReceiveConnectionFlowControlWindow = 15 * (1 << 20) // 12 MB - -// WindowUpdateThreshold is the fraction of the receive window that has to be consumed before an higher offset is advertised to the client -const WindowUpdateThreshold = 0.25 - -// DefaultMaxIncomingStreams is the maximum number of streams that a peer may open -const DefaultMaxIncomingStreams = 100 - -// DefaultMaxIncomingUniStreams is the maximum number of unidirectional streams that a peer may open -const DefaultMaxIncomingUniStreams = 100 - -// MaxSessionUnprocessedPackets is the max number of packets stored in each session that are not yet processed. -const MaxSessionUnprocessedPackets = defaultMaxCongestionWindowPackets - -// SkipPacketAveragePeriodLength is the average period length in which one packet number is skipped to prevent an Optimistic ACK attack -const SkipPacketAveragePeriodLength PacketNumber = 500 - -// MaxTrackedSkippedPackets is the maximum number of skipped packet numbers the SentPacketHandler keep track of for Optimistic ACK attack mitigation -const MaxTrackedSkippedPackets = 10 - -// MaxAcceptQueueSize is the maximum number of sessions that the server queues for accepting. -// If the queue is full, new connection attempts will be rejected. -const MaxAcceptQueueSize = 32 - -// TokenValidity is the duration that a (non-retry) token is considered valid -const TokenValidity = 24 * time.Hour - -// RetryTokenValidity is the duration that a retry token is considered valid -const RetryTokenValidity = 10 * time.Second - -// MaxOutstandingSentPackets is maximum number of packets saved for retransmission. -// When reached, it imposes a soft limit on sending new packets: -// Sending ACKs and retransmission is still allowed, but now new regular packets can be sent. -const MaxOutstandingSentPackets = 2 * defaultMaxCongestionWindowPackets - -// MaxTrackedSentPackets is maximum number of sent packets saved for retransmission. -// When reached, no more packets will be sent. -// This value *must* be larger than MaxOutstandingSentPackets. -const MaxTrackedSentPackets = MaxOutstandingSentPackets * 5 / 4 - -// MaxTrackedReceivedAckRanges is the maximum number of ACK ranges tracked -const MaxTrackedReceivedAckRanges = defaultMaxCongestionWindowPackets - -// MaxNonAckElicitingAcks is the maximum number of packets containing an ACK, -// but no ack-eliciting frames, that we send in a row -const MaxNonAckElicitingAcks = 19 - -// MaxStreamFrameSorterGaps is the maximum number of gaps between received StreamFrames -// prevents DoS attacks against the streamFrameSorter -const MaxStreamFrameSorterGaps = 1000 - -// MaxCryptoStreamOffset is the maximum offset allowed on any of the crypto streams. -// This limits the size of the ClientHello and Certificates that can be received. -const MaxCryptoStreamOffset = 16 * (1 << 10) - -// MinRemoteIdleTimeout is the minimum value that we accept for the remote idle timeout -const MinRemoteIdleTimeout = 5 * time.Second - -// DefaultIdleTimeout is the default idle timeout -const DefaultIdleTimeout = 30 * time.Second - -// DefaultHandshakeTimeout is the default timeout for a connection until the crypto handshake succeeds. -const DefaultHandshakeTimeout = 10 * time.Second - -// RetiredConnectionIDDeleteTimeout is the time we keep closed sessions around in order to retransmit the CONNECTION_CLOSE. -// after this time all information about the old connection will be deleted -const RetiredConnectionIDDeleteTimeout = 5 * time.Second - -// MinStreamFrameSize is the minimum size that has to be left in a packet, so that we add another STREAM frame. -// This avoids splitting up STREAM frames into small pieces, which has 2 advantages: -// 1. it reduces the framing overhead -// 2. it reduces the head-of-line blocking, when a packet is lost -const MinStreamFrameSize ByteCount = 128 - -// MaxPostHandshakeCryptoFrameSize is the maximum size of CRYPTO frames -// we send after the handshake completes. -const MaxPostHandshakeCryptoFrameSize ByteCount = 1000 - -// MaxAckFrameSize is the maximum size for an ACK frame that we write -// Due to the varint encoding, ACK frames can grow (almost) indefinitely large. -// The MaxAckFrameSize should be large enough to encode many ACK range, -// but must ensure that a maximum size ACK frame fits into one packet. -const MaxAckFrameSize ByteCount = 1000 - -// MinPacingDelay is the minimum duration that is used for packet pacing -// If the packet packing frequency is higher, multiple packets might be sent at once. -// Example: For a packet pacing delay of 20 microseconds, we would send 5 packets at once, wait for 100 microseconds, and so forth. -const MinPacingDelay time.Duration = 100 * time.Microsecond - -// DefaultConnectionIDLength is the connection ID length that is used for multiplexed connections -// if no other value is configured. -const DefaultConnectionIDLength = 4 - -// AckDelayExponent is the ack delay exponent used when sending ACKs. -const AckDelayExponent = 3 - -// Estimated timer granularity. -// The loss detection timer will not be set to a value smaller than granularity. -const TimerGranularity = time.Millisecond - -// MaxAckDelay is the maximum time by which we delay sending ACKs. -const MaxAckDelay = 25 * time.Millisecond - -// MaxAckDelayInclGranularity is the max_ack_delay including the timer granularity. -// This is the value that should be advertised to the peer. -const MaxAckDelayInclGranularity = MaxAckDelay + TimerGranularity - -// KeyUpdateInterval is the maximum number of packets we send or receive before initiating a key udpate. -const KeyUpdateInterval = 100 * 1000 diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/perspective.go b/vendor/github.com/lucas-clemente/quic-go/internal/protocol/perspective.go deleted file mode 100644 index 43358fecb4..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/perspective.go +++ /dev/null @@ -1,26 +0,0 @@ -package protocol - -// Perspective determines if we're acting as a server or a client -type Perspective int - -// the perspectives -const ( - PerspectiveServer Perspective = 1 - PerspectiveClient Perspective = 2 -) - -// Opposite returns the perspective of the peer -func (p Perspective) Opposite() Perspective { - return 3 - p -} - -func (p Perspective) String() string { - switch p { - case PerspectiveServer: - return "Server" - case PerspectiveClient: - return "Client" - default: - return "invalid perspective" - } -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/protocol.go b/vendor/github.com/lucas-clemente/quic-go/internal/protocol/protocol.go deleted file mode 100644 index 130cb1bffb..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/protocol.go +++ /dev/null @@ -1,75 +0,0 @@ -package protocol - -import ( - "fmt" - "time" -) - -// The PacketType is the Long Header Type -type PacketType uint8 - -const ( - // PacketTypeInitial is the packet type of an Initial packet - PacketTypeInitial PacketType = 1 + iota - // PacketTypeRetry is the packet type of a Retry packet - PacketTypeRetry - // PacketTypeHandshake is the packet type of a Handshake packet - PacketTypeHandshake - // PacketType0RTT is the packet type of a 0-RTT packet - PacketType0RTT -) - -func (t PacketType) String() string { - switch t { - case PacketTypeInitial: - return "Initial" - case PacketTypeRetry: - return "Retry" - case PacketTypeHandshake: - return "Handshake" - case PacketType0RTT: - return "0-RTT Protected" - default: - return fmt.Sprintf("unknown packet type: %d", t) - } -} - -// A ByteCount in QUIC -type ByteCount uint64 - -// MaxByteCount is the maximum value of a ByteCount -const MaxByteCount = ByteCount(1<<62 - 1) - -// An ApplicationErrorCode is an application-defined error code. -type ApplicationErrorCode uint64 - -// MaxReceivePacketSize maximum packet size of any QUIC packet, based on -// ethernet's max size, minus the IP and UDP headers. IPv6 has a 40 byte header, -// UDP adds an additional 8 bytes. This is a total overhead of 48 bytes. -// Ethernet's max packet size is 1500 bytes, 1500 - 48 = 1452. -const MaxReceivePacketSize ByteCount = 1452 - -// DefaultTCPMSS is the default maximum packet size used in the Linux TCP implementation. -// Used in QUIC for congestion window computations in bytes. -const DefaultTCPMSS ByteCount = 1460 - -// MinInitialPacketSize is the minimum size an Initial packet is required to have. -const MinInitialPacketSize = 1200 - -// MinStatelessResetSize is the minimum size of a stateless reset packet -const MinStatelessResetSize = 1 /* first byte */ + 22 /* random bytes */ + 16 /* token */ - -// MinConnectionIDLenInitial is the minimum length of the destination connection ID on an Initial packet. -const MinConnectionIDLenInitial = 8 - -// DefaultAckDelayExponent is the default ack delay exponent -const DefaultAckDelayExponent = 3 - -// MaxAckDelayExponent is the maximum ack delay exponent -const MaxAckDelayExponent = 20 - -// DefaultMaxAckDelay is the default max_ack_delay -const DefaultMaxAckDelay = 25 * time.Millisecond - -// MaxMaxAckDelay is the maximum max_ack_delay -const MaxMaxAckDelay = 1 << 14 * time.Millisecond diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/stream.go b/vendor/github.com/lucas-clemente/quic-go/internal/protocol/stream.go deleted file mode 100644 index 988dcc82fd..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/stream.go +++ /dev/null @@ -1,76 +0,0 @@ -package protocol - -// StreamType encodes if this is a unidirectional or bidirectional stream -type StreamType uint8 - -const ( - // StreamTypeUni is a unidirectional stream - StreamTypeUni StreamType = iota - // StreamTypeBidi is a bidirectional stream - StreamTypeBidi -) - -// InvalidPacketNumber is a stream ID that is invalid. -// The first valid stream ID in QUIC is 0. -const InvalidStreamID StreamID = -1 - -// StreamNum is the stream number -type StreamNum int64 - -const ( - // InvalidStreamNum is an invalid stream number. - InvalidStreamNum = -1 - // MaxStreamCount is the maximum stream count value that can be sent in MAX_STREAMS frames - // and as the stream count in the transport parameters - MaxStreamCount StreamNum = 1 << 60 -) - -// StreamID calculates the stream ID. -func (s StreamNum) StreamID(stype StreamType, pers Perspective) StreamID { - if s == 0 { - return InvalidStreamID - } - var first StreamID - switch stype { - case StreamTypeBidi: - switch pers { - case PerspectiveClient: - first = 0 - case PerspectiveServer: - first = 1 - } - case StreamTypeUni: - switch pers { - case PerspectiveClient: - first = 2 - case PerspectiveServer: - first = 3 - } - } - return first + 4*StreamID(s-1) -} - -// A StreamID in QUIC -type StreamID int64 - -// InitiatedBy says if the stream was initiated by the client or by the server -func (s StreamID) InitiatedBy() Perspective { - if s%2 == 0 { - return PerspectiveClient - } - return PerspectiveServer -} - -//Type says if this is a unidirectional or bidirectional stream -func (s StreamID) Type() StreamType { - if s%4 >= 2 { - return StreamTypeUni - } - return StreamTypeBidi -} - -// StreamNum returns how many streams in total are below this -// Example: for stream 9 it returns 3 (i.e. streams 1, 5 and 9) -func (s StreamID) StreamNum() StreamNum { - return StreamNum(s/4) + 1 -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/version.go b/vendor/github.com/lucas-clemente/quic-go/internal/protocol/version.go deleted file mode 100644 index 3406cfa465..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/protocol/version.go +++ /dev/null @@ -1,117 +0,0 @@ -package protocol - -import ( - "crypto/rand" - "encoding/binary" - "fmt" - "math" -) - -// VersionNumber is a version number as int -type VersionNumber uint32 - -// gQUIC version range as defined in the wiki: https://github.com/quicwg/base-drafts/wiki/QUIC-Versions -const ( - gquicVersion0 = 0x51303030 - maxGquicVersion = 0x51303439 -) - -// The version numbers, making grepping easier -const ( - VersionTLS VersionNumber = 0x51474fff - VersionWhatever VersionNumber = 1 // for when the version doesn't matter - VersionUnknown VersionNumber = math.MaxUint32 -) - -// SupportedVersions lists the versions that the server supports -// must be in sorted descending order -var SupportedVersions = []VersionNumber{VersionTLS} - -// IsValidVersion says if the version is known to quic-go -func IsValidVersion(v VersionNumber) bool { - return v == VersionTLS || IsSupportedVersion(SupportedVersions, v) -} - -func (vn VersionNumber) String() string { - switch vn { - case VersionWhatever: - return "whatever" - case VersionUnknown: - return "unknown" - case VersionTLS: - return "TLS dev version (WIP)" - default: - if vn.isGQUIC() { - return fmt.Sprintf("gQUIC %d", vn.toGQUICVersion()) - } - return fmt.Sprintf("%#x", uint32(vn)) - } -} - -// ToAltSvc returns the representation of the version for the H2 Alt-Svc parameters -func (vn VersionNumber) ToAltSvc() string { - return fmt.Sprintf("%d", vn) -} - -func (vn VersionNumber) isGQUIC() bool { - return vn > gquicVersion0 && vn <= maxGquicVersion -} - -func (vn VersionNumber) toGQUICVersion() int { - return int(10*(vn-gquicVersion0)/0x100) + int(vn%0x10) -} - -// IsSupportedVersion returns true if the server supports this version -func IsSupportedVersion(supported []VersionNumber, v VersionNumber) bool { - for _, t := range supported { - if t == v { - return true - } - } - return false -} - -// ChooseSupportedVersion finds the best version in the overlap of ours and theirs -// ours is a slice of versions that we support, sorted by our preference (descending) -// theirs is a slice of versions offered by the peer. The order does not matter. -// The bool returned indicates if a matching version was found. -func ChooseSupportedVersion(ours, theirs []VersionNumber) (VersionNumber, bool) { - for _, ourVer := range ours { - for _, theirVer := range theirs { - if ourVer == theirVer { - return ourVer, true - } - } - } - return 0, false -} - -// generateReservedVersion generates a reserved version number (v & 0x0f0f0f0f == 0x0a0a0a0a) -func generateReservedVersion() VersionNumber { - b := make([]byte, 4) - _, _ = rand.Read(b) // ignore the error here. Failure to read random data doesn't break anything - return VersionNumber((binary.BigEndian.Uint32(b) | 0x0a0a0a0a) & 0xfafafafa) -} - -// GetGreasedVersions adds one reserved version number to a slice of version numbers, at a random position -func GetGreasedVersions(supported []VersionNumber) []VersionNumber { - b := make([]byte, 1) - _, _ = rand.Read(b) // ignore the error here. Failure to read random data doesn't break anything - randPos := int(b[0]) % (len(supported) + 1) - greased := make([]VersionNumber, len(supported)+1) - copy(greased, supported[:randPos]) - greased[randPos] = generateReservedVersion() - copy(greased[randPos+1:], supported[randPos:]) - return greased -} - -// StripGreasedVersions strips all greased versions from a slice of versions -func StripGreasedVersions(versions []VersionNumber) []VersionNumber { - realVersions := make([]VersionNumber, 0, len(versions)) - for _, v := range versions { - if v&0x0f0f0f0f != 0x0a0a0a0a { - realVersions = append(realVersions, v) - } - } - return realVersions -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/qerr/error_codes.go b/vendor/github.com/lucas-clemente/quic-go/internal/qerr/error_codes.go deleted file mode 100644 index f5a9de5e3d..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/qerr/error_codes.go +++ /dev/null @@ -1,71 +0,0 @@ -package qerr - -import ( - "fmt" - - "github.com/marten-seemann/qtls" -) - -// ErrorCode can be used as a normal error without reason. -type ErrorCode uint64 - -// The error codes defined by QUIC -const ( - NoError ErrorCode = 0x0 - InternalError ErrorCode = 0x1 - ServerBusy ErrorCode = 0x2 - FlowControlError ErrorCode = 0x3 - StreamLimitError ErrorCode = 0x4 - StreamStateError ErrorCode = 0x5 - FinalSizeError ErrorCode = 0x6 - FrameEncodingError ErrorCode = 0x7 - TransportParameterError ErrorCode = 0x8 - VersionNegotiationError ErrorCode = 0x9 - ProtocolViolation ErrorCode = 0xa - InvalidMigration ErrorCode = 0xc -) - -func (e ErrorCode) isCryptoError() bool { - return e >= 0x100 && e < 0x200 -} - -func (e ErrorCode) Error() string { - if e.isCryptoError() { - return fmt.Sprintf("%s: %s", e.String(), qtls.Alert(e-0x100).Error()) - } - return e.String() -} - -func (e ErrorCode) String() string { - switch e { - case NoError: - return "NO_ERROR" - case InternalError: - return "INTERNAL_ERROR" - case ServerBusy: - return "SERVER_BUSY" - case FlowControlError: - return "FLOW_CONTROL_ERROR" - case StreamLimitError: - return "STREAM_LIMIT_ERROR" - case StreamStateError: - return "STREAM_STATE_ERROR" - case FinalSizeError: - return "FINAL_SIZE_ERROR" - case FrameEncodingError: - return "FRAME_ENCODING_ERROR" - case TransportParameterError: - return "TRANSPORT_PARAMETER_ERROR" - case VersionNegotiationError: - return "VERSION_NEGOTIATION_ERROR" - case ProtocolViolation: - return "PROTOCOL_VIOLATION" - case InvalidMigration: - return "INVALID_MIGRATION" - default: - if e.isCryptoError() { - return "CRYPTO_ERROR" - } - return fmt.Sprintf("unknown error code: %#x", uint16(e)) - } -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/qerr/quic_error.go b/vendor/github.com/lucas-clemente/quic-go/internal/qerr/quic_error.go deleted file mode 100644 index c4347afa29..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/qerr/quic_error.go +++ /dev/null @@ -1,88 +0,0 @@ -package qerr - -import ( - "fmt" - "net" -) - -// A QuicError consists of an error code plus a error reason -type QuicError struct { - ErrorCode ErrorCode - ErrorMessage string - isTimeout bool - isApplicationError bool -} - -var _ net.Error = &QuicError{} - -// Error creates a new QuicError instance -func Error(errorCode ErrorCode, errorMessage string) *QuicError { - return &QuicError{ - ErrorCode: errorCode, - ErrorMessage: errorMessage, - } -} - -// TimeoutError creates a new QuicError instance for a timeout error -func TimeoutError(errorMessage string) *QuicError { - return &QuicError{ - ErrorMessage: errorMessage, - isTimeout: true, - } -} - -// CryptoError create a new QuicError instance for a crypto error -func CryptoError(tlsAlert uint8, errorMessage string) *QuicError { - return &QuicError{ - ErrorCode: 0x100 + ErrorCode(tlsAlert), - ErrorMessage: errorMessage, - } -} - -func ApplicationError(errorCode ErrorCode, errorMessage string) *QuicError { - return &QuicError{ - ErrorCode: errorCode, - ErrorMessage: errorMessage, - isApplicationError: true, - } -} - -func (e *QuicError) Error() string { - if e.isApplicationError { - if len(e.ErrorMessage) == 0 { - return fmt.Sprintf("Application error %#x", uint64(e.ErrorCode)) - } - return fmt.Sprintf("Application error %#x: %s", uint64(e.ErrorCode), e.ErrorMessage) - } - if len(e.ErrorMessage) == 0 { - return e.ErrorCode.Error() - } - return fmt.Sprintf("%s: %s", e.ErrorCode.String(), e.ErrorMessage) -} - -// IsCryptoError says if this error is a crypto error -func (e *QuicError) IsCryptoError() bool { - return e.ErrorCode.isCryptoError() -} - -// Temporary says if the error is temporary. -func (e *QuicError) Temporary() bool { - return false -} - -// Timeout says if this error is a timeout. -func (e *QuicError) Timeout() bool { - return e.isTimeout -} - -// ToQuicError converts an arbitrary error to a QuicError. It leaves QuicErrors -// unchanged, and properly handles `ErrorCode`s. -func ToQuicError(err error) *QuicError { - switch e := err.(type) { - case *QuicError: - return e - case ErrorCode: - return Error(e, "") - } - return Error(InternalError, err.Error()) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/ack_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/ack_frame.go deleted file mode 100644 index 7909bffa8f..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/ack_frame.go +++ /dev/null @@ -1,226 +0,0 @@ -package wire - -import ( - "bytes" - "errors" - "sort" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -var errInvalidAckRanges = errors.New("AckFrame: ACK frame contains invalid ACK ranges") - -// An AckFrame is an ACK frame -type AckFrame struct { - AckRanges []AckRange // has to be ordered. The highest ACK range goes first, the lowest ACK range goes last - DelayTime time.Duration -} - -// parseAckFrame reads an ACK frame -func parseAckFrame(r *bytes.Reader, ackDelayExponent uint8, version protocol.VersionNumber) (*AckFrame, error) { - typeByte, err := r.ReadByte() - if err != nil { - return nil, err - } - ecn := typeByte&0x1 > 0 - - frame := &AckFrame{} - - la, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - largestAcked := protocol.PacketNumber(la) - delay, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - frame.DelayTime = time.Duration(delay*1< largestAcked { - return nil, errors.New("invalid first ACK range") - } - smallest := largestAcked - ackBlock - - // read all the other ACK ranges - frame.AckRanges = append(frame.AckRanges, AckRange{Smallest: smallest, Largest: largestAcked}) - for i := uint64(0); i < numBlocks; i++ { - g, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - gap := protocol.PacketNumber(g) - if smallest < gap+2 { - return nil, errInvalidAckRanges - } - largest := smallest - gap - 2 - - ab, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - ackBlock := protocol.PacketNumber(ab) - - if ackBlock > largest { - return nil, errInvalidAckRanges - } - smallest = largest - ackBlock - frame.AckRanges = append(frame.AckRanges, AckRange{Smallest: smallest, Largest: largest}) - } - - if !frame.validateAckRanges() { - return nil, errInvalidAckRanges - } - - // parse (and skip) the ECN section - if ecn { - for i := 0; i < 3; i++ { - if _, err := utils.ReadVarInt(r); err != nil { - return nil, err - } - } - } - - return frame, nil -} - -// Write writes an ACK frame. -func (f *AckFrame) Write(b *bytes.Buffer, version protocol.VersionNumber) error { - b.WriteByte(0x2) - utils.WriteVarInt(b, uint64(f.LargestAcked())) - utils.WriteVarInt(b, encodeAckDelay(f.DelayTime)) - - numRanges := f.numEncodableAckRanges() - utils.WriteVarInt(b, uint64(numRanges-1)) - - // write the first range - _, firstRange := f.encodeAckRange(0) - utils.WriteVarInt(b, firstRange) - - // write all the other range - for i := 1; i < numRanges; i++ { - gap, len := f.encodeAckRange(i) - utils.WriteVarInt(b, gap) - utils.WriteVarInt(b, len) - } - return nil -} - -// Length of a written frame -func (f *AckFrame) Length(version protocol.VersionNumber) protocol.ByteCount { - largestAcked := f.AckRanges[0].Largest - numRanges := f.numEncodableAckRanges() - - length := 1 + utils.VarIntLen(uint64(largestAcked)) + utils.VarIntLen(encodeAckDelay(f.DelayTime)) - - length += utils.VarIntLen(uint64(numRanges - 1)) - lowestInFirstRange := f.AckRanges[0].Smallest - length += utils.VarIntLen(uint64(largestAcked - lowestInFirstRange)) - - for i := 1; i < numRanges; i++ { - gap, len := f.encodeAckRange(i) - length += utils.VarIntLen(gap) - length += utils.VarIntLen(len) - } - return length -} - -// gets the number of ACK ranges that can be encoded -// such that the resulting frame is smaller than the maximum ACK frame size -func (f *AckFrame) numEncodableAckRanges() int { - length := 1 + utils.VarIntLen(uint64(f.LargestAcked())) + utils.VarIntLen(encodeAckDelay(f.DelayTime)) - length += 2 // assume that the number of ranges will consume 2 bytes - for i := 1; i < len(f.AckRanges); i++ { - gap, len := f.encodeAckRange(i) - rangeLen := utils.VarIntLen(gap) + utils.VarIntLen(len) - if length+rangeLen > protocol.MaxAckFrameSize { - // Writing range i would exceed the MaxAckFrameSize. - // So encode one range less than that. - return i - 1 - } - length += rangeLen - } - return len(f.AckRanges) -} - -func (f *AckFrame) encodeAckRange(i int) (uint64 /* gap */, uint64 /* length */) { - if i == 0 { - return 0, uint64(f.AckRanges[0].Largest - f.AckRanges[0].Smallest) - } - return uint64(f.AckRanges[i-1].Smallest - f.AckRanges[i].Largest - 2), - uint64(f.AckRanges[i].Largest - f.AckRanges[i].Smallest) -} - -// HasMissingRanges returns if this frame reports any missing packets -func (f *AckFrame) HasMissingRanges() bool { - return len(f.AckRanges) > 1 -} - -func (f *AckFrame) validateAckRanges() bool { - if len(f.AckRanges) == 0 { - return false - } - - // check the validity of every single ACK range - for _, ackRange := range f.AckRanges { - if ackRange.Smallest > ackRange.Largest { - return false - } - } - - // check the consistency for ACK with multiple NACK ranges - for i, ackRange := range f.AckRanges { - if i == 0 { - continue - } - lastAckRange := f.AckRanges[i-1] - if lastAckRange.Smallest <= ackRange.Smallest { - return false - } - if lastAckRange.Smallest <= ackRange.Largest+1 { - return false - } - } - - return true -} - -// LargestAcked is the largest acked packet number -func (f *AckFrame) LargestAcked() protocol.PacketNumber { - return f.AckRanges[0].Largest -} - -// LowestAcked is the lowest acked packet number -func (f *AckFrame) LowestAcked() protocol.PacketNumber { - return f.AckRanges[len(f.AckRanges)-1].Smallest -} - -// AcksPacket determines if this ACK frame acks a certain packet number -func (f *AckFrame) AcksPacket(p protocol.PacketNumber) bool { - if p < f.LowestAcked() || p > f.LargestAcked() { - return false - } - - i := sort.Search(len(f.AckRanges), func(i int) bool { - return p >= f.AckRanges[i].Smallest - }) - // i will always be < len(f.AckRanges), since we checked above that p is not bigger than the largest acked - return p <= f.AckRanges[i].Largest -} - -func encodeAckDelay(delay time.Duration) uint64 { - return uint64(delay.Nanoseconds() / (1000 * (1 << protocol.AckDelayExponent))) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/ack_range.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/ack_range.go deleted file mode 100644 index 0f4185801d..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/ack_range.go +++ /dev/null @@ -1,14 +0,0 @@ -package wire - -import "github.com/lucas-clemente/quic-go/internal/protocol" - -// AckRange is an ACK range -type AckRange struct { - Smallest protocol.PacketNumber - Largest protocol.PacketNumber -} - -// Len returns the number of packets contained in this ACK range -func (r AckRange) Len() protocol.PacketNumber { - return r.Largest - r.Smallest + 1 -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/connection_close_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/connection_close_frame.go deleted file mode 100644 index 5d07760dee..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/connection_close_frame.go +++ /dev/null @@ -1,81 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/qerr" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A ConnectionCloseFrame is a CONNECTION_CLOSE frame -type ConnectionCloseFrame struct { - IsApplicationError bool - ErrorCode qerr.ErrorCode - ReasonPhrase string -} - -func parseConnectionCloseFrame(r *bytes.Reader, version protocol.VersionNumber) (*ConnectionCloseFrame, error) { - typeByte, err := r.ReadByte() - if err != nil { - return nil, err - } - - f := &ConnectionCloseFrame{IsApplicationError: typeByte == 0x1d} - ec, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - f.ErrorCode = qerr.ErrorCode(ec) - // read the Frame Type, if this is not an application error - if !f.IsApplicationError { - if _, err := utils.ReadVarInt(r); err != nil { - return nil, err - } - } - var reasonPhraseLen uint64 - reasonPhraseLen, err = utils.ReadVarInt(r) - if err != nil { - return nil, err - } - // shortcut to prevent the unnecessary allocation of dataLen bytes - // if the dataLen is larger than the remaining length of the packet - // reading the whole reason phrase would result in EOF when attempting to READ - if int(reasonPhraseLen) > r.Len() { - return nil, io.EOF - } - - reasonPhrase := make([]byte, reasonPhraseLen) - if _, err := io.ReadFull(r, reasonPhrase); err != nil { - // this should never happen, since we already checked the reasonPhraseLen earlier - return nil, err - } - f.ReasonPhrase = string(reasonPhrase) - return f, nil -} - -// Length of a written frame -func (f *ConnectionCloseFrame) Length(version protocol.VersionNumber) protocol.ByteCount { - length := 1 + utils.VarIntLen(uint64(f.ErrorCode)) + utils.VarIntLen(uint64(len(f.ReasonPhrase))) + protocol.ByteCount(len(f.ReasonPhrase)) - if !f.IsApplicationError { - length++ // for the frame type - } - return length -} - -func (f *ConnectionCloseFrame) Write(b *bytes.Buffer, version protocol.VersionNumber) error { - if f.IsApplicationError { - b.WriteByte(0x1d) - } else { - b.WriteByte(0x1c) - } - - utils.WriteVarInt(b, uint64(f.ErrorCode)) - if !f.IsApplicationError { - utils.WriteVarInt(b, 0) - } - utils.WriteVarInt(b, uint64(len(f.ReasonPhrase))) - b.WriteString(f.ReasonPhrase) - return nil -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/crypto_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/crypto_frame.go deleted file mode 100644 index eeafea9743..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/crypto_frame.go +++ /dev/null @@ -1,71 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A CryptoFrame is a CRYPTO frame -type CryptoFrame struct { - Offset protocol.ByteCount - Data []byte -} - -func parseCryptoFrame(r *bytes.Reader, _ protocol.VersionNumber) (*CryptoFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - - frame := &CryptoFrame{} - offset, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - frame.Offset = protocol.ByteCount(offset) - dataLen, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - if dataLen > uint64(r.Len()) { - return nil, io.EOF - } - if dataLen != 0 { - frame.Data = make([]byte, dataLen) - if _, err := io.ReadFull(r, frame.Data); err != nil { - // this should never happen, since we already checked the dataLen earlier - return nil, err - } - } - return frame, nil -} - -func (f *CryptoFrame) Write(b *bytes.Buffer, _ protocol.VersionNumber) error { - b.WriteByte(0x6) - utils.WriteVarInt(b, uint64(f.Offset)) - utils.WriteVarInt(b, uint64(len(f.Data))) - b.Write(f.Data) - return nil -} - -// Length of a written frame -func (f *CryptoFrame) Length(_ protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(uint64(f.Offset)) + utils.VarIntLen(uint64(len(f.Data))) + protocol.ByteCount(len(f.Data)) -} - -// MaxDataLen returns the maximum data length -func (f *CryptoFrame) MaxDataLen(maxSize protocol.ByteCount) protocol.ByteCount { - // pretend that the data size will be 1 bytes - // if it turns out that varint encoding the length will consume 2 bytes, we need to adjust the data length afterwards - headerLen := 1 + utils.VarIntLen(uint64(f.Offset)) + 1 - if headerLen > maxSize { - return 0 - } - maxDataLen := maxSize - headerLen - if utils.VarIntLen(uint64(maxDataLen)) != 1 { - maxDataLen-- - } - return maxDataLen -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/data_blocked_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/data_blocked_frame.go deleted file mode 100644 index 91c05ccfbb..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/data_blocked_frame.go +++ /dev/null @@ -1,38 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A DataBlockedFrame is a DATA_BLOCKED frame -type DataBlockedFrame struct { - DataLimit protocol.ByteCount -} - -func parseDataBlockedFrame(r *bytes.Reader, _ protocol.VersionNumber) (*DataBlockedFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - offset, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - return &DataBlockedFrame{ - DataLimit: protocol.ByteCount(offset), - }, nil -} - -func (f *DataBlockedFrame) Write(b *bytes.Buffer, version protocol.VersionNumber) error { - typeByte := uint8(0x14) - b.WriteByte(typeByte) - utils.WriteVarInt(b, uint64(f.DataLimit)) - return nil -} - -// Length of a written frame -func (f *DataBlockedFrame) Length(version protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(uint64(f.DataLimit)) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/extended_header.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/extended_header.go deleted file mode 100644 index 4ab3951dc4..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/extended_header.go +++ /dev/null @@ -1,216 +0,0 @@ -package wire - -import ( - "bytes" - "errors" - "fmt" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// ErrInvalidReservedBits is returned when the reserved bits are incorrect. -// When this error is returned, parsing continues, and an ExtendedHeader is returned. -// This is necessary because we need to decrypt the packet in that case, -// in order to avoid a timing side-channel. -var ErrInvalidReservedBits = errors.New("invalid reserved bits") - -// ExtendedHeader is the header of a QUIC packet. -type ExtendedHeader struct { - Header - - typeByte byte - - PacketNumberLen protocol.PacketNumberLen - PacketNumber protocol.PacketNumber - - KeyPhase protocol.KeyPhaseBit -} - -func (h *ExtendedHeader) parse(b *bytes.Reader, v protocol.VersionNumber) (*ExtendedHeader, error) { - // read the (now unencrypted) first byte - var err error - h.typeByte, err = b.ReadByte() - if err != nil { - return nil, err - } - if _, err := b.Seek(int64(h.ParsedLen())-1, io.SeekCurrent); err != nil { - return nil, err - } - if h.IsLongHeader { - return h.parseLongHeader(b, v) - } - return h.parseShortHeader(b, v) -} - -func (h *ExtendedHeader) parseLongHeader(b *bytes.Reader, v protocol.VersionNumber) (*ExtendedHeader, error) { - if err := h.readPacketNumber(b); err != nil { - return nil, err - } - var err error - if h.typeByte&0xc != 0 { - err = ErrInvalidReservedBits - } - return h, err -} - -func (h *ExtendedHeader) parseShortHeader(b *bytes.Reader, v protocol.VersionNumber) (*ExtendedHeader, error) { - h.KeyPhase = protocol.KeyPhaseZero - if h.typeByte&0x4 > 0 { - h.KeyPhase = protocol.KeyPhaseOne - } - - if err := h.readPacketNumber(b); err != nil { - return nil, err - } - var err error - if h.typeByte&0x18 != 0 { - err = ErrInvalidReservedBits - } - return h, err -} - -func (h *ExtendedHeader) readPacketNumber(b *bytes.Reader) error { - h.PacketNumberLen = protocol.PacketNumberLen(h.typeByte&0x3) + 1 - pn, err := utils.BigEndian.ReadUintN(b, uint8(h.PacketNumberLen)) - if err != nil { - return err - } - h.PacketNumber = protocol.PacketNumber(pn) - return nil -} - -// Write writes the Header. -func (h *ExtendedHeader) Write(b *bytes.Buffer, ver protocol.VersionNumber) error { - if h.IsLongHeader { - return h.writeLongHeader(b, ver) - } - return h.writeShortHeader(b, ver) -} - -func (h *ExtendedHeader) writeLongHeader(b *bytes.Buffer, v protocol.VersionNumber) error { - var packetType uint8 - switch h.Type { - case protocol.PacketTypeInitial: - packetType = 0x0 - case protocol.PacketType0RTT: - packetType = 0x1 - case protocol.PacketTypeHandshake: - packetType = 0x2 - case protocol.PacketTypeRetry: - packetType = 0x3 - } - firstByte := 0xc0 | packetType<<4 - if h.Type == protocol.PacketTypeRetry { - odcil, err := encodeSingleConnIDLen(h.OrigDestConnectionID) - if err != nil { - return err - } - firstByte |= odcil - } else { // Retry packets don't have a packet number - firstByte |= uint8(h.PacketNumberLen - 1) - } - - b.WriteByte(firstByte) - utils.BigEndian.WriteUint32(b, uint32(h.Version)) - connIDLen, err := encodeConnIDLen(h.DestConnectionID, h.SrcConnectionID) - if err != nil { - return err - } - b.WriteByte(connIDLen) - b.Write(h.DestConnectionID.Bytes()) - b.Write(h.SrcConnectionID.Bytes()) - - switch h.Type { - case protocol.PacketTypeRetry: - b.Write(h.OrigDestConnectionID.Bytes()) - b.Write(h.Token) - return nil - case protocol.PacketTypeInitial: - utils.WriteVarInt(b, uint64(len(h.Token))) - b.Write(h.Token) - } - - utils.WriteVarInt(b, uint64(h.Length)) - return h.writePacketNumber(b) -} - -// TODO: add support for the key phase -func (h *ExtendedHeader) writeShortHeader(b *bytes.Buffer, v protocol.VersionNumber) error { - typeByte := 0x40 | uint8(h.PacketNumberLen-1) - if h.KeyPhase == protocol.KeyPhaseOne { - typeByte |= byte(1 << 2) - } - - b.WriteByte(typeByte) - b.Write(h.DestConnectionID.Bytes()) - return h.writePacketNumber(b) -} - -func (h *ExtendedHeader) writePacketNumber(b *bytes.Buffer) error { - if h.PacketNumberLen == protocol.PacketNumberLenInvalid || h.PacketNumberLen > protocol.PacketNumberLen4 { - return fmt.Errorf("invalid packet number length: %d", h.PacketNumberLen) - } - utils.BigEndian.WriteUintN(b, uint8(h.PacketNumberLen), uint64(h.PacketNumber)) - return nil -} - -// GetLength determines the length of the Header. -func (h *ExtendedHeader) GetLength(v protocol.VersionNumber) protocol.ByteCount { - if h.IsLongHeader { - length := 1 /* type byte */ + 4 /* version */ + 1 /* conn id len byte */ + protocol.ByteCount(h.DestConnectionID.Len()+h.SrcConnectionID.Len()) + protocol.ByteCount(h.PacketNumberLen) + utils.VarIntLen(uint64(h.Length)) - if h.Type == protocol.PacketTypeInitial { - length += utils.VarIntLen(uint64(len(h.Token))) + protocol.ByteCount(len(h.Token)) - } - return length - } - - length := protocol.ByteCount(1 /* type byte */ + h.DestConnectionID.Len()) - length += protocol.ByteCount(h.PacketNumberLen) - return length -} - -// Log logs the Header -func (h *ExtendedHeader) Log(logger utils.Logger) { - if h.IsLongHeader { - var token string - if h.Type == protocol.PacketTypeInitial || h.Type == protocol.PacketTypeRetry { - if len(h.Token) == 0 { - token = "Token: (empty), " - } else { - token = fmt.Sprintf("Token: %#x, ", h.Token) - } - if h.Type == protocol.PacketTypeRetry { - logger.Debugf("\tLong Header{Type: %s, DestConnectionID: %s, SrcConnectionID: %s, %sOrigDestConnectionID: %s, Version: %s}", h.Type, h.DestConnectionID, h.SrcConnectionID, token, h.OrigDestConnectionID, h.Version) - return - } - } - logger.Debugf("\tLong Header{Type: %s, DestConnectionID: %s, SrcConnectionID: %s, %sPacketNumber: %#x, PacketNumberLen: %d, Length: %d, Version: %s}", h.Type, h.DestConnectionID, h.SrcConnectionID, token, h.PacketNumber, h.PacketNumberLen, h.Length, h.Version) - } else { - logger.Debugf("\tShort Header{DestConnectionID: %s, PacketNumber: %#x, PacketNumberLen: %d, KeyPhase: %s}", h.DestConnectionID, h.PacketNumber, h.PacketNumberLen, h.KeyPhase) - } -} - -func encodeConnIDLen(dest, src protocol.ConnectionID) (byte, error) { - dcil, err := encodeSingleConnIDLen(dest) - if err != nil { - return 0, err - } - scil, err := encodeSingleConnIDLen(src) - if err != nil { - return 0, err - } - return scil | dcil<<4, nil -} - -func encodeSingleConnIDLen(id protocol.ConnectionID) (byte, error) { - len := id.Len() - if len == 0 { - return 0, nil - } - if len < 4 || len > 18 { - return 0, fmt.Errorf("invalid connection ID length: %d bytes", len) - } - return byte(len - 3), nil -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/frame_parser.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/frame_parser.go deleted file mode 100644 index da775f8cda..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/frame_parser.go +++ /dev/null @@ -1,115 +0,0 @@ -package wire - -import ( - "bytes" - "fmt" - "reflect" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/qerr" -) - -type frameParser struct { - ackDelayExponent uint8 - - version protocol.VersionNumber -} - -// NewFrameParser creates a new frame parser. -func NewFrameParser(v protocol.VersionNumber) FrameParser { - return &frameParser{version: v} -} - -// ParseNextFrame parses the next frame -// It skips PADDING frames. -func (p *frameParser) ParseNext(r *bytes.Reader, encLevel protocol.EncryptionLevel) (Frame, error) { - for r.Len() != 0 { - typeByte, _ := r.ReadByte() - if typeByte == 0x0 { // PADDING frame - continue - } - r.UnreadByte() - - f, err := p.parseFrame(r, typeByte, encLevel) - if err != nil { - return nil, qerr.Error(qerr.FrameEncodingError, err.Error()) - } - return f, nil - } - return nil, nil -} - -func (p *frameParser) parseFrame(r *bytes.Reader, typeByte byte, encLevel protocol.EncryptionLevel) (Frame, error) { - var frame Frame - var err error - if typeByte&0xf8 == 0x8 { - frame, err = parseStreamFrame(r, p.version) - } else { - switch typeByte { - case 0x1: - frame, err = parsePingFrame(r, p.version) - case 0x2, 0x3: - ackDelayExponent := p.ackDelayExponent - if encLevel != protocol.Encryption1RTT { - ackDelayExponent = protocol.DefaultAckDelayExponent - } - frame, err = parseAckFrame(r, ackDelayExponent, p.version) - case 0x4: - frame, err = parseResetStreamFrame(r, p.version) - case 0x5: - frame, err = parseStopSendingFrame(r, p.version) - case 0x6: - frame, err = parseCryptoFrame(r, p.version) - case 0x7: - frame, err = parseNewTokenFrame(r, p.version) - case 0x10: - frame, err = parseMaxDataFrame(r, p.version) - case 0x11: - frame, err = parseMaxStreamDataFrame(r, p.version) - case 0x12, 0x13: - frame, err = parseMaxStreamsFrame(r, p.version) - case 0x14: - frame, err = parseDataBlockedFrame(r, p.version) - case 0x15: - frame, err = parseStreamDataBlockedFrame(r, p.version) - case 0x16, 0x17: - frame, err = parseStreamsBlockedFrame(r, p.version) - case 0x18: - frame, err = parseNewConnectionIDFrame(r, p.version) - case 0x19: - frame, err = parseRetireConnectionIDFrame(r, p.version) - case 0x1a: - frame, err = parsePathChallengeFrame(r, p.version) - case 0x1b: - frame, err = parsePathResponseFrame(r, p.version) - case 0x1c, 0x1d: - frame, err = parseConnectionCloseFrame(r, p.version) - default: - err = fmt.Errorf("unknown type byte 0x%x", typeByte) - } - } - if err != nil { - return nil, err - } - if !p.isAllowedAtEncLevel(frame, encLevel) { - return nil, fmt.Errorf("%s not allowed at encryption level %s", reflect.TypeOf(frame).Elem().Name(), encLevel) - } - return frame, nil -} - -func (p *frameParser) isAllowedAtEncLevel(f Frame, encLevel protocol.EncryptionLevel) bool { - switch encLevel { - case protocol.EncryptionInitial, protocol.EncryptionHandshake: - switch f.(type) { - case *CryptoFrame, *AckFrame, *ConnectionCloseFrame: - return true - } - case protocol.Encryption1RTT: - return true - } - return false -} - -func (p *frameParser) SetAckDelayExponent(exp uint8) { - p.ackDelayExponent = exp -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/header.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/header.go deleted file mode 100644 index 8051982922..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/header.go +++ /dev/null @@ -1,251 +0,0 @@ -package wire - -import ( - "bytes" - "errors" - "fmt" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// ParseConnectionID parses the destination connection ID of a packet. -// It uses the data slice for the connection ID. -// That means that the connection ID must not be used after the packet buffer is released. -func ParseConnectionID(data []byte, shortHeaderConnIDLen int) (protocol.ConnectionID, error) { - if len(data) == 0 { - return nil, io.EOF - } - isLongHeader := data[0]&0x80 > 0 - if !isLongHeader { - if len(data) < shortHeaderConnIDLen+1 { - return nil, io.EOF - } - return protocol.ConnectionID(data[1 : 1+shortHeaderConnIDLen]), nil - } - if len(data) < 6 { - return nil, io.EOF - } - destConnIDLen, _ := decodeConnIDLen(data[5]) - if len(data) < 6+destConnIDLen { - return nil, io.EOF - } - return protocol.ConnectionID(data[6 : 6+destConnIDLen]), nil -} - -// IsVersionNegotiationPacket says if this is a version negotiation packet -func IsVersionNegotiationPacket(b []byte) bool { - if len(b) < 5 { - return false - } - return b[0]&0x80 > 0 && b[1] == 0 && b[2] == 0 && b[3] == 0 && b[4] == 0 -} - -var errUnsupportedVersion = errors.New("unsupported version") - -// The Header is the version independent part of the header -type Header struct { - Version protocol.VersionNumber - SrcConnectionID protocol.ConnectionID - DestConnectionID protocol.ConnectionID - - IsLongHeader bool - Type protocol.PacketType - Length protocol.ByteCount - - Token []byte - SupportedVersions []protocol.VersionNumber // sent in a Version Negotiation Packet - OrigDestConnectionID protocol.ConnectionID // sent in the Retry packet - - typeByte byte - parsedLen protocol.ByteCount // how many bytes were read while parsing this header -} - -// ParsePacket parses a packet. -// If the packet has a long header, the packet is cut according to the length field. -// If we understand the version, the packet is header up unto the packet number. -// Otherwise, only the invariant part of the header is parsed. -func ParsePacket(data []byte, shortHeaderConnIDLen int) (*Header, []byte /* packet data */, []byte /* rest */, error) { - hdr, err := parseHeader(bytes.NewReader(data), shortHeaderConnIDLen) - if err != nil { - if err == errUnsupportedVersion { - return hdr, nil, nil, nil - } - return nil, nil, nil, err - } - var rest []byte - if hdr.IsLongHeader { - if protocol.ByteCount(len(data)) < hdr.ParsedLen()+hdr.Length { - return nil, nil, nil, fmt.Errorf("packet length (%d bytes) is smaller than the expected length (%d bytes)", len(data)-int(hdr.ParsedLen()), hdr.Length) - } - packetLen := int(hdr.ParsedLen() + hdr.Length) - rest = data[packetLen:] - data = data[:packetLen] - } - return hdr, data, rest, nil -} - -// ParseHeader parses the header. -// For short header packets: up to the packet number. -// For long header packets: -// * if we understand the version: up to the packet number -// * if not, only the invariant part of the header -func parseHeader(b *bytes.Reader, shortHeaderConnIDLen int) (*Header, error) { - startLen := b.Len() - h, err := parseHeaderImpl(b, shortHeaderConnIDLen) - if err != nil { - return h, err - } - h.parsedLen = protocol.ByteCount(startLen - b.Len()) - return h, err -} - -func parseHeaderImpl(b *bytes.Reader, shortHeaderConnIDLen int) (*Header, error) { - typeByte, err := b.ReadByte() - if err != nil { - return nil, err - } - - h := &Header{ - typeByte: typeByte, - IsLongHeader: typeByte&0x80 > 0, - } - - if !h.IsLongHeader { - if h.typeByte&0x40 == 0 { - return nil, errors.New("not a QUIC packet") - } - if err := h.parseShortHeader(b, shortHeaderConnIDLen); err != nil { - return nil, err - } - return h, nil - } - return h, h.parseLongHeader(b) -} - -func (h *Header) parseShortHeader(b *bytes.Reader, shortHeaderConnIDLen int) error { - var err error - h.DestConnectionID, err = protocol.ReadConnectionID(b, shortHeaderConnIDLen) - return err -} - -func (h *Header) parseLongHeader(b *bytes.Reader) error { - v, err := utils.BigEndian.ReadUint32(b) - if err != nil { - return err - } - h.Version = protocol.VersionNumber(v) - if h.Version != 0 && h.typeByte&0x40 == 0 { - return errors.New("not a QUIC packet") - } - connIDLenByte, err := b.ReadByte() - if err != nil { - return err - } - dcil, scil := decodeConnIDLen(connIDLenByte) - h.DestConnectionID, err = protocol.ReadConnectionID(b, dcil) - if err != nil { - return err - } - h.SrcConnectionID, err = protocol.ReadConnectionID(b, scil) - if err != nil { - return err - } - if h.Version == 0 { - return h.parseVersionNegotiationPacket(b) - } - // If we don't understand the version, we have no idea how to interpret the rest of the bytes - if !protocol.IsSupportedVersion(protocol.SupportedVersions, h.Version) { - return errUnsupportedVersion - } - - switch (h.typeByte & 0x30) >> 4 { - case 0x0: - h.Type = protocol.PacketTypeInitial - case 0x1: - h.Type = protocol.PacketType0RTT - case 0x2: - h.Type = protocol.PacketTypeHandshake - case 0x3: - h.Type = protocol.PacketTypeRetry - } - - if h.Type == protocol.PacketTypeRetry { - odcil := decodeSingleConnIDLen(h.typeByte & 0xf) - h.OrigDestConnectionID, err = protocol.ReadConnectionID(b, odcil) - if err != nil { - return err - } - h.Token = make([]byte, b.Len()) - if _, err := io.ReadFull(b, h.Token); err != nil { - return err - } - return nil - } - - if h.Type == protocol.PacketTypeInitial { - tokenLen, err := utils.ReadVarInt(b) - if err != nil { - return err - } - if tokenLen > uint64(b.Len()) { - return io.EOF - } - h.Token = make([]byte, tokenLen) - if _, err := io.ReadFull(b, h.Token); err != nil { - return err - } - } - - pl, err := utils.ReadVarInt(b) - if err != nil { - return err - } - h.Length = protocol.ByteCount(pl) - return nil -} - -func (h *Header) parseVersionNegotiationPacket(b *bytes.Reader) error { - if b.Len() == 0 { - return errors.New("Version Negotiation packet has empty version list") - } - if b.Len()%4 != 0 { - return errors.New("Version Negotiation packet has a version list with an invalid length") - } - h.SupportedVersions = make([]protocol.VersionNumber, b.Len()/4) - for i := 0; b.Len() > 0; i++ { - v, err := utils.BigEndian.ReadUint32(b) - if err != nil { - return err - } - h.SupportedVersions[i] = protocol.VersionNumber(v) - } - return nil -} - -// ParsedLen returns the number of bytes that were consumed when parsing the header -func (h *Header) ParsedLen() protocol.ByteCount { - return h.parsedLen -} - -// ParseExtended parses the version dependent part of the header. -// The Reader has to be set such that it points to the first byte of the header. -func (h *Header) ParseExtended(b *bytes.Reader, ver protocol.VersionNumber) (*ExtendedHeader, error) { - return h.toExtendedHeader().parse(b, ver) -} - -func (h *Header) toExtendedHeader() *ExtendedHeader { - return &ExtendedHeader{Header: *h} -} - -func decodeConnIDLen(enc byte) (int /*dest conn id len*/, int /*src conn id len*/) { - return decodeSingleConnIDLen(enc >> 4), decodeSingleConnIDLen(enc & 0xf) -} - -func decodeSingleConnIDLen(enc uint8) int { - if enc == 0 { - return 0 - } - return int(enc) + 3 -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/interface.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/interface.go deleted file mode 100644 index 99fdc80fb2..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/interface.go +++ /dev/null @@ -1,19 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// A Frame in QUIC -type Frame interface { - Write(b *bytes.Buffer, version protocol.VersionNumber) error - Length(version protocol.VersionNumber) protocol.ByteCount -} - -// A FrameParser parses QUIC frames, one by one. -type FrameParser interface { - ParseNext(*bytes.Reader, protocol.EncryptionLevel) (Frame, error) - SetAckDelayExponent(uint8) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/log.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/log.go deleted file mode 100644 index 6013c8beb8..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/log.go +++ /dev/null @@ -1,57 +0,0 @@ -package wire - -import ( - "fmt" - "strings" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// LogFrame logs a frame, either sent or received -func LogFrame(logger utils.Logger, frame Frame, sent bool) { - if !logger.Debug() { - return - } - dir := "<-" - if sent { - dir = "->" - } - switch f := frame.(type) { - case *CryptoFrame: - dataLen := protocol.ByteCount(len(f.Data)) - logger.Debugf("\t%s &wire.CryptoFrame{Offset: 0x%x, Data length: 0x%x, Offset + Data length: 0x%x}", dir, f.Offset, dataLen, f.Offset+dataLen) - case *StreamFrame: - logger.Debugf("\t%s &wire.StreamFrame{StreamID: %d, FinBit: %t, Offset: 0x%x, Data length: 0x%x, Offset + Data length: 0x%x}", dir, f.StreamID, f.FinBit, f.Offset, f.DataLen(), f.Offset+f.DataLen()) - case *AckFrame: - if len(f.AckRanges) > 1 { - ackRanges := make([]string, len(f.AckRanges)) - for i, r := range f.AckRanges { - ackRanges[i] = fmt.Sprintf("{Largest: %#x, Smallest: %#x}", r.Largest, r.Smallest) - } - logger.Debugf("\t%s &wire.AckFrame{LargestAcked: %#x, LowestAcked: %#x, AckRanges: {%s}, DelayTime: %s}", dir, f.LargestAcked(), f.LowestAcked(), strings.Join(ackRanges, ", "), f.DelayTime.String()) - } else { - logger.Debugf("\t%s &wire.AckFrame{LargestAcked: %#x, LowestAcked: %#x, DelayTime: %s}", dir, f.LargestAcked(), f.LowestAcked(), f.DelayTime.String()) - } - case *MaxStreamsFrame: - switch f.Type { - case protocol.StreamTypeUni: - logger.Debugf("\t%s &wire.MaxStreamsFrame{Type: uni, MaxStreamNum: %d}", dir, f.MaxStreamNum) - case protocol.StreamTypeBidi: - logger.Debugf("\t%s &wire.MaxStreamsFrame{Type: bidi, MaxStreamNum: %d}", dir, f.MaxStreamNum) - } - case *StreamsBlockedFrame: - switch f.Type { - case protocol.StreamTypeUni: - logger.Debugf("\t%s &wire.StreamsBlockedFrame{Type: uni, MaxStreams: %d}", dir, f.StreamLimit) - case protocol.StreamTypeBidi: - logger.Debugf("\t%s &wire.StreamsBlockedFrame{Type: bidi, MaxStreams: %d}", dir, f.StreamLimit) - } - case *NewConnectionIDFrame: - logger.Debugf("\t%s &wire.NewConnectionIDFrame{SequenceNumber: %d, ConnectionID: %s, StatelessResetToken: %#x}", dir, f.SequenceNumber, f.ConnectionID, f.StatelessResetToken) - case *NewTokenFrame: - logger.Debugf("\t%s &wire.NewTokenFrame{Token: %#x}", dir, f.Token) - default: - logger.Debugf("\t%s %#v", dir, frame) - } -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/max_data_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/max_data_frame.go deleted file mode 100644 index c4a9be0df0..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/max_data_frame.go +++ /dev/null @@ -1,40 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A MaxDataFrame carries flow control information for the connection -type MaxDataFrame struct { - ByteOffset protocol.ByteCount -} - -// parseMaxDataFrame parses a MAX_DATA frame -func parseMaxDataFrame(r *bytes.Reader, version protocol.VersionNumber) (*MaxDataFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - - frame := &MaxDataFrame{} - byteOffset, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - frame.ByteOffset = protocol.ByteCount(byteOffset) - return frame, nil -} - -//Write writes a MAX_STREAM_DATA frame -func (f *MaxDataFrame) Write(b *bytes.Buffer, version protocol.VersionNumber) error { - b.WriteByte(0x10) - utils.WriteVarInt(b, uint64(f.ByteOffset)) - return nil -} - -// Length of a written frame -func (f *MaxDataFrame) Length(version protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(uint64(f.ByteOffset)) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/max_stream_data_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/max_stream_data_frame.go deleted file mode 100644 index 2566f1c9be..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/max_stream_data_frame.go +++ /dev/null @@ -1,46 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A MaxStreamDataFrame is a MAX_STREAM_DATA frame -type MaxStreamDataFrame struct { - StreamID protocol.StreamID - ByteOffset protocol.ByteCount -} - -func parseMaxStreamDataFrame(r *bytes.Reader, version protocol.VersionNumber) (*MaxStreamDataFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - - sid, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - offset, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - - return &MaxStreamDataFrame{ - StreamID: protocol.StreamID(sid), - ByteOffset: protocol.ByteCount(offset), - }, nil -} - -func (f *MaxStreamDataFrame) Write(b *bytes.Buffer, version protocol.VersionNumber) error { - b.WriteByte(0x11) - utils.WriteVarInt(b, uint64(f.StreamID)) - utils.WriteVarInt(b, uint64(f.ByteOffset)) - return nil -} - -// Length of a written frame -func (f *MaxStreamDataFrame) Length(version protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(uint64(f.StreamID)) + utils.VarIntLen(uint64(f.ByteOffset)) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/max_streams_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/max_streams_frame.go deleted file mode 100644 index 63e506c490..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/max_streams_frame.go +++ /dev/null @@ -1,51 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A MaxStreamsFrame is a MAX_STREAMS frame -type MaxStreamsFrame struct { - Type protocol.StreamType - MaxStreamNum protocol.StreamNum -} - -func parseMaxStreamsFrame(r *bytes.Reader, _ protocol.VersionNumber) (*MaxStreamsFrame, error) { - typeByte, err := r.ReadByte() - if err != nil { - return nil, err - } - - f := &MaxStreamsFrame{} - switch typeByte { - case 0x12: - f.Type = protocol.StreamTypeBidi - case 0x13: - f.Type = protocol.StreamTypeUni - } - streamID, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - f.MaxStreamNum = protocol.StreamNum(streamID) - return f, nil -} - -func (f *MaxStreamsFrame) Write(b *bytes.Buffer, _ protocol.VersionNumber) error { - switch f.Type { - case protocol.StreamTypeBidi: - b.WriteByte(0x12) - case protocol.StreamTypeUni: - b.WriteByte(0x13) - } - utils.WriteVarInt(b, uint64(f.MaxStreamNum)) - return nil -} - -// Length of a written frame -func (f *MaxStreamsFrame) Length(protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(uint64(f.MaxStreamNum)) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/new_connection_id_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/new_connection_id_frame.go deleted file mode 100644 index 9a612aa6c3..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/new_connection_id_frame.go +++ /dev/null @@ -1,70 +0,0 @@ -package wire - -import ( - "bytes" - "fmt" - "io" - - "github.com/lucas-clemente/quic-go/internal/utils" - - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// A NewConnectionIDFrame is a NEW_CONNECTION_ID frame -type NewConnectionIDFrame struct { - SequenceNumber uint64 - ConnectionID protocol.ConnectionID - StatelessResetToken [16]byte -} - -func parseNewConnectionIDFrame(r *bytes.Reader, _ protocol.VersionNumber) (*NewConnectionIDFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - - seq, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - connIDLen, err := r.ReadByte() - if err != nil { - return nil, err - } - if connIDLen < 4 || connIDLen > 18 { - return nil, fmt.Errorf("invalid connection ID length: %d", connIDLen) - } - connID, err := protocol.ReadConnectionID(r, int(connIDLen)) - if err != nil { - return nil, err - } - frame := &NewConnectionIDFrame{ - SequenceNumber: seq, - ConnectionID: connID, - } - if _, err := io.ReadFull(r, frame.StatelessResetToken[:]); err != nil { - if err == io.ErrUnexpectedEOF { - return nil, io.EOF - } - return nil, err - } - - return frame, nil -} - -func (f *NewConnectionIDFrame) Write(b *bytes.Buffer, _ protocol.VersionNumber) error { - b.WriteByte(0x18) - utils.WriteVarInt(b, f.SequenceNumber) - connIDLen := f.ConnectionID.Len() - if connIDLen < 4 || connIDLen > 18 { - return fmt.Errorf("invalid connection ID length: %d", connIDLen) - } - b.WriteByte(uint8(connIDLen)) - b.Write(f.ConnectionID.Bytes()) - b.Write(f.StatelessResetToken[:]) - return nil -} - -// Length of a written frame -func (f *NewConnectionIDFrame) Length(protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(f.SequenceNumber) + 1 /* connection ID length */ + protocol.ByteCount(f.ConnectionID.Len()) + 16 -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/new_token_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/new_token_frame.go deleted file mode 100644 index 2cf6fce5e4..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/new_token_frame.go +++ /dev/null @@ -1,44 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A NewTokenFrame is a NEW_TOKEN frame -type NewTokenFrame struct { - Token []byte -} - -func parseNewTokenFrame(r *bytes.Reader, _ protocol.VersionNumber) (*NewTokenFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - tokenLen, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - if uint64(r.Len()) < tokenLen { - return nil, io.EOF - } - token := make([]byte, int(tokenLen)) - if _, err := io.ReadFull(r, token); err != nil { - return nil, err - } - return &NewTokenFrame{Token: token}, nil -} - -func (f *NewTokenFrame) Write(b *bytes.Buffer, _ protocol.VersionNumber) error { - b.WriteByte(0x7) - utils.WriteVarInt(b, uint64(len(f.Token))) - b.Write(f.Token) - return nil -} - -// Length of a written frame -func (f *NewTokenFrame) Length(protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(uint64(len(f.Token))) + protocol.ByteCount(len(f.Token)) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/path_challenge_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/path_challenge_frame.go deleted file mode 100644 index d35ee3b54b..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/path_challenge_frame.go +++ /dev/null @@ -1,38 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// A PathChallengeFrame is a PATH_CHALLENGE frame -type PathChallengeFrame struct { - Data [8]byte -} - -func parsePathChallengeFrame(r *bytes.Reader, version protocol.VersionNumber) (*PathChallengeFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - frame := &PathChallengeFrame{} - if _, err := io.ReadFull(r, frame.Data[:]); err != nil { - if err == io.ErrUnexpectedEOF { - return nil, io.EOF - } - return nil, err - } - return frame, nil -} - -func (f *PathChallengeFrame) Write(b *bytes.Buffer, _ protocol.VersionNumber) error { - b.WriteByte(0x1a) - b.Write(f.Data[:]) - return nil -} - -// Length of a written frame -func (f *PathChallengeFrame) Length(_ protocol.VersionNumber) protocol.ByteCount { - return 1 + 8 -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/path_response_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/path_response_frame.go deleted file mode 100644 index 20d8fd7215..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/path_response_frame.go +++ /dev/null @@ -1,38 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// A PathResponseFrame is a PATH_RESPONSE frame -type PathResponseFrame struct { - Data [8]byte -} - -func parsePathResponseFrame(r *bytes.Reader, version protocol.VersionNumber) (*PathResponseFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - frame := &PathResponseFrame{} - if _, err := io.ReadFull(r, frame.Data[:]); err != nil { - if err == io.ErrUnexpectedEOF { - return nil, io.EOF - } - return nil, err - } - return frame, nil -} - -func (f *PathResponseFrame) Write(b *bytes.Buffer, _ protocol.VersionNumber) error { - b.WriteByte(0x1b) - b.Write(f.Data[:]) - return nil -} - -// Length of a written frame -func (f *PathResponseFrame) Length(_ protocol.VersionNumber) protocol.ByteCount { - return 1 + 8 -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/ping_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/ping_frame.go deleted file mode 100644 index aed6857b56..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/ping_frame.go +++ /dev/null @@ -1,27 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// A PingFrame is a PING frame -type PingFrame struct{} - -func parsePingFrame(r *bytes.Reader, version protocol.VersionNumber) (*PingFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - return &PingFrame{}, nil -} - -func (f *PingFrame) Write(b *bytes.Buffer, version protocol.VersionNumber) error { - b.WriteByte(0x1) - return nil -} - -// Length of a written frame -func (f *PingFrame) Length(version protocol.VersionNumber) protocol.ByteCount { - return 1 -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/reset_stream_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/reset_stream_frame.go deleted file mode 100644 index b743e04653..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/reset_stream_frame.go +++ /dev/null @@ -1,57 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A ResetStreamFrame is a RESET_STREAM frame in QUIC -type ResetStreamFrame struct { - StreamID protocol.StreamID - ErrorCode protocol.ApplicationErrorCode - ByteOffset protocol.ByteCount -} - -func parseResetStreamFrame(r *bytes.Reader, version protocol.VersionNumber) (*ResetStreamFrame, error) { - if _, err := r.ReadByte(); err != nil { // read the TypeByte - return nil, err - } - - var streamID protocol.StreamID - var byteOffset protocol.ByteCount - sid, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - streamID = protocol.StreamID(sid) - errorCode, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - bo, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - byteOffset = protocol.ByteCount(bo) - - return &ResetStreamFrame{ - StreamID: streamID, - ErrorCode: protocol.ApplicationErrorCode(errorCode), - ByteOffset: byteOffset, - }, nil -} - -func (f *ResetStreamFrame) Write(b *bytes.Buffer, version protocol.VersionNumber) error { - b.WriteByte(0x4) - utils.WriteVarInt(b, uint64(f.StreamID)) - utils.WriteVarInt(b, uint64(f.ErrorCode)) - utils.WriteVarInt(b, uint64(f.ByteOffset)) - return nil -} - -// Length of a written frame -func (f *ResetStreamFrame) Length(version protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(uint64(f.StreamID)) + utils.VarIntLen(uint64(f.ErrorCode)) + utils.VarIntLen(uint64(f.ByteOffset)) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/retire_connection_id_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/retire_connection_id_frame.go deleted file mode 100644 index 9a715a4c48..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/retire_connection_id_frame.go +++ /dev/null @@ -1,36 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A RetireConnectionIDFrame is a RETIRE_CONNECTION_ID frame -type RetireConnectionIDFrame struct { - SequenceNumber uint64 -} - -func parseRetireConnectionIDFrame(r *bytes.Reader, _ protocol.VersionNumber) (*RetireConnectionIDFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - - seq, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - return &RetireConnectionIDFrame{SequenceNumber: seq}, nil -} - -func (f *RetireConnectionIDFrame) Write(b *bytes.Buffer, _ protocol.VersionNumber) error { - b.WriteByte(0x19) - utils.WriteVarInt(b, f.SequenceNumber) - return nil -} - -// Length of a written frame -func (f *RetireConnectionIDFrame) Length(protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(f.SequenceNumber) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/stop_sending_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/stop_sending_frame.go deleted file mode 100644 index f9a5d60b02..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/stop_sending_frame.go +++ /dev/null @@ -1,47 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A StopSendingFrame is a STOP_SENDING frame -type StopSendingFrame struct { - StreamID protocol.StreamID - ErrorCode protocol.ApplicationErrorCode -} - -// parseStopSendingFrame parses a STOP_SENDING frame -func parseStopSendingFrame(r *bytes.Reader, _ protocol.VersionNumber) (*StopSendingFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - - streamID, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - errorCode, err := utils.BigEndian.ReadUint16(r) - if err != nil { - return nil, err - } - - return &StopSendingFrame{ - StreamID: protocol.StreamID(streamID), - ErrorCode: protocol.ApplicationErrorCode(errorCode), - }, nil -} - -// Length of a written frame -func (f *StopSendingFrame) Length(_ protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(uint64(f.StreamID)) + 2 -} - -func (f *StopSendingFrame) Write(b *bytes.Buffer, _ protocol.VersionNumber) error { - b.WriteByte(0x5) - utils.WriteVarInt(b, uint64(f.StreamID)) - utils.BigEndian.WriteUint16(b, uint16(f.ErrorCode)) - return nil -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/stream_data_blocked_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/stream_data_blocked_frame.go deleted file mode 100644 index 9f2e90be0b..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/stream_data_blocked_frame.go +++ /dev/null @@ -1,46 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A StreamDataBlockedFrame is a STREAM_DATA_BLOCKED frame -type StreamDataBlockedFrame struct { - StreamID protocol.StreamID - DataLimit protocol.ByteCount -} - -func parseStreamDataBlockedFrame(r *bytes.Reader, _ protocol.VersionNumber) (*StreamDataBlockedFrame, error) { - if _, err := r.ReadByte(); err != nil { - return nil, err - } - - sid, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - offset, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - - return &StreamDataBlockedFrame{ - StreamID: protocol.StreamID(sid), - DataLimit: protocol.ByteCount(offset), - }, nil -} - -func (f *StreamDataBlockedFrame) Write(b *bytes.Buffer, version protocol.VersionNumber) error { - b.WriteByte(0x15) - utils.WriteVarInt(b, uint64(f.StreamID)) - utils.WriteVarInt(b, uint64(f.DataLimit)) - return nil -} - -// Length of a written frame -func (f *StreamDataBlockedFrame) Length(version protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(uint64(f.StreamID)) + utils.VarIntLen(uint64(f.DataLimit)) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/stream_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/stream_frame.go deleted file mode 100644 index dfc1d1adfd..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/stream_frame.go +++ /dev/null @@ -1,168 +0,0 @@ -package wire - -import ( - "bytes" - "errors" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/qerr" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A StreamFrame of QUIC -type StreamFrame struct { - StreamID protocol.StreamID - FinBit bool - DataLenPresent bool - Offset protocol.ByteCount - Data []byte -} - -func parseStreamFrame(r *bytes.Reader, version protocol.VersionNumber) (*StreamFrame, error) { - typeByte, err := r.ReadByte() - if err != nil { - return nil, err - } - - hasOffset := typeByte&0x4 > 0 - frame := &StreamFrame{ - FinBit: typeByte&0x1 > 0, - DataLenPresent: typeByte&0x2 > 0, - } - - streamID, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - frame.StreamID = protocol.StreamID(streamID) - if hasOffset { - offset, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - frame.Offset = protocol.ByteCount(offset) - } - - var dataLen uint64 - if frame.DataLenPresent { - var err error - dataLen, err = utils.ReadVarInt(r) - if err != nil { - return nil, err - } - // shortcut to prevent the unnecessary allocation of dataLen bytes - // if the dataLen is larger than the remaining length of the packet - // reading the packet contents would result in EOF when attempting to READ - if dataLen > uint64(r.Len()) { - return nil, io.EOF - } - } else { - // The rest of the packet is data - dataLen = uint64(r.Len()) - } - if dataLen != 0 { - frame.Data = make([]byte, dataLen) - if _, err := io.ReadFull(r, frame.Data); err != nil { - // this should never happen, since we already checked the dataLen earlier - return nil, err - } - } - if frame.Offset+frame.DataLen() > protocol.MaxByteCount { - return nil, qerr.Error(qerr.FrameEncodingError, "stream data overflows maximum offset") - } - return frame, nil -} - -// Write writes a STREAM frame -func (f *StreamFrame) Write(b *bytes.Buffer, version protocol.VersionNumber) error { - if len(f.Data) == 0 && !f.FinBit { - return errors.New("StreamFrame: attempting to write empty frame without FIN") - } - - typeByte := byte(0x8) - if f.FinBit { - typeByte ^= 0x1 - } - hasOffset := f.Offset != 0 - if f.DataLenPresent { - typeByte ^= 0x2 - } - if hasOffset { - typeByte ^= 0x4 - } - b.WriteByte(typeByte) - utils.WriteVarInt(b, uint64(f.StreamID)) - if hasOffset { - utils.WriteVarInt(b, uint64(f.Offset)) - } - if f.DataLenPresent { - utils.WriteVarInt(b, uint64(f.DataLen())) - } - b.Write(f.Data) - return nil -} - -// Length returns the total length of the STREAM frame -func (f *StreamFrame) Length(version protocol.VersionNumber) protocol.ByteCount { - length := 1 + utils.VarIntLen(uint64(f.StreamID)) - if f.Offset != 0 { - length += utils.VarIntLen(uint64(f.Offset)) - } - if f.DataLenPresent { - length += utils.VarIntLen(uint64(f.DataLen())) - } - return length + f.DataLen() -} - -// DataLen gives the length of data in bytes -func (f *StreamFrame) DataLen() protocol.ByteCount { - return protocol.ByteCount(len(f.Data)) -} - -// MaxDataLen returns the maximum data length -// If 0 is returned, writing will fail (a STREAM frame must contain at least 1 byte of data). -func (f *StreamFrame) MaxDataLen(maxSize protocol.ByteCount, version protocol.VersionNumber) protocol.ByteCount { - headerLen := 1 + utils.VarIntLen(uint64(f.StreamID)) - if f.Offset != 0 { - headerLen += utils.VarIntLen(uint64(f.Offset)) - } - if f.DataLenPresent { - // pretend that the data size will be 1 bytes - // if it turns out that varint encoding the length will consume 2 bytes, we need to adjust the data length afterwards - headerLen++ - } - if headerLen > maxSize { - return 0 - } - maxDataLen := maxSize - headerLen - if f.DataLenPresent && utils.VarIntLen(uint64(maxDataLen)) != 1 { - maxDataLen-- - } - return maxDataLen -} - -// MaybeSplitOffFrame splits a frame such that it is not bigger than n bytes. -// If n >= len(frame), nil is returned and nothing is modified. -func (f *StreamFrame) MaybeSplitOffFrame(maxSize protocol.ByteCount, version protocol.VersionNumber) (*StreamFrame, error) { - if maxSize >= f.Length(version) { - return nil, nil - } - - n := f.MaxDataLen(maxSize, version) - if n == 0 { - return nil, errors.New("too small") - } - newFrame := &StreamFrame{ - FinBit: false, - StreamID: f.StreamID, - Offset: f.Offset, - Data: f.Data[:n], - DataLenPresent: f.DataLenPresent, - } - - f.Data = f.Data[n:] - f.Offset += n - - return newFrame, nil -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/streams_blocked_frame.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/streams_blocked_frame.go deleted file mode 100644 index c46e87b479..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/streams_blocked_frame.go +++ /dev/null @@ -1,52 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// A StreamsBlockedFrame is a STREAMS_BLOCKED frame -type StreamsBlockedFrame struct { - Type protocol.StreamType - StreamLimit protocol.StreamNum -} - -func parseStreamsBlockedFrame(r *bytes.Reader, _ protocol.VersionNumber) (*StreamsBlockedFrame, error) { - typeByte, err := r.ReadByte() - if err != nil { - return nil, err - } - - f := &StreamsBlockedFrame{} - switch typeByte { - case 0x16: - f.Type = protocol.StreamTypeBidi - case 0x17: - f.Type = protocol.StreamTypeUni - } - streamLimit, err := utils.ReadVarInt(r) - if err != nil { - return nil, err - } - f.StreamLimit = protocol.StreamNum(streamLimit) - - return f, nil -} - -func (f *StreamsBlockedFrame) Write(b *bytes.Buffer, _ protocol.VersionNumber) error { - switch f.Type { - case protocol.StreamTypeBidi: - b.WriteByte(0x16) - case protocol.StreamTypeUni: - b.WriteByte(0x17) - } - utils.WriteVarInt(b, uint64(f.StreamLimit)) - return nil -} - -// Length of a written frame -func (f *StreamsBlockedFrame) Length(_ protocol.VersionNumber) protocol.ByteCount { - return 1 + utils.VarIntLen(uint64(f.StreamLimit)) -} diff --git a/vendor/github.com/lucas-clemente/quic-go/internal/wire/version_negotiation.go b/vendor/github.com/lucas-clemente/quic-go/internal/wire/version_negotiation.go deleted file mode 100644 index bfc27af775..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/internal/wire/version_negotiation.go +++ /dev/null @@ -1,31 +0,0 @@ -package wire - -import ( - "bytes" - "crypto/rand" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// ComposeVersionNegotiation composes a Version Negotiation -func ComposeVersionNegotiation(destConnID, srcConnID protocol.ConnectionID, versions []protocol.VersionNumber) ([]byte, error) { - greasedVersions := protocol.GetGreasedVersions(versions) - expectedLen := 1 /* type byte */ + 4 /* version field */ + 1 /* connection ID length field */ + destConnID.Len() + srcConnID.Len() + len(greasedVersions)*4 - buf := bytes.NewBuffer(make([]byte, 0, expectedLen)) - r := make([]byte, 1) - _, _ = rand.Read(r) // ignore the error here. It is not critical to have perfect random here. - buf.WriteByte(r[0] | 0xc0) - utils.BigEndian.WriteUint32(buf, 0) // version 0 - connIDLen, err := encodeConnIDLen(destConnID, srcConnID) - if err != nil { - return nil, err - } - buf.WriteByte(connIDLen) - buf.Write(destConnID) - buf.Write(srcConnID) - for _, v := range greasedVersions { - utils.BigEndian.WriteUint32(buf, uint32(v)) - } - return buf.Bytes(), nil -} diff --git a/vendor/github.com/lucas-clemente/quic-go/quictrace/README.md b/vendor/github.com/lucas-clemente/quic-go/quictrace/README.md deleted file mode 100644 index ec00c5d480..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/quictrace/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# quic-trace Adapter - -This is an experimental implementation of the log format consumed by [quic-trace](https://github.com/google/quic-trace). - -At this moment, this package comes with no API stability whatsoever. diff --git a/vendor/github.com/lucas-clemente/quic-go/quictrace/interface.go b/vendor/github.com/lucas-clemente/quic-go/quictrace/interface.go deleted file mode 100644 index 561c5543b1..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/quictrace/interface.go +++ /dev/null @@ -1,50 +0,0 @@ -package quictrace - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" -) - -// A Tracer traces a QUIC connection -type Tracer interface { - Trace(protocol.ConnectionID, Event) - GetAllTraces() map[string][]byte -} - -// EventType is the type of an event -type EventType uint8 - -const ( - // PacketSent means that a packet was sent - PacketSent EventType = 1 + iota - // PacketReceived means that a packet was received - PacketReceived - // PacketLost means that a packet was lost - PacketLost -) - -// Event is a quic-traceable event -type Event struct { - Time time.Time - EventType EventType - - TransportState *TransportState - EncryptionLevel protocol.EncryptionLevel - PacketNumber protocol.PacketNumber - PacketSize protocol.ByteCount - Frames []wire.Frame -} - -// TransportState contains some transport and congestion statistics -type TransportState struct { - MinRTT time.Duration - SmoothedRTT time.Duration - LatestRTT time.Duration - - BytesInFlight protocol.ByteCount - CongestionWindow protocol.ByteCount - InSlowStart bool - InRecovery bool -} diff --git a/vendor/github.com/lucas-clemente/quic-go/quictrace/pb/quic-trace.pb.go b/vendor/github.com/lucas-clemente/quic-go/quictrace/pb/quic-trace.pb.go deleted file mode 100644 index b83e42bab0..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/quictrace/pb/quic-trace.pb.go +++ /dev/null @@ -1,1215 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: quic-trace.proto - -package pb - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -type FrameType int32 - -const ( - FrameType_UNKNOWN_FRAME FrameType = 0 - FrameType_STREAM FrameType = 1 - FrameType_ACK FrameType = 2 - FrameType_RESET_STREAM FrameType = 3 - FrameType_CONNECTION_CLOSE FrameType = 4 - FrameType_MAX_DATA FrameType = 5 - FrameType_MAX_STREAM_DATA FrameType = 6 - FrameType_PING FrameType = 7 - FrameType_BLOCKED FrameType = 8 - FrameType_STREAM_BLOCKED FrameType = 9 - FrameType_PADDING FrameType = 10 - FrameType_CRYPTO FrameType = 11 -) - -var FrameType_name = map[int32]string{ - 0: "UNKNOWN_FRAME", - 1: "STREAM", - 2: "ACK", - 3: "RESET_STREAM", - 4: "CONNECTION_CLOSE", - 5: "MAX_DATA", - 6: "MAX_STREAM_DATA", - 7: "PING", - 8: "BLOCKED", - 9: "STREAM_BLOCKED", - 10: "PADDING", - 11: "CRYPTO", -} - -var FrameType_value = map[string]int32{ - "UNKNOWN_FRAME": 0, - "STREAM": 1, - "ACK": 2, - "RESET_STREAM": 3, - "CONNECTION_CLOSE": 4, - "MAX_DATA": 5, - "MAX_STREAM_DATA": 6, - "PING": 7, - "BLOCKED": 8, - "STREAM_BLOCKED": 9, - "PADDING": 10, - "CRYPTO": 11, -} - -func (x FrameType) Enum() *FrameType { - p := new(FrameType) - *p = x - return p -} - -func (x FrameType) String() string { - return proto.EnumName(FrameType_name, int32(x)) -} - -func (x *FrameType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FrameType_value, data, "FrameType") - if err != nil { - return err - } - *x = FrameType(value) - return nil -} - -func (FrameType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{0} -} - -// Metadata for CONNECTION_CLOSE frames. -// Close_type will indicate whether the close is a Google QUIC close, -// IETF QUIC Transport CONNECTION CLOSE, or IETF QUIC Application -// Connection Close, frame. -type CloseType int32 - -const ( - CloseType_GOOGLE_QUIC_CONNECTION_CLOSE CloseType = 0 - CloseType_IETF_QUIC_TRANSPORT_CONNECTION_CLOSE CloseType = 1 - CloseType_IETF_QUIC_APPLICATION_CONNECTION_CLOSE CloseType = 2 -) - -var CloseType_name = map[int32]string{ - 0: "GOOGLE_QUIC_CONNECTION_CLOSE", - 1: "IETF_QUIC_TRANSPORT_CONNECTION_CLOSE", - 2: "IETF_QUIC_APPLICATION_CONNECTION_CLOSE", -} - -var CloseType_value = map[string]int32{ - "GOOGLE_QUIC_CONNECTION_CLOSE": 0, - "IETF_QUIC_TRANSPORT_CONNECTION_CLOSE": 1, - "IETF_QUIC_APPLICATION_CONNECTION_CLOSE": 2, -} - -func (x CloseType) Enum() *CloseType { - p := new(CloseType) - *p = x - return p -} - -func (x CloseType) String() string { - return proto.EnumName(CloseType_name, int32(x)) -} - -func (x *CloseType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(CloseType_value, data, "CloseType") - if err != nil { - return err - } - *x = CloseType(value) - return nil -} - -func (CloseType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{1} -} - -type EncryptionLevel int32 - -const ( - EncryptionLevel_ENCRYPTION_UNKNOWN EncryptionLevel = 0 - EncryptionLevel_ENCRYPTION_INITIAL EncryptionLevel = 1 - EncryptionLevel_ENCRYPTION_0RTT EncryptionLevel = 2 - EncryptionLevel_ENCRYPTION_1RTT EncryptionLevel = 3 - EncryptionLevel_ENCRYPTION_HANDSHAKE EncryptionLevel = 4 -) - -var EncryptionLevel_name = map[int32]string{ - 0: "ENCRYPTION_UNKNOWN", - 1: "ENCRYPTION_INITIAL", - 2: "ENCRYPTION_0RTT", - 3: "ENCRYPTION_1RTT", - 4: "ENCRYPTION_HANDSHAKE", -} - -var EncryptionLevel_value = map[string]int32{ - "ENCRYPTION_UNKNOWN": 0, - "ENCRYPTION_INITIAL": 1, - "ENCRYPTION_0RTT": 2, - "ENCRYPTION_1RTT": 3, - "ENCRYPTION_HANDSHAKE": 4, -} - -func (x EncryptionLevel) Enum() *EncryptionLevel { - p := new(EncryptionLevel) - *p = x - return p -} - -func (x EncryptionLevel) String() string { - return proto.EnumName(EncryptionLevel_name, int32(x)) -} - -func (x *EncryptionLevel) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(EncryptionLevel_value, data, "EncryptionLevel") - if err != nil { - return err - } - *x = EncryptionLevel(value) - return nil -} - -func (EncryptionLevel) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{2} -} - -type EventType int32 - -const ( - EventType_UNKNOWN_EVENT EventType = 0 - EventType_PACKET_SENT EventType = 1 - EventType_PACKET_RECEIVED EventType = 2 - EventType_PACKET_LOST EventType = 3 - // An APPLICATION_LIMITED event occurs when the sender is capable of sending - // more data and tries to send it, but discovers that it does not have any - // outstanding data to send. Such events are important to some congestion - // control algorithms (for example, BBR) since they are trying to measure the - // largest achievable throughput, but it is impossible to measure it when the - // application does not send anything. - EventType_APPLICATION_LIMITED EventType = 4 - // Record when external information about expected network conditions - // (available bandwidth, RTT, congestion window, etc) is supplied to the - // sender. - EventType_EXTERNAL_PARAMETERS EventType = 5 -) - -var EventType_name = map[int32]string{ - 0: "UNKNOWN_EVENT", - 1: "PACKET_SENT", - 2: "PACKET_RECEIVED", - 3: "PACKET_LOST", - 4: "APPLICATION_LIMITED", - 5: "EXTERNAL_PARAMETERS", -} - -var EventType_value = map[string]int32{ - "UNKNOWN_EVENT": 0, - "PACKET_SENT": 1, - "PACKET_RECEIVED": 2, - "PACKET_LOST": 3, - "APPLICATION_LIMITED": 4, - "EXTERNAL_PARAMETERS": 5, -} - -func (x EventType) Enum() *EventType { - p := new(EventType) - *p = x - return p -} - -func (x EventType) String() string { - return proto.EnumName(EventType_name, int32(x)) -} - -func (x *EventType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(EventType_value, data, "EventType") - if err != nil { - return err - } - *x = EventType(value) - return nil -} - -func (EventType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{3} -} - -type TransmissionReason int32 - -const ( - // Indicates that there was not any particular special reason the packet was - // sent. - TransmissionReason_NORMAL_TRANSMISSION TransmissionReason = 0 - // Indicates that the packet sent is a tail loss probe, cf. - // https://tools.ietf.org/html/draft-ietf-quic-recovery-14#section-4.3.2 - TransmissionReason_TAIL_LOSS_PROBE TransmissionReason = 1 - // Indicates that the packet is sent due to retransmission timeout, cf - // https://tools.ietf.org/html/draft-ietf-quic-recovery-14#section-4.3.3 - TransmissionReason_RTO_TRANSMISSION TransmissionReason = 2 - // Indicates that the packet is sent in order to probe whether there is extra - // bandwidth available in cases where the sender needs an estimate of - // available bandwidth, but the application does not provide enough data for - // such estimate to become naturally available. This is usually only used in - // real-time protocols. - TransmissionReason_PROBING_TRANSMISSION TransmissionReason = 3 -) - -var TransmissionReason_name = map[int32]string{ - 0: "NORMAL_TRANSMISSION", - 1: "TAIL_LOSS_PROBE", - 2: "RTO_TRANSMISSION", - 3: "PROBING_TRANSMISSION", -} - -var TransmissionReason_value = map[string]int32{ - "NORMAL_TRANSMISSION": 0, - "TAIL_LOSS_PROBE": 1, - "RTO_TRANSMISSION": 2, - "PROBING_TRANSMISSION": 3, -} - -func (x TransmissionReason) Enum() *TransmissionReason { - p := new(TransmissionReason) - *p = x - return p -} - -func (x TransmissionReason) String() string { - return proto.EnumName(TransmissionReason_name, int32(x)) -} - -func (x *TransmissionReason) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(TransmissionReason_value, data, "TransmissionReason") - if err != nil { - return err - } - *x = TransmissionReason(value) - return nil -} - -func (TransmissionReason) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{4} -} - -// Metadata for STREAM frames. -type StreamFrameInfo struct { - StreamId *uint64 `protobuf:"varint,1,opt,name=stream_id,json=streamId" json:"stream_id,omitempty"` - Fin *bool `protobuf:"varint,2,opt,name=fin" json:"fin,omitempty"` - Length *uint64 `protobuf:"varint,3,opt,name=length" json:"length,omitempty"` - Offset *uint64 `protobuf:"varint,4,opt,name=offset" json:"offset,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamFrameInfo) Reset() { *m = StreamFrameInfo{} } -func (m *StreamFrameInfo) String() string { return proto.CompactTextString(m) } -func (*StreamFrameInfo) ProtoMessage() {} -func (*StreamFrameInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{0} -} - -func (m *StreamFrameInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamFrameInfo.Unmarshal(m, b) -} -func (m *StreamFrameInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamFrameInfo.Marshal(b, m, deterministic) -} -func (m *StreamFrameInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamFrameInfo.Merge(m, src) -} -func (m *StreamFrameInfo) XXX_Size() int { - return xxx_messageInfo_StreamFrameInfo.Size(m) -} -func (m *StreamFrameInfo) XXX_DiscardUnknown() { - xxx_messageInfo_StreamFrameInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamFrameInfo proto.InternalMessageInfo - -func (m *StreamFrameInfo) GetStreamId() uint64 { - if m != nil && m.StreamId != nil { - return *m.StreamId - } - return 0 -} - -func (m *StreamFrameInfo) GetFin() bool { - if m != nil && m.Fin != nil { - return *m.Fin - } - return false -} - -func (m *StreamFrameInfo) GetLength() uint64 { - if m != nil && m.Length != nil { - return *m.Length - } - return 0 -} - -func (m *StreamFrameInfo) GetOffset() uint64 { - if m != nil && m.Offset != nil { - return *m.Offset - } - return 0 -} - -// Metadata for CRYPTO frames. -type CryptoFrameInfo struct { - Length *uint64 `protobuf:"varint,1,opt,name=length" json:"length,omitempty"` - Offset *uint64 `protobuf:"varint,2,opt,name=offset" json:"offset,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CryptoFrameInfo) Reset() { *m = CryptoFrameInfo{} } -func (m *CryptoFrameInfo) String() string { return proto.CompactTextString(m) } -func (*CryptoFrameInfo) ProtoMessage() {} -func (*CryptoFrameInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{1} -} - -func (m *CryptoFrameInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CryptoFrameInfo.Unmarshal(m, b) -} -func (m *CryptoFrameInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CryptoFrameInfo.Marshal(b, m, deterministic) -} -func (m *CryptoFrameInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_CryptoFrameInfo.Merge(m, src) -} -func (m *CryptoFrameInfo) XXX_Size() int { - return xxx_messageInfo_CryptoFrameInfo.Size(m) -} -func (m *CryptoFrameInfo) XXX_DiscardUnknown() { - xxx_messageInfo_CryptoFrameInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_CryptoFrameInfo proto.InternalMessageInfo - -func (m *CryptoFrameInfo) GetLength() uint64 { - if m != nil && m.Length != nil { - return *m.Length - } - return 0 -} - -func (m *CryptoFrameInfo) GetOffset() uint64 { - if m != nil && m.Offset != nil { - return *m.Offset - } - return 0 -} - -// The intervals are closed, i.e. the interval represented here is -// [first_packet, last_packet]. -type AckBlock struct { - FirstPacket *uint64 `protobuf:"varint,1,opt,name=first_packet,json=firstPacket" json:"first_packet,omitempty"` - LastPacket *uint64 `protobuf:"varint,2,opt,name=last_packet,json=lastPacket" json:"last_packet,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *AckBlock) Reset() { *m = AckBlock{} } -func (m *AckBlock) String() string { return proto.CompactTextString(m) } -func (*AckBlock) ProtoMessage() {} -func (*AckBlock) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{2} -} - -func (m *AckBlock) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_AckBlock.Unmarshal(m, b) -} -func (m *AckBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_AckBlock.Marshal(b, m, deterministic) -} -func (m *AckBlock) XXX_Merge(src proto.Message) { - xxx_messageInfo_AckBlock.Merge(m, src) -} -func (m *AckBlock) XXX_Size() int { - return xxx_messageInfo_AckBlock.Size(m) -} -func (m *AckBlock) XXX_DiscardUnknown() { - xxx_messageInfo_AckBlock.DiscardUnknown(m) -} - -var xxx_messageInfo_AckBlock proto.InternalMessageInfo - -func (m *AckBlock) GetFirstPacket() uint64 { - if m != nil && m.FirstPacket != nil { - return *m.FirstPacket - } - return 0 -} - -func (m *AckBlock) GetLastPacket() uint64 { - if m != nil && m.LastPacket != nil { - return *m.LastPacket - } - return 0 -} - -// Metadata for ACK frames. -type AckInfo struct { - AckedPackets []*AckBlock `protobuf:"bytes,1,rep,name=acked_packets,json=ackedPackets" json:"acked_packets,omitempty"` - AckDelayUs *uint64 `protobuf:"varint,2,opt,name=ack_delay_us,json=ackDelayUs" json:"ack_delay_us,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *AckInfo) Reset() { *m = AckInfo{} } -func (m *AckInfo) String() string { return proto.CompactTextString(m) } -func (*AckInfo) ProtoMessage() {} -func (*AckInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{3} -} - -func (m *AckInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_AckInfo.Unmarshal(m, b) -} -func (m *AckInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_AckInfo.Marshal(b, m, deterministic) -} -func (m *AckInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_AckInfo.Merge(m, src) -} -func (m *AckInfo) XXX_Size() int { - return xxx_messageInfo_AckInfo.Size(m) -} -func (m *AckInfo) XXX_DiscardUnknown() { - xxx_messageInfo_AckInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_AckInfo proto.InternalMessageInfo - -func (m *AckInfo) GetAckedPackets() []*AckBlock { - if m != nil { - return m.AckedPackets - } - return nil -} - -func (m *AckInfo) GetAckDelayUs() uint64 { - if m != nil && m.AckDelayUs != nil { - return *m.AckDelayUs - } - return 0 -} - -// Metadata for RST_STREAM frames. -type ResetStreamInfo struct { - StreamId *uint64 `protobuf:"varint,1,opt,name=stream_id,json=streamId" json:"stream_id,omitempty"` - ApplicationErrorCode *uint32 `protobuf:"varint,2,opt,name=application_error_code,json=applicationErrorCode" json:"application_error_code,omitempty"` - FinalOffset *uint64 `protobuf:"varint,3,opt,name=final_offset,json=finalOffset" json:"final_offset,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ResetStreamInfo) Reset() { *m = ResetStreamInfo{} } -func (m *ResetStreamInfo) String() string { return proto.CompactTextString(m) } -func (*ResetStreamInfo) ProtoMessage() {} -func (*ResetStreamInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{4} -} - -func (m *ResetStreamInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ResetStreamInfo.Unmarshal(m, b) -} -func (m *ResetStreamInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ResetStreamInfo.Marshal(b, m, deterministic) -} -func (m *ResetStreamInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_ResetStreamInfo.Merge(m, src) -} -func (m *ResetStreamInfo) XXX_Size() int { - return xxx_messageInfo_ResetStreamInfo.Size(m) -} -func (m *ResetStreamInfo) XXX_DiscardUnknown() { - xxx_messageInfo_ResetStreamInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_ResetStreamInfo proto.InternalMessageInfo - -func (m *ResetStreamInfo) GetStreamId() uint64 { - if m != nil && m.StreamId != nil { - return *m.StreamId - } - return 0 -} - -func (m *ResetStreamInfo) GetApplicationErrorCode() uint32 { - if m != nil && m.ApplicationErrorCode != nil { - return *m.ApplicationErrorCode - } - return 0 -} - -func (m *ResetStreamInfo) GetFinalOffset() uint64 { - if m != nil && m.FinalOffset != nil { - return *m.FinalOffset - } - return 0 -} - -// Metadata for CONNECTION_CLOSE/APPLICATION_CLOSE frames. -type CloseInfo struct { - ErrorCode *uint32 `protobuf:"varint,1,opt,name=error_code,json=errorCode" json:"error_code,omitempty"` - ReasonPhrase *string `protobuf:"bytes,2,opt,name=reason_phrase,json=reasonPhrase" json:"reason_phrase,omitempty"` - CloseType *CloseType `protobuf:"varint,3,opt,name=close_type,json=closeType,enum=pb.CloseType" json:"close_type,omitempty"` - TransportCloseFrameType *uint64 `protobuf:"varint,4,opt,name=transport_close_frame_type,json=transportCloseFrameType" json:"transport_close_frame_type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CloseInfo) Reset() { *m = CloseInfo{} } -func (m *CloseInfo) String() string { return proto.CompactTextString(m) } -func (*CloseInfo) ProtoMessage() {} -func (*CloseInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{5} -} - -func (m *CloseInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CloseInfo.Unmarshal(m, b) -} -func (m *CloseInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CloseInfo.Marshal(b, m, deterministic) -} -func (m *CloseInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_CloseInfo.Merge(m, src) -} -func (m *CloseInfo) XXX_Size() int { - return xxx_messageInfo_CloseInfo.Size(m) -} -func (m *CloseInfo) XXX_DiscardUnknown() { - xxx_messageInfo_CloseInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_CloseInfo proto.InternalMessageInfo - -func (m *CloseInfo) GetErrorCode() uint32 { - if m != nil && m.ErrorCode != nil { - return *m.ErrorCode - } - return 0 -} - -func (m *CloseInfo) GetReasonPhrase() string { - if m != nil && m.ReasonPhrase != nil { - return *m.ReasonPhrase - } - return "" -} - -func (m *CloseInfo) GetCloseType() CloseType { - if m != nil && m.CloseType != nil { - return *m.CloseType - } - return CloseType_GOOGLE_QUIC_CONNECTION_CLOSE -} - -func (m *CloseInfo) GetTransportCloseFrameType() uint64 { - if m != nil && m.TransportCloseFrameType != nil { - return *m.TransportCloseFrameType - } - return 0 -} - -// Metadata for MAX_DATA/MAX_STREAM_DATA frames. -type FlowControlInfo struct { - MaxData *uint64 `protobuf:"varint,1,opt,name=max_data,json=maxData" json:"max_data,omitempty"` - StreamId *uint64 `protobuf:"varint,2,opt,name=stream_id,json=streamId" json:"stream_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FlowControlInfo) Reset() { *m = FlowControlInfo{} } -func (m *FlowControlInfo) String() string { return proto.CompactTextString(m) } -func (*FlowControlInfo) ProtoMessage() {} -func (*FlowControlInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{6} -} - -func (m *FlowControlInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FlowControlInfo.Unmarshal(m, b) -} -func (m *FlowControlInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FlowControlInfo.Marshal(b, m, deterministic) -} -func (m *FlowControlInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_FlowControlInfo.Merge(m, src) -} -func (m *FlowControlInfo) XXX_Size() int { - return xxx_messageInfo_FlowControlInfo.Size(m) -} -func (m *FlowControlInfo) XXX_DiscardUnknown() { - xxx_messageInfo_FlowControlInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_FlowControlInfo proto.InternalMessageInfo - -func (m *FlowControlInfo) GetMaxData() uint64 { - if m != nil && m.MaxData != nil { - return *m.MaxData - } - return 0 -} - -func (m *FlowControlInfo) GetStreamId() uint64 { - if m != nil && m.StreamId != nil { - return *m.StreamId - } - return 0 -} - -// A message representing a frame, either sent or received. -type Frame struct { - FrameType *FrameType `protobuf:"varint,1,opt,name=frame_type,json=frameType,enum=pb.FrameType" json:"frame_type,omitempty"` - StreamFrameInfo *StreamFrameInfo `protobuf:"bytes,2,opt,name=stream_frame_info,json=streamFrameInfo" json:"stream_frame_info,omitempty"` - AckInfo *AckInfo `protobuf:"bytes,3,opt,name=ack_info,json=ackInfo" json:"ack_info,omitempty"` - ResetStreamInfo *ResetStreamInfo `protobuf:"bytes,4,opt,name=reset_stream_info,json=resetStreamInfo" json:"reset_stream_info,omitempty"` - CloseInfo *CloseInfo `protobuf:"bytes,5,opt,name=close_info,json=closeInfo" json:"close_info,omitempty"` - FlowControlInfo *FlowControlInfo `protobuf:"bytes,6,opt,name=flow_control_info,json=flowControlInfo" json:"flow_control_info,omitempty"` - CryptoFrameInfo *CryptoFrameInfo `protobuf:"bytes,7,opt,name=crypto_frame_info,json=cryptoFrameInfo" json:"crypto_frame_info,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Frame) Reset() { *m = Frame{} } -func (m *Frame) String() string { return proto.CompactTextString(m) } -func (*Frame) ProtoMessage() {} -func (*Frame) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{7} -} - -func (m *Frame) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Frame.Unmarshal(m, b) -} -func (m *Frame) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Frame.Marshal(b, m, deterministic) -} -func (m *Frame) XXX_Merge(src proto.Message) { - xxx_messageInfo_Frame.Merge(m, src) -} -func (m *Frame) XXX_Size() int { - return xxx_messageInfo_Frame.Size(m) -} -func (m *Frame) XXX_DiscardUnknown() { - xxx_messageInfo_Frame.DiscardUnknown(m) -} - -var xxx_messageInfo_Frame proto.InternalMessageInfo - -func (m *Frame) GetFrameType() FrameType { - if m != nil && m.FrameType != nil { - return *m.FrameType - } - return FrameType_UNKNOWN_FRAME -} - -func (m *Frame) GetStreamFrameInfo() *StreamFrameInfo { - if m != nil { - return m.StreamFrameInfo - } - return nil -} - -func (m *Frame) GetAckInfo() *AckInfo { - if m != nil { - return m.AckInfo - } - return nil -} - -func (m *Frame) GetResetStreamInfo() *ResetStreamInfo { - if m != nil { - return m.ResetStreamInfo - } - return nil -} - -func (m *Frame) GetCloseInfo() *CloseInfo { - if m != nil { - return m.CloseInfo - } - return nil -} - -func (m *Frame) GetFlowControlInfo() *FlowControlInfo { - if m != nil { - return m.FlowControlInfo - } - return nil -} - -func (m *Frame) GetCryptoFrameInfo() *CryptoFrameInfo { - if m != nil { - return m.CryptoFrameInfo - } - return nil -} - -// Metadata that represents transport stack's understanding of the current state -// of the transport channel. -type TransportState struct { - MinRttUs *uint64 `protobuf:"varint,1,opt,name=min_rtt_us,json=minRttUs" json:"min_rtt_us,omitempty"` - // Smoothed RTT, usually computed using EWMA. - SmoothedRttUs *uint64 `protobuf:"varint,2,opt,name=smoothed_rtt_us,json=smoothedRttUs" json:"smoothed_rtt_us,omitempty"` - // The latest RTT measureent available. - LastRttUs *uint64 `protobuf:"varint,3,opt,name=last_rtt_us,json=lastRttUs" json:"last_rtt_us,omitempty"` - InFlightBytes *uint64 `protobuf:"varint,4,opt,name=in_flight_bytes,json=inFlightBytes" json:"in_flight_bytes,omitempty"` - CwndBytes *uint64 `protobuf:"varint,5,opt,name=cwnd_bytes,json=cwndBytes" json:"cwnd_bytes,omitempty"` - // Pacing rate, in bits per second. - PacingRateBps *uint64 `protobuf:"varint,6,opt,name=pacing_rate_bps,json=pacingRateBps" json:"pacing_rate_bps,omitempty"` - // Any arbitrary information about congestion control state that is not - // representable via parameters above. - CongestionControlState *string `protobuf:"bytes,7,opt,name=congestion_control_state,json=congestionControlState" json:"congestion_control_state,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TransportState) Reset() { *m = TransportState{} } -func (m *TransportState) String() string { return proto.CompactTextString(m) } -func (*TransportState) ProtoMessage() {} -func (*TransportState) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{8} -} - -func (m *TransportState) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TransportState.Unmarshal(m, b) -} -func (m *TransportState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TransportState.Marshal(b, m, deterministic) -} -func (m *TransportState) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransportState.Merge(m, src) -} -func (m *TransportState) XXX_Size() int { - return xxx_messageInfo_TransportState.Size(m) -} -func (m *TransportState) XXX_DiscardUnknown() { - xxx_messageInfo_TransportState.DiscardUnknown(m) -} - -var xxx_messageInfo_TransportState proto.InternalMessageInfo - -func (m *TransportState) GetMinRttUs() uint64 { - if m != nil && m.MinRttUs != nil { - return *m.MinRttUs - } - return 0 -} - -func (m *TransportState) GetSmoothedRttUs() uint64 { - if m != nil && m.SmoothedRttUs != nil { - return *m.SmoothedRttUs - } - return 0 -} - -func (m *TransportState) GetLastRttUs() uint64 { - if m != nil && m.LastRttUs != nil { - return *m.LastRttUs - } - return 0 -} - -func (m *TransportState) GetInFlightBytes() uint64 { - if m != nil && m.InFlightBytes != nil { - return *m.InFlightBytes - } - return 0 -} - -func (m *TransportState) GetCwndBytes() uint64 { - if m != nil && m.CwndBytes != nil { - return *m.CwndBytes - } - return 0 -} - -func (m *TransportState) GetPacingRateBps() uint64 { - if m != nil && m.PacingRateBps != nil { - return *m.PacingRateBps - } - return 0 -} - -func (m *TransportState) GetCongestionControlState() string { - if m != nil && m.CongestionControlState != nil { - return *m.CongestionControlState - } - return "" -} - -// Documents external network parameters supplied to the sender. Typically not -// all of those would be supplied (e.g. if bandwidth and RTT are supplied, you -// can infer the suggested CWND), but there are no restrictions on which fields -// may or may not be set. -type ExternalNetworkParameters struct { - BandwidthBps *uint64 `protobuf:"varint,1,opt,name=bandwidth_bps,json=bandwidthBps" json:"bandwidth_bps,omitempty"` - RttUs *uint64 `protobuf:"varint,2,opt,name=rtt_us,json=rttUs" json:"rtt_us,omitempty"` - CwndBytes *uint64 `protobuf:"varint,3,opt,name=cwnd_bytes,json=cwndBytes" json:"cwnd_bytes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExternalNetworkParameters) Reset() { *m = ExternalNetworkParameters{} } -func (m *ExternalNetworkParameters) String() string { return proto.CompactTextString(m) } -func (*ExternalNetworkParameters) ProtoMessage() {} -func (*ExternalNetworkParameters) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{9} -} - -func (m *ExternalNetworkParameters) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExternalNetworkParameters.Unmarshal(m, b) -} -func (m *ExternalNetworkParameters) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExternalNetworkParameters.Marshal(b, m, deterministic) -} -func (m *ExternalNetworkParameters) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExternalNetworkParameters.Merge(m, src) -} -func (m *ExternalNetworkParameters) XXX_Size() int { - return xxx_messageInfo_ExternalNetworkParameters.Size(m) -} -func (m *ExternalNetworkParameters) XXX_DiscardUnknown() { - xxx_messageInfo_ExternalNetworkParameters.DiscardUnknown(m) -} - -var xxx_messageInfo_ExternalNetworkParameters proto.InternalMessageInfo - -func (m *ExternalNetworkParameters) GetBandwidthBps() uint64 { - if m != nil && m.BandwidthBps != nil { - return *m.BandwidthBps - } - return 0 -} - -func (m *ExternalNetworkParameters) GetRttUs() uint64 { - if m != nil && m.RttUs != nil { - return *m.RttUs - } - return 0 -} - -func (m *ExternalNetworkParameters) GetCwndBytes() uint64 { - if m != nil && m.CwndBytes != nil { - return *m.CwndBytes - } - return 0 -} - -// An event that has occurred over duration of the connection. -type Event struct { - TimeUs *uint64 `protobuf:"varint,1,opt,name=time_us,json=timeUs" json:"time_us,omitempty"` - EventType *EventType `protobuf:"varint,2,opt,name=event_type,json=eventType,enum=pb.EventType" json:"event_type,omitempty"` - PacketNumber *uint64 `protobuf:"varint,3,opt,name=packet_number,json=packetNumber" json:"packet_number,omitempty"` - Frames []*Frame `protobuf:"bytes,4,rep,name=frames" json:"frames,omitempty"` - PacketSize *uint64 `protobuf:"varint,5,opt,name=packet_size,json=packetSize" json:"packet_size,omitempty"` - EncryptionLevel *EncryptionLevel `protobuf:"varint,6,opt,name=encryption_level,json=encryptionLevel,enum=pb.EncryptionLevel" json:"encryption_level,omitempty"` - // State of the transport stack after the event has happened. - TransportState *TransportState `protobuf:"bytes,7,opt,name=transport_state,json=transportState" json:"transport_state,omitempty"` - // For event_type = EXTERNAL_PARAMETERS, record parameters specified. - ExternalNetworkParameters *ExternalNetworkParameters `protobuf:"bytes,8,opt,name=external_network_parameters,json=externalNetworkParameters" json:"external_network_parameters,omitempty"` - // For sent packets, indicate if there is a special reason for why the packet - // in question was transmitted. - TransmissionReason *TransmissionReason `protobuf:"varint,9,opt,name=transmission_reason,json=transmissionReason,enum=pb.TransmissionReason,def=0" json:"transmission_reason,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Event) Reset() { *m = Event{} } -func (m *Event) String() string { return proto.CompactTextString(m) } -func (*Event) ProtoMessage() {} -func (*Event) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{10} -} - -func (m *Event) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Event.Unmarshal(m, b) -} -func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Event.Marshal(b, m, deterministic) -} -func (m *Event) XXX_Merge(src proto.Message) { - xxx_messageInfo_Event.Merge(m, src) -} -func (m *Event) XXX_Size() int { - return xxx_messageInfo_Event.Size(m) -} -func (m *Event) XXX_DiscardUnknown() { - xxx_messageInfo_Event.DiscardUnknown(m) -} - -var xxx_messageInfo_Event proto.InternalMessageInfo - -const Default_Event_TransmissionReason TransmissionReason = TransmissionReason_NORMAL_TRANSMISSION - -func (m *Event) GetTimeUs() uint64 { - if m != nil && m.TimeUs != nil { - return *m.TimeUs - } - return 0 -} - -func (m *Event) GetEventType() EventType { - if m != nil && m.EventType != nil { - return *m.EventType - } - return EventType_UNKNOWN_EVENT -} - -func (m *Event) GetPacketNumber() uint64 { - if m != nil && m.PacketNumber != nil { - return *m.PacketNumber - } - return 0 -} - -func (m *Event) GetFrames() []*Frame { - if m != nil { - return m.Frames - } - return nil -} - -func (m *Event) GetPacketSize() uint64 { - if m != nil && m.PacketSize != nil { - return *m.PacketSize - } - return 0 -} - -func (m *Event) GetEncryptionLevel() EncryptionLevel { - if m != nil && m.EncryptionLevel != nil { - return *m.EncryptionLevel - } - return EncryptionLevel_ENCRYPTION_UNKNOWN -} - -func (m *Event) GetTransportState() *TransportState { - if m != nil { - return m.TransportState - } - return nil -} - -func (m *Event) GetExternalNetworkParameters() *ExternalNetworkParameters { - if m != nil { - return m.ExternalNetworkParameters - } - return nil -} - -func (m *Event) GetTransmissionReason() TransmissionReason { - if m != nil && m.TransmissionReason != nil { - return *m.TransmissionReason - } - return Default_Event_TransmissionReason -} - -type Trace struct { - // QUIC version tag, as represented on wire. Should be always 4 bytes long. - ProtocolVersion []byte `protobuf:"bytes,1,opt,name=protocol_version,json=protocolVersion" json:"protocol_version,omitempty"` - // Source and destination connection ID. If multiple connection IDs are used, - // record the first one used with short-form header. - SourceConnectionId []byte `protobuf:"bytes,2,opt,name=source_connection_id,json=sourceConnectionId" json:"source_connection_id,omitempty"` - DestinationConnectionId []byte `protobuf:"bytes,3,opt,name=destination_connection_id,json=destinationConnectionId" json:"destination_connection_id,omitempty"` - Events []*Event `protobuf:"bytes,4,rep,name=events" json:"events,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Trace) Reset() { *m = Trace{} } -func (m *Trace) String() string { return proto.CompactTextString(m) } -func (*Trace) ProtoMessage() {} -func (*Trace) Descriptor() ([]byte, []int) { - return fileDescriptor_79ecf15e0416742d, []int{11} -} - -func (m *Trace) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Trace.Unmarshal(m, b) -} -func (m *Trace) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Trace.Marshal(b, m, deterministic) -} -func (m *Trace) XXX_Merge(src proto.Message) { - xxx_messageInfo_Trace.Merge(m, src) -} -func (m *Trace) XXX_Size() int { - return xxx_messageInfo_Trace.Size(m) -} -func (m *Trace) XXX_DiscardUnknown() { - xxx_messageInfo_Trace.DiscardUnknown(m) -} - -var xxx_messageInfo_Trace proto.InternalMessageInfo - -func (m *Trace) GetProtocolVersion() []byte { - if m != nil { - return m.ProtocolVersion - } - return nil -} - -func (m *Trace) GetSourceConnectionId() []byte { - if m != nil { - return m.SourceConnectionId - } - return nil -} - -func (m *Trace) GetDestinationConnectionId() []byte { - if m != nil { - return m.DestinationConnectionId - } - return nil -} - -func (m *Trace) GetEvents() []*Event { - if m != nil { - return m.Events - } - return nil -} - -func init() { - proto.RegisterEnum("pb.FrameType", FrameType_name, FrameType_value) - proto.RegisterEnum("pb.CloseType", CloseType_name, CloseType_value) - proto.RegisterEnum("pb.EncryptionLevel", EncryptionLevel_name, EncryptionLevel_value) - proto.RegisterEnum("pb.EventType", EventType_name, EventType_value) - proto.RegisterEnum("pb.TransmissionReason", TransmissionReason_name, TransmissionReason_value) - proto.RegisterType((*StreamFrameInfo)(nil), "pb.StreamFrameInfo") - proto.RegisterType((*CryptoFrameInfo)(nil), "pb.CryptoFrameInfo") - proto.RegisterType((*AckBlock)(nil), "pb.AckBlock") - proto.RegisterType((*AckInfo)(nil), "pb.AckInfo") - proto.RegisterType((*ResetStreamInfo)(nil), "pb.ResetStreamInfo") - proto.RegisterType((*CloseInfo)(nil), "pb.CloseInfo") - proto.RegisterType((*FlowControlInfo)(nil), "pb.FlowControlInfo") - proto.RegisterType((*Frame)(nil), "pb.Frame") - proto.RegisterType((*TransportState)(nil), "pb.TransportState") - proto.RegisterType((*ExternalNetworkParameters)(nil), "pb.ExternalNetworkParameters") - proto.RegisterType((*Event)(nil), "pb.Event") - proto.RegisterType((*Trace)(nil), "pb.Trace") -} - -func init() { proto.RegisterFile("quic-trace.proto", fileDescriptor_79ecf15e0416742d) } - -var fileDescriptor_79ecf15e0416742d = []byte{ - // 1432 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x56, 0xdd, 0x6e, 0xe3, 0x44, - 0x14, 0xae, 0xf3, 0x9f, 0x93, 0xa4, 0x76, 0xa7, 0xa5, 0x4d, 0xd9, 0x5d, 0xe8, 0x06, 0x54, 0x95, - 0x0a, 0x56, 0xbb, 0x15, 0x17, 0x68, 0x57, 0x62, 0xe5, 0x26, 0x6e, 0xd7, 0x6a, 0x6a, 0x87, 0x89, - 0xbb, 0x2c, 0x12, 0x30, 0x72, 0x9d, 0x49, 0x6b, 0xd5, 0xb1, 0x8d, 0x3d, 0x6d, 0xb7, 0x7b, 0x8b, - 0xd0, 0x5e, 0xf2, 0x08, 0xbc, 0x07, 0x97, 0xf0, 0x44, 0xbc, 0x01, 0x9a, 0x19, 0x3b, 0x7f, 0x65, - 0xc5, 0x9d, 0xe7, 0x3b, 0xdf, 0xf9, 0x99, 0xef, 0x9c, 0x33, 0x09, 0x68, 0xbf, 0x5c, 0xfb, 0xde, - 0x57, 0x2c, 0x71, 0x3d, 0xfa, 0x24, 0x4e, 0x22, 0x16, 0xa1, 0x42, 0x7c, 0xde, 0x89, 0x41, 0x1d, - 0xb2, 0x84, 0xba, 0x93, 0xa3, 0xc4, 0x9d, 0x50, 0x33, 0x1c, 0x47, 0xe8, 0x01, 0xd4, 0x53, 0x01, - 0x11, 0x7f, 0xd4, 0x56, 0x76, 0x94, 0xbd, 0x12, 0xae, 0x49, 0xc0, 0x1c, 0x21, 0x0d, 0x8a, 0x63, - 0x3f, 0x6c, 0x17, 0x76, 0x94, 0xbd, 0x1a, 0xe6, 0x9f, 0x68, 0x13, 0x2a, 0x01, 0x0d, 0x2f, 0xd8, - 0x65, 0xbb, 0x28, 0xb8, 0xd9, 0x89, 0xe3, 0xd1, 0x78, 0x9c, 0x52, 0xd6, 0x2e, 0x49, 0x5c, 0x9e, - 0x3a, 0x3a, 0xa8, 0xdd, 0xe4, 0x2e, 0x66, 0xd1, 0x2c, 0xe3, 0x2c, 0x84, 0xf2, 0x81, 0x10, 0x85, - 0x85, 0x10, 0x16, 0xd4, 0x74, 0xef, 0xea, 0x30, 0x88, 0xbc, 0x2b, 0xf4, 0x18, 0x9a, 0x63, 0x3f, - 0x49, 0x19, 0x89, 0x5d, 0xef, 0x8a, 0xb2, 0x2c, 0x42, 0x43, 0x60, 0x03, 0x01, 0xa1, 0x4f, 0xa1, - 0x11, 0xb8, 0x33, 0x86, 0x8c, 0x05, 0x1c, 0x92, 0x84, 0xce, 0xcf, 0x50, 0xd5, 0xbd, 0x2b, 0x51, - 0xca, 0x33, 0x68, 0x71, 0x6c, 0x94, 0x91, 0xd3, 0xb6, 0xb2, 0x53, 0xdc, 0x6b, 0x1c, 0x34, 0x9f, - 0xc4, 0xe7, 0x4f, 0xf2, 0x9c, 0xb8, 0x29, 0x28, 0xd2, 0x39, 0x45, 0x3b, 0xc0, 0xcf, 0x64, 0x44, - 0x03, 0xf7, 0x8e, 0x5c, 0xa7, 0x79, 0x7c, 0xd7, 0xbb, 0xea, 0x71, 0xe8, 0x2c, 0xed, 0xbc, 0x57, - 0x40, 0xc5, 0x34, 0xa5, 0x4c, 0x4a, 0xfd, 0xff, 0x2a, 0x7f, 0x0d, 0x9b, 0x6e, 0x1c, 0x07, 0xbe, - 0xe7, 0x32, 0x3f, 0x0a, 0x09, 0x4d, 0x92, 0x28, 0x21, 0x5e, 0x34, 0xa2, 0x22, 0x78, 0x0b, 0x6f, - 0xcc, 0x59, 0x0d, 0x6e, 0xec, 0x46, 0x23, 0x2a, 0xa5, 0x08, 0xdd, 0x80, 0x64, 0xa2, 0x15, 0x73, - 0x29, 0x42, 0x37, 0xb0, 0xa5, 0x72, 0x7f, 0x2a, 0x50, 0xef, 0x06, 0x51, 0x2a, 0x75, 0x7f, 0x04, - 0x30, 0x17, 0x5a, 0x11, 0xa1, 0xeb, 0x74, 0x1a, 0xef, 0x33, 0x68, 0x25, 0xd4, 0x4d, 0xa3, 0x90, - 0xc4, 0x97, 0x89, 0x9b, 0xca, 0xe4, 0x75, 0xdc, 0x94, 0xe0, 0x40, 0x60, 0xe8, 0x4b, 0x00, 0x8f, - 0x07, 0x24, 0xec, 0x2e, 0xa6, 0x22, 0xe5, 0xea, 0x41, 0x8b, 0xab, 0x25, 0xd2, 0x38, 0x77, 0x31, - 0xc5, 0x75, 0x2f, 0xff, 0x44, 0x2f, 0xe0, 0x63, 0x96, 0xb8, 0x61, 0x1a, 0x47, 0x09, 0x23, 0xd2, - 0x6f, 0xcc, 0xc7, 0x40, 0x7a, 0xcb, 0x41, 0xd9, 0x9a, 0x32, 0x44, 0x08, 0x31, 0x26, 0xdc, 0xb9, - 0x63, 0x82, 0x7a, 0x14, 0x44, 0xb7, 0xdd, 0x28, 0x64, 0x49, 0x14, 0x88, 0x1b, 0x6c, 0x43, 0x6d, - 0xe2, 0xbe, 0x25, 0x23, 0x97, 0xb9, 0x99, 0x88, 0xd5, 0x89, 0xfb, 0xb6, 0xe7, 0x32, 0x77, 0x51, - 0xe0, 0xc2, 0xa2, 0xc0, 0x9d, 0xdf, 0x8b, 0x50, 0x16, 0x81, 0x79, 0xfd, 0x73, 0x15, 0x28, 0xb3, - 0xfa, 0xa7, 0x79, 0x71, 0x7d, 0x9c, 0x7f, 0xa2, 0x97, 0xb0, 0x96, 0x05, 0x95, 0x4e, 0x7e, 0x38, - 0x8e, 0x44, 0xf0, 0xc6, 0xc1, 0x3a, 0x77, 0x5a, 0xda, 0x25, 0xac, 0xa6, 0x4b, 0xcb, 0xb5, 0x0b, - 0x35, 0x3e, 0x2c, 0xc2, 0xaf, 0x28, 0xfc, 0x1a, 0xd9, 0x68, 0x09, 0x7e, 0xd5, 0xcd, 0xe6, 0xf0, - 0x25, 0xac, 0x25, 0x7c, 0x62, 0x48, 0x7e, 0x07, 0xee, 0x50, 0x9a, 0x25, 0x5a, 0x1a, 0x27, 0xac, - 0x26, 0x4b, 0xf3, 0x35, 0xed, 0x8b, 0xf0, 0x2c, 0x0b, 0xcf, 0x59, 0x5f, 0x84, 0x8f, 0xec, 0x4b, - 0x9e, 0x6e, 0x1c, 0x44, 0xb7, 0xc4, 0x93, 0xda, 0x4a, 0xa7, 0xca, 0x2c, 0xdd, 0x92, 0xee, 0x58, - 0x1d, 0x2f, 0x35, 0xe2, 0x25, 0xac, 0x79, 0x62, 0xab, 0xe7, 0x85, 0xa9, 0xce, 0x02, 0x2c, 0xad, - 0x3c, 0x56, 0xbd, 0x45, 0xa0, 0xf3, 0x47, 0x01, 0x56, 0x9d, 0xbc, 0xf1, 0x43, 0xe6, 0x32, 0x8a, - 0x1e, 0x02, 0x4c, 0xfc, 0x90, 0x24, 0x8c, 0xf1, 0xb5, 0xca, 0x76, 0x64, 0xe2, 0x87, 0x98, 0xb1, - 0xb3, 0x14, 0xed, 0x82, 0x9a, 0x4e, 0xa2, 0x88, 0x5d, 0xd2, 0x51, 0x4e, 0x91, 0x5d, 0x6e, 0xe5, - 0xb0, 0xe4, 0x7d, 0x92, 0x6d, 0x7f, 0xc6, 0x91, 0x4b, 0x51, 0xe7, 0xd0, 0x34, 0x8e, 0x1f, 0x92, - 0x71, 0xe0, 0x5f, 0x5c, 0x32, 0x72, 0x7e, 0xc7, 0x68, 0x9a, 0xcd, 0x61, 0xcb, 0x0f, 0x8f, 0x04, - 0x7a, 0xc8, 0x41, 0xbe, 0x2c, 0xde, 0x6d, 0x38, 0xca, 0x28, 0x65, 0x19, 0x86, 0x23, 0xd2, 0xbc, - 0x0b, 0x6a, 0xec, 0x7a, 0x7e, 0x78, 0x41, 0x12, 0x97, 0x51, 0x72, 0x1e, 0xa7, 0x42, 0xbf, 0x12, - 0x6e, 0x49, 0x18, 0xbb, 0x8c, 0x1e, 0xc6, 0x29, 0xfa, 0x06, 0xda, 0x5e, 0x14, 0x5e, 0xd0, 0x54, - 0x6c, 0x76, 0xae, 0x77, 0xca, 0x2f, 0x2c, 0xf4, 0xaa, 0xe3, 0xcd, 0x99, 0x3d, 0x53, 0x58, 0xc8, - 0xd1, 0xb9, 0x81, 0x6d, 0xe3, 0x2d, 0xa3, 0x49, 0xe8, 0x06, 0x16, 0x65, 0xb7, 0x51, 0x72, 0x35, - 0x70, 0xb9, 0x7c, 0x8c, 0x26, 0x29, 0xdf, 0xd5, 0x73, 0x37, 0x1c, 0xdd, 0xfa, 0x23, 0x76, 0x29, - 0x92, 0x4b, 0xb9, 0x9a, 0x53, 0x90, 0xe7, 0xfe, 0x08, 0x2a, 0x0b, 0x4a, 0x95, 0x13, 0xa1, 0xc0, - 0xe2, 0xcd, 0x8a, 0x4b, 0x37, 0xeb, 0xfc, 0x53, 0x84, 0xb2, 0x71, 0x43, 0x43, 0x86, 0xb6, 0xa0, - 0xca, 0xfc, 0x09, 0x9d, 0x75, 0xa3, 0xc2, 0x8f, 0x67, 0x29, 0x1f, 0x36, 0xca, 0x19, 0x72, 0x89, - 0x0a, 0xb3, 0x25, 0x12, 0x7e, 0x72, 0x89, 0x68, 0xfe, 0xc9, 0x6b, 0x95, 0xaf, 0x2b, 0x09, 0xaf, - 0x27, 0xe7, 0x34, 0xc9, 0x52, 0x36, 0x25, 0x68, 0x09, 0x0c, 0x3d, 0x86, 0x8a, 0x98, 0x24, 0xde, - 0x0d, 0xfe, 0x02, 0xd7, 0xa7, 0x3b, 0x89, 0x33, 0x03, 0x7f, 0xd7, 0xb3, 0x38, 0xa9, 0xff, 0x8e, - 0x66, 0x2d, 0x01, 0x09, 0x0d, 0xfd, 0x77, 0x14, 0x7d, 0x0b, 0x1a, 0x0d, 0xc5, 0xa0, 0x71, 0xad, - 0x03, 0x7a, 0x43, 0x03, 0xd1, 0x94, 0x55, 0x39, 0x93, 0xc6, 0xd4, 0xd6, 0xe7, 0x26, 0xac, 0xd2, - 0x45, 0x00, 0xbd, 0x00, 0x75, 0xf6, 0x5a, 0xcd, 0x5a, 0xd4, 0x38, 0x40, 0xdc, 0x7d, 0x71, 0x5a, - 0xf1, 0x2a, 0x5b, 0x9c, 0xde, 0x9f, 0xe0, 0x01, 0xcd, 0xda, 0x45, 0x42, 0xd9, 0x2f, 0x12, 0x4f, - 0x1b, 0xd6, 0xae, 0x89, 0x40, 0x8f, 0x44, 0x1d, 0x1f, 0xea, 0x2a, 0xde, 0xa6, 0x1f, 0x6c, 0xf8, - 0x8f, 0xb0, 0x2e, 0x12, 0x4e, 0xfc, 0x34, 0xe5, 0xb7, 0x93, 0x8f, 0x72, 0xbb, 0x2e, 0xae, 0xb7, - 0x39, 0xad, 0x2f, 0x33, 0x63, 0x61, 0x7d, 0xbe, 0x6e, 0xd9, 0xf8, 0x54, 0xef, 0x13, 0x07, 0xeb, - 0xd6, 0xf0, 0xd4, 0x1c, 0x0e, 0x4d, 0xdb, 0xc2, 0x88, 0xdd, 0x23, 0x76, 0xfe, 0x56, 0xa0, 0xec, - 0xf0, 0xbf, 0x0a, 0xe8, 0x0b, 0xd0, 0xc4, 0xbf, 0x05, 0x2f, 0x0a, 0xc8, 0x0d, 0x4d, 0x38, 0x47, - 0x34, 0xbf, 0x89, 0xd5, 0x1c, 0x7f, 0x2d, 0x61, 0xf4, 0x14, 0x36, 0xd2, 0xe8, 0x3a, 0xf1, 0x28, - 0x1f, 0xeb, 0x90, 0x7a, 0x42, 0xf5, 0xec, 0xf1, 0x6d, 0x62, 0x24, 0x6d, 0xdd, 0xa9, 0xc9, 0x1c, - 0xa1, 0xe7, 0xb0, 0x3d, 0xe2, 0x93, 0x1e, 0xba, 0xf9, 0x36, 0xcc, 0xb9, 0x15, 0x85, 0xdb, 0xd6, - 0x1c, 0x61, 0xc1, 0xf7, 0x31, 0x54, 0xc4, 0x48, 0x2d, 0x0c, 0x88, 0x98, 0x37, 0x9c, 0x19, 0xf6, - 0xff, 0x52, 0xa0, 0x3e, 0x7d, 0xc6, 0xd1, 0x1a, 0xb4, 0xce, 0xac, 0x13, 0xcb, 0xfe, 0xde, 0x22, - 0x47, 0x58, 0x3f, 0x35, 0xb4, 0x15, 0x04, 0x50, 0x19, 0x3a, 0xd8, 0xd0, 0x4f, 0x35, 0x05, 0x55, - 0xa1, 0xa8, 0x77, 0x4f, 0xb4, 0x02, 0xd2, 0xa0, 0x89, 0x8d, 0xa1, 0xe1, 0x90, 0xcc, 0x54, 0x44, - 0x1b, 0xa0, 0x75, 0x6d, 0xcb, 0x32, 0xba, 0x8e, 0x69, 0x5b, 0xa4, 0xdb, 0xb7, 0x87, 0x86, 0x56, - 0x42, 0x4d, 0xa8, 0x9d, 0xea, 0x6f, 0x48, 0x4f, 0x77, 0x74, 0xad, 0x8c, 0xd6, 0x41, 0xe5, 0x27, - 0xe9, 0x23, 0xc1, 0x0a, 0xaa, 0x41, 0x69, 0x60, 0x5a, 0xc7, 0x5a, 0x15, 0x35, 0xa0, 0x7a, 0xd8, - 0xb7, 0xbb, 0x27, 0x46, 0x4f, 0xab, 0x21, 0x04, 0xab, 0x19, 0x2f, 0xc7, 0xea, 0x9c, 0x30, 0xd0, - 0x7b, 0x3d, 0xce, 0x06, 0x5e, 0x57, 0x17, 0xff, 0x30, 0x70, 0x6c, 0xad, 0xb1, 0xff, 0x6b, 0xfe, - 0x93, 0x2d, 0x2e, 0xb1, 0x03, 0x0f, 0x8f, 0x6d, 0xfb, 0xb8, 0x6f, 0x90, 0xef, 0xce, 0xcc, 0x2e, - 0xb9, 0x57, 0xd6, 0x0a, 0xda, 0x83, 0xcf, 0x4d, 0xc3, 0x39, 0x92, 0x76, 0xd1, 0xe8, 0x81, 0x8d, - 0x9d, 0xfb, 0x4c, 0x05, 0xed, 0xc3, 0xee, 0x8c, 0xa9, 0x0f, 0x06, 0x7d, 0xb3, 0xab, 0x4b, 0xc2, - 0x32, 0xb7, 0xb0, 0xff, 0x9b, 0x02, 0xea, 0xd2, 0xbe, 0xa0, 0x4d, 0x40, 0x86, 0x25, 0xea, 0xe4, - 0xcc, 0x4c, 0x5b, 0x6d, 0x65, 0x09, 0x37, 0x2d, 0xd3, 0x31, 0xf5, 0xbe, 0xa6, 0x70, 0x89, 0xe6, - 0xf0, 0xa7, 0xd8, 0x71, 0xb4, 0xc2, 0x12, 0xf8, 0x8c, 0x83, 0x45, 0xd4, 0x86, 0x8d, 0x39, 0xf0, - 0x95, 0x6e, 0xf5, 0x86, 0xaf, 0xf4, 0x13, 0x43, 0x2b, 0xed, 0xbf, 0x57, 0xa0, 0x3e, 0x7d, 0x54, - 0xe6, 0x5b, 0x6a, 0xbc, 0x36, 0x2c, 0x47, 0x5b, 0x41, 0x2a, 0x34, 0x06, 0x7a, 0xf7, 0x84, 0xb7, - 0x8f, 0x03, 0x22, 0x6b, 0x06, 0x60, 0xa3, 0x6b, 0x98, 0xaf, 0x8d, 0x9e, 0x56, 0x98, 0x63, 0xf5, - 0xed, 0x21, 0xcf, 0xb8, 0x05, 0xeb, 0xf3, 0x0a, 0xf4, 0xcd, 0x53, 0xd3, 0x31, 0x7a, 0x5a, 0x89, - 0x1b, 0x8c, 0x37, 0x8e, 0x81, 0x2d, 0xbd, 0x4f, 0x06, 0x3a, 0x9f, 0x1b, 0xc7, 0xc0, 0x43, 0xad, - 0xbc, 0x9f, 0x00, 0xba, 0xbf, 0x61, 0x9c, 0xfe, 0x1f, 0x3b, 0xa6, 0xad, 0xf0, 0x32, 0x1c, 0xdd, - 0xec, 0xf3, 0x7c, 0x43, 0x32, 0xc0, 0xf6, 0x21, 0xef, 0xc0, 0x06, 0x68, 0xd8, 0xb1, 0x17, 0xa9, - 0x05, 0x7e, 0x7b, 0x4e, 0x30, 0xad, 0xe3, 0x45, 0x4b, 0xf1, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, - 0x4a, 0x0f, 0xb7, 0x51, 0xc4, 0x0b, 0x00, 0x00, -} diff --git a/vendor/github.com/lucas-clemente/quic-go/quictrace/pb/quic-trace.proto b/vendor/github.com/lucas-clemente/quic-go/quictrace/pb/quic-trace.proto deleted file mode 100644 index 3fa47d596a..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/quictrace/pb/quic-trace.proto +++ /dev/null @@ -1,204 +0,0 @@ -// copied from https://github.com/google/quic-trace/ -// Only changed the package name. - -syntax = "proto2"; - -package pb; - -enum FrameType { - UNKNOWN_FRAME = 0; - - STREAM = 1; - ACK = 2; - RESET_STREAM = 3; - CONNECTION_CLOSE = 4; - MAX_DATA = 5; - MAX_STREAM_DATA = 6; - PING = 7; - BLOCKED = 8; - STREAM_BLOCKED = 9; - PADDING = 10; - CRYPTO = 11; -}; - -// Metadata for STREAM frames. -message StreamFrameInfo { - optional uint64 stream_id = 1; - optional bool fin = 2; - optional uint64 length = 3; - optional uint64 offset = 4; -}; - -// Metadata for CRYPTO frames. -message CryptoFrameInfo { - optional uint64 length = 1; - optional uint64 offset = 2; -} - -// The intervals are closed, i.e. the interval represented here is -// [first_packet, last_packet]. -message AckBlock { - optional uint64 first_packet = 1; - optional uint64 last_packet = 2; -}; - -// Metadata for ACK frames. -message AckInfo { - repeated AckBlock acked_packets = 1; - optional uint64 ack_delay_us = 2; -}; - -// Metadata for RST_STREAM frames. -message ResetStreamInfo { - optional uint64 stream_id = 1; - optional uint32 application_error_code = 2; - optional uint64 final_offset = 3; -}; - -// Metadata for CONNECTION_CLOSE frames. -// Close_type will indicate whether the close is a Google QUIC close, -// IETF QUIC Transport CONNECTION CLOSE, or IETF QUIC Application -// Connection Close, frame. -enum CloseType { - GOOGLE_QUIC_CONNECTION_CLOSE = 0; - IETF_QUIC_TRANSPORT_CONNECTION_CLOSE = 1; - IETF_QUIC_APPLICATION_CONNECTION_CLOSE = 2; -}; - -// Metadata for CONNECTION_CLOSE/APPLICATION_CLOSE frames. -message CloseInfo { - optional uint32 error_code = 1; - optional string reason_phrase = 2; - optional CloseType close_type = 3; - optional uint64 transport_close_frame_type = 4; -}; - -// Metadata for MAX_DATA/MAX_STREAM_DATA frames. -message FlowControlInfo { - optional uint64 max_data = 1; - optional uint64 stream_id = 2; -}; - -// A message representing a frame, either sent or received. -message Frame { - optional FrameType frame_type = 1; - - optional StreamFrameInfo stream_frame_info = 2; - optional AckInfo ack_info = 3; - optional ResetStreamInfo reset_stream_info = 4; - optional CloseInfo close_info = 5; - optional FlowControlInfo flow_control_info = 6; - optional CryptoFrameInfo crypto_frame_info = 7; -}; - -// Metadata that represents transport stack's understanding of the current state -// of the transport channel. -message TransportState { - optional uint64 min_rtt_us = 1; - // Smoothed RTT, usually computed using EWMA. - optional uint64 smoothed_rtt_us = 2; - // The latest RTT measureent available. - optional uint64 last_rtt_us = 3; - - optional uint64 in_flight_bytes = 4; - optional uint64 cwnd_bytes = 5; - // Pacing rate, in bits per second. - optional uint64 pacing_rate_bps = 6; - - // Any arbitrary information about congestion control state that is not - // representable via parameters above. - optional string congestion_control_state = 7; -}; - -// Documents external network parameters supplied to the sender. Typically not -// all of those would be supplied (e.g. if bandwidth and RTT are supplied, you -// can infer the suggested CWND), but there are no restrictions on which fields -// may or may not be set. -message ExternalNetworkParameters { - optional uint64 bandwidth_bps = 1; // in bits per second - optional uint64 rtt_us = 2; - optional uint64 cwnd_bytes = 3; -}; - -enum EncryptionLevel { - ENCRYPTION_UNKNOWN = 0; - - ENCRYPTION_INITIAL = 1; - ENCRYPTION_0RTT = 2; - ENCRYPTION_1RTT = 3; - ENCRYPTION_HANDSHAKE = 4; -}; - -enum EventType { - UNKNOWN_EVENT = 0; - - PACKET_SENT = 1; - PACKET_RECEIVED = 2; - PACKET_LOST = 3; - - // An APPLICATION_LIMITED event occurs when the sender is capable of sending - // more data and tries to send it, but discovers that it does not have any - // outstanding data to send. Such events are important to some congestion - // control algorithms (for example, BBR) since they are trying to measure the - // largest achievable throughput, but it is impossible to measure it when the - // application does not send anything. - APPLICATION_LIMITED = 4; - - // Record when external information about expected network conditions - // (available bandwidth, RTT, congestion window, etc) is supplied to the - // sender. - EXTERNAL_PARAMETERS = 5; -}; - -enum TransmissionReason { - // Indicates that there was not any particular special reason the packet was - // sent. - NORMAL_TRANSMISSION = 0; - - // Indicates that the packet sent is a tail loss probe, cf. - // https://tools.ietf.org/html/draft-ietf-quic-recovery-14#section-4.3.2 - TAIL_LOSS_PROBE = 1; - - // Indicates that the packet is sent due to retransmission timeout, cf - // https://tools.ietf.org/html/draft-ietf-quic-recovery-14#section-4.3.3 - RTO_TRANSMISSION = 2; - - // Indicates that the packet is sent in order to probe whether there is extra - // bandwidth available in cases where the sender needs an estimate of - // available bandwidth, but the application does not provide enough data for - // such estimate to become naturally available. This is usually only used in - // real-time protocols. - PROBING_TRANSMISSION = 3; -}; - -// An event that has occurred over duration of the connection. -message Event { - optional uint64 time_us = 1; - optional EventType event_type = 2; - - optional uint64 packet_number = 3; - repeated Frame frames = 4; - optional uint64 packet_size = 5; - optional EncryptionLevel encryption_level = 6; - // State of the transport stack after the event has happened. - optional TransportState transport_state = 7; - // For event_type = EXTERNAL_PARAMETERS, record parameters specified. - optional ExternalNetworkParameters external_network_parameters = 8; - - // For sent packets, indicate if there is a special reason for why the packet - // in question was transmitted. - optional TransmissionReason transmission_reason = 9 - [default = NORMAL_TRANSMISSION]; -}; - -message Trace { - // QUIC version tag, as represented on wire. Should be always 4 bytes long. - optional bytes protocol_version = 1; - - // Source and destination connection ID. If multiple connection IDs are used, - // record the first one used with short-form header. - optional bytes source_connection_id = 2; - optional bytes destination_connection_id = 3; - - repeated Event events = 4; -}; diff --git a/vendor/github.com/lucas-clemente/quic-go/quictrace/tracer.go b/vendor/github.com/lucas-clemente/quic-go/quictrace/tracer.go deleted file mode 100644 index c74404bd6c..0000000000 --- a/vendor/github.com/lucas-clemente/quic-go/quictrace/tracer.go +++ /dev/null @@ -1,201 +0,0 @@ -package quictrace - -import ( - "fmt" - "time" - - "github.com/golang/protobuf/proto" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - "github.com/lucas-clemente/quic-go/quictrace/pb" -) - -type traceEvent struct { - connID protocol.ConnectionID - ev Event -} - -// A tracer is used to trace a QUIC connection -type tracer struct { - eventQueue chan traceEvent - - events map[string] /* conn ID */ []traceEvent -} - -var _ Tracer = &tracer{} - -// NewTracer creates a new Tracer -func NewTracer() Tracer { - qt := &tracer{ - eventQueue: make(chan traceEvent, 1<<10), - events: make(map[string][]traceEvent), - } - go qt.run() - return qt -} - -// Trace traces an event -func (t *tracer) Trace(connID protocol.ConnectionID, ev Event) { - t.eventQueue <- traceEvent{connID: connID, ev: ev} -} - -func (t *tracer) run() { - for tev := range t.eventQueue { - key := string(tev.connID) - if _, ok := t.events[key]; !ok { - t.events[key] = make([]traceEvent, 0, 10*1<<10) - } - t.events[key] = append(t.events[key], tev) - } -} - -func (t *tracer) GetAllTraces() map[string][]byte { - traces := make(map[string][]byte) - for connID := range t.events { - data, err := t.emitByConnIDAsString(connID) - if err != nil { - panic(err) - } - traces[connID] = data - } - return traces -} - -// Emit emits the serialized protobuf that will be consumed by quic-trace -func (t *tracer) Emit(connID protocol.ConnectionID) ([]byte, error) { - return t.emitByConnIDAsString(string(connID)) -} - -func (t *tracer) emitByConnIDAsString(connID string) ([]byte, error) { - events, ok := t.events[connID] - if !ok { - return nil, fmt.Errorf("No trace found for connection ID %s", connID) - } - trace := &pb.Trace{ - DestinationConnectionId: []byte{1, 2, 3, 4, 5, 6, 7, 8}, - SourceConnectionId: []byte{1, 2, 3, 4, 5, 6, 7, 8}, - ProtocolVersion: []byte{0xff, 0, 0, 19}, - Events: make([]*pb.Event, len(events)), - } - var startTime time.Time - for i, ev := range events { - event := ev.ev - if i == 0 { - startTime = event.Time - } - - packetNumber := uint64(event.PacketNumber) - packetSize := uint64(event.PacketSize) - - trace.Events[i] = &pb.Event{ - TimeUs: durationToUs(event.Time.Sub(startTime)), - EventType: getEventType(event.EventType), - PacketSize: &packetSize, - PacketNumber: &packetNumber, - TransportState: getTransportState(event.TransportState), - EncryptionLevel: getEncryptionLevel(event.EncryptionLevel), - Frames: getFrames(event.Frames), - } - } - delete(t.events, connID) - return proto.Marshal(trace) -} - -func getEventType(evType EventType) *pb.EventType { - var t pb.EventType - switch evType { - case PacketSent: - t = pb.EventType_PACKET_SENT - case PacketReceived: - t = pb.EventType_PACKET_RECEIVED - case PacketLost: - t = pb.EventType_PACKET_LOST - default: - panic("unknown event type") - } - return &t -} - -func getEncryptionLevel(encLevel protocol.EncryptionLevel) *pb.EncryptionLevel { - enc := pb.EncryptionLevel_ENCRYPTION_UNKNOWN - switch encLevel { - case protocol.EncryptionInitial: - enc = pb.EncryptionLevel_ENCRYPTION_INITIAL - case protocol.EncryptionHandshake: - enc = pb.EncryptionLevel_ENCRYPTION_HANDSHAKE - case protocol.Encryption1RTT: - enc = pb.EncryptionLevel_ENCRYPTION_1RTT - } - return &enc -} - -func getFrames(wframes []wire.Frame) []*pb.Frame { - streamFrameType := pb.FrameType_STREAM - cryptoFrameType := pb.FrameType_CRYPTO - ackFrameType := pb.FrameType_ACK - var frames []*pb.Frame - for _, frame := range wframes { - switch f := frame.(type) { - case *wire.CryptoFrame: - offset := uint64(f.Offset) - length := uint64(len(f.Data)) - frames = append(frames, &pb.Frame{ - FrameType: &cryptoFrameType, - CryptoFrameInfo: &pb.CryptoFrameInfo{ - Offset: &offset, - Length: &length, - }, - }) - case *wire.StreamFrame: - streamID := uint64(f.StreamID) - offset := uint64(f.Offset) - length := uint64(f.DataLen()) - frames = append(frames, &pb.Frame{ - FrameType: &streamFrameType, - StreamFrameInfo: &pb.StreamFrameInfo{ - StreamId: &streamID, - Offset: &offset, - Length: &length, - }, - }) - case *wire.AckFrame: - var ackedPackets []*pb.AckBlock - for _, ackBlock := range f.AckRanges { - firstPacket := uint64(ackBlock.Smallest) - lastPacket := uint64(ackBlock.Largest) - ackedPackets = append(ackedPackets, &pb.AckBlock{ - FirstPacket: &firstPacket, - LastPacket: &lastPacket, - }) - } - frames = append(frames, &pb.Frame{ - FrameType: &ackFrameType, - AckInfo: &pb.AckInfo{ - AckDelayUs: durationToUs(f.DelayTime), - AckedPackets: ackedPackets, - }, - }) - } - } - return frames -} - -func getTransportState(state *TransportState) *pb.TransportState { - bytesInFlight := uint64(state.BytesInFlight) - congestionWindow := uint64(state.CongestionWindow) - ccs := fmt.Sprintf("InSlowStart: %t, InRecovery: %t", state.InSlowStart, state.InRecovery) - return &pb.TransportState{ - MinRttUs: durationToUs(state.MinRTT), - SmoothedRttUs: durationToUs(state.SmoothedRTT), - LastRttUs: durationToUs(state.LatestRTT), - InFlightBytes: &bytesInFlight, - CwndBytes: &congestionWindow, - CongestionControlState: &ccs, - } -} - -func durationToUs(d time.Duration) *uint64 { - dur := uint64(d / 1000) - return &dur -} diff --git a/vendor/github.com/marten-seemann/qtls/alert.go b/vendor/github.com/marten-seemann/qtls/alert.go deleted file mode 100644 index ba1c9ce394..0000000000 --- a/vendor/github.com/marten-seemann/qtls/alert.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import "strconv" - -type alert uint8 - -// Alert is a TLS alert -type Alert = alert - -const ( - // alert level - alertLevelWarning = 1 - alertLevelError = 2 -) - -const ( - alertCloseNotify alert = 0 - alertUnexpectedMessage alert = 10 - alertBadRecordMAC alert = 20 - alertDecryptionFailed alert = 21 - alertRecordOverflow alert = 22 - alertDecompressionFailure alert = 30 - alertHandshakeFailure alert = 40 - alertBadCertificate alert = 42 - alertUnsupportedCertificate alert = 43 - alertCertificateRevoked alert = 44 - alertCertificateExpired alert = 45 - alertCertificateUnknown alert = 46 - alertIllegalParameter alert = 47 - alertUnknownCA alert = 48 - alertAccessDenied alert = 49 - alertDecodeError alert = 50 - alertDecryptError alert = 51 - alertProtocolVersion alert = 70 - alertInsufficientSecurity alert = 71 - alertInternalError alert = 80 - alertInappropriateFallback alert = 86 - alertUserCanceled alert = 90 - alertNoRenegotiation alert = 100 - alertMissingExtension alert = 109 - alertUnsupportedExtension alert = 110 - alertNoApplicationProtocol alert = 120 -) - -var alertText = map[alert]string{ - alertCloseNotify: "close notify", - alertUnexpectedMessage: "unexpected message", - alertBadRecordMAC: "bad record MAC", - alertDecryptionFailed: "decryption failed", - alertRecordOverflow: "record overflow", - alertDecompressionFailure: "decompression failure", - alertHandshakeFailure: "handshake failure", - alertBadCertificate: "bad certificate", - alertUnsupportedCertificate: "unsupported certificate", - alertCertificateRevoked: "revoked certificate", - alertCertificateExpired: "expired certificate", - alertCertificateUnknown: "unknown certificate", - alertIllegalParameter: "illegal parameter", - alertUnknownCA: "unknown certificate authority", - alertAccessDenied: "access denied", - alertDecodeError: "error decoding message", - alertDecryptError: "error decrypting message", - alertProtocolVersion: "protocol version not supported", - alertInsufficientSecurity: "insufficient security level", - alertInternalError: "internal error", - alertInappropriateFallback: "inappropriate fallback", - alertUserCanceled: "user canceled", - alertNoRenegotiation: "no renegotiation", - alertMissingExtension: "missing extension", - alertUnsupportedExtension: "unsupported extension", - alertNoApplicationProtocol: "no application protocol", -} - -func (e alert) String() string { - s, ok := alertText[e] - if ok { - return "tls: " + s - } - return "tls: alert(" + strconv.Itoa(int(e)) + ")" -} - -func (e alert) Error() string { - return e.String() -} diff --git a/vendor/github.com/marten-seemann/qtls/auth.go b/vendor/github.com/marten-seemann/qtls/auth.go deleted file mode 100644 index b8fd7f9bab..0000000000 --- a/vendor/github.com/marten-seemann/qtls/auth.go +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "encoding/asn1" - "errors" - "fmt" - "hash" - "io" -) - -// pickSignatureAlgorithm selects a signature algorithm that is compatible with -// the given public key and the list of algorithms from the peer and this side. -// The lists of signature algorithms (peerSigAlgs and ourSigAlgs) are ignored -// for tlsVersion < VersionTLS12. -// -// The returned SignatureScheme codepoint is only meaningful for TLS 1.2, -// previous TLS versions have a fixed hash function. -func pickSignatureAlgorithm(pubkey crypto.PublicKey, peerSigAlgs, ourSigAlgs []SignatureScheme, tlsVersion uint16) (sigAlg SignatureScheme, sigType uint8, hashFunc crypto.Hash, err error) { - if tlsVersion < VersionTLS12 || len(peerSigAlgs) == 0 { - // For TLS 1.1 and before, the signature algorithm could not be - // negotiated and the hash is fixed based on the signature type. For TLS - // 1.2, if the client didn't send signature_algorithms extension then we - // can assume that it supports SHA1. See RFC 5246, Section 7.4.1.4.1. - switch pubkey.(type) { - case *rsa.PublicKey: - if tlsVersion < VersionTLS12 { - return 0, signaturePKCS1v15, crypto.MD5SHA1, nil - } else { - return PKCS1WithSHA1, signaturePKCS1v15, crypto.SHA1, nil - } - case *ecdsa.PublicKey: - return ECDSAWithSHA1, signatureECDSA, crypto.SHA1, nil - default: - return 0, 0, 0, fmt.Errorf("tls: unsupported public key: %T", pubkey) - } - } - for _, sigAlg := range peerSigAlgs { - if !isSupportedSignatureAlgorithm(sigAlg, ourSigAlgs) { - continue - } - hashAlg, err := hashFromSignatureScheme(sigAlg) - if err != nil { - panic("tls: supported signature algorithm has an unknown hash function") - } - sigType := signatureFromSignatureScheme(sigAlg) - switch pubkey.(type) { - case *rsa.PublicKey: - if sigType == signaturePKCS1v15 || sigType == signatureRSAPSS { - return sigAlg, sigType, hashAlg, nil - } - case *ecdsa.PublicKey: - if sigType == signatureECDSA { - return sigAlg, sigType, hashAlg, nil - } - default: - return 0, 0, 0, fmt.Errorf("tls: unsupported public key: %T", pubkey) - } - } - return 0, 0, 0, errors.New("tls: peer doesn't support any common signature algorithms") -} - -// verifyHandshakeSignature verifies a signature against pre-hashed handshake -// contents. -func verifyHandshakeSignature(sigType uint8, pubkey crypto.PublicKey, hashFunc crypto.Hash, digest, sig []byte) error { - switch sigType { - case signatureECDSA: - pubKey, ok := pubkey.(*ecdsa.PublicKey) - if !ok { - return errors.New("tls: ECDSA signing requires a ECDSA public key") - } - ecdsaSig := new(ecdsaSignature) - if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil { - return err - } - if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { - return errors.New("tls: ECDSA signature contained zero or negative values") - } - if !ecdsa.Verify(pubKey, digest, ecdsaSig.R, ecdsaSig.S) { - return errors.New("tls: ECDSA verification failure") - } - case signaturePKCS1v15: - pubKey, ok := pubkey.(*rsa.PublicKey) - if !ok { - return errors.New("tls: RSA signing requires a RSA public key") - } - if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, digest, sig); err != nil { - return err - } - case signatureRSAPSS: - pubKey, ok := pubkey.(*rsa.PublicKey) - if !ok { - return errors.New("tls: RSA signing requires a RSA public key") - } - signOpts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash} - if err := rsa.VerifyPSS(pubKey, hashFunc, digest, sig, signOpts); err != nil { - return err - } - default: - return errors.New("tls: unknown signature algorithm") - } - return nil -} - -const ( - serverSignatureContext = "TLS 1.3, server CertificateVerify\x00" - clientSignatureContext = "TLS 1.3, client CertificateVerify\x00" -) - -var signaturePadding = []byte{ - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, -} - -// writeSignedMessage writes the content to be signed by certificate keys in TLS -// 1.3 to sigHash. See RFC 8446, Section 4.4.3. -func writeSignedMessage(sigHash io.Writer, context string, transcript hash.Hash) { - sigHash.Write(signaturePadding) - io.WriteString(sigHash, context) - sigHash.Write(transcript.Sum(nil)) -} - -// signatureSchemesForCertificate returns the list of supported SignatureSchemes -// for a given certificate, based on the public key and the protocol version. It -// does not support the crypto.Decrypter interface, so shouldn't be used on the -// server side in TLS 1.2 and earlier. -func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme { - priv, ok := cert.PrivateKey.(crypto.Signer) - if !ok { - return nil - } - - switch pub := priv.Public().(type) { - case *ecdsa.PublicKey: - if version != VersionTLS13 { - // In TLS 1.2 and earlier, ECDSA algorithms are not - // constrained to a single curve. - return []SignatureScheme{ - ECDSAWithP256AndSHA256, - ECDSAWithP384AndSHA384, - ECDSAWithP521AndSHA512, - ECDSAWithSHA1, - } - } - switch pub.Curve { - case elliptic.P256(): - return []SignatureScheme{ECDSAWithP256AndSHA256} - case elliptic.P384(): - return []SignatureScheme{ECDSAWithP384AndSHA384} - case elliptic.P521(): - return []SignatureScheme{ECDSAWithP521AndSHA512} - default: - return nil - } - case *rsa.PublicKey: - if version != VersionTLS13 { - return []SignatureScheme{ - PSSWithSHA256, - PSSWithSHA384, - PSSWithSHA512, - PKCS1WithSHA256, - PKCS1WithSHA384, - PKCS1WithSHA512, - PKCS1WithSHA1, - } - } - // RSA keys with RSA-PSS OID are not supported by crypto/x509. - return []SignatureScheme{ - PSSWithSHA256, - PSSWithSHA384, - PSSWithSHA512, - } - default: - return nil - } -} - -// unsupportedCertificateError returns a helpful error for certificates with -// an unsupported private key. -func unsupportedCertificateError(cert *Certificate) error { - switch cert.PrivateKey.(type) { - case rsa.PrivateKey, ecdsa.PrivateKey: - return fmt.Errorf("tls: unsupported certificate: private key is %T, expected *%T", - cert.PrivateKey, cert.PrivateKey) - } - - signer, ok := cert.PrivateKey.(crypto.Signer) - if !ok { - return fmt.Errorf("tls: certificate private key (%T) does not implement crypto.Signer", - cert.PrivateKey) - } - - switch pub := signer.Public().(type) { - case *ecdsa.PublicKey: - switch pub.Curve { - case elliptic.P256(): - case elliptic.P384(): - case elliptic.P521(): - default: - return fmt.Errorf("tls: unsupported certificate curve (%s)", pub.Curve.Params().Name) - } - case *rsa.PublicKey: - default: - return fmt.Errorf("tls: unsupported certificate key (%T)", pub) - } - - return fmt.Errorf("tls: internal error: unsupported key (%T)", cert.PrivateKey) -} diff --git a/vendor/github.com/marten-seemann/qtls/cipher_suites.go b/vendor/github.com/marten-seemann/qtls/cipher_suites.go deleted file mode 100644 index e0b7e2f19b..0000000000 --- a/vendor/github.com/marten-seemann/qtls/cipher_suites.go +++ /dev/null @@ -1,487 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "crypto" - "crypto/aes" - "crypto/cipher" - "crypto/des" - "crypto/hmac" - "crypto/rc4" - "crypto/sha1" - "crypto/sha256" - "crypto/x509" - "hash" - - "golang.org/x/crypto/chacha20poly1305" -) - -// a keyAgreement implements the client and server side of a TLS key agreement -// protocol by generating and processing key exchange messages. -type keyAgreement interface { - // On the server side, the first two methods are called in order. - - // In the case that the key agreement protocol doesn't use a - // ServerKeyExchange message, generateServerKeyExchange can return nil, - // nil. - generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error) - processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error) - - // On the client side, the next two methods are called in order. - - // This method may not be called if the server doesn't send a - // ServerKeyExchange message. - processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error - generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) -} - -const ( - // suiteECDH indicates that the cipher suite involves elliptic curve - // Diffie-Hellman. This means that it should only be selected when the - // client indicates that it supports ECC with a curve and point format - // that we're happy with. - suiteECDHE = 1 << iota - // suiteECDSA indicates that the cipher suite involves an ECDSA - // signature and therefore may only be selected when the server's - // certificate is ECDSA. If this is not set then the cipher suite is - // RSA based. - suiteECDSA - // suiteTLS12 indicates that the cipher suite should only be advertised - // and accepted when using TLS 1.2. - suiteTLS12 - // suiteSHA384 indicates that the cipher suite uses SHA384 as the - // handshake hash. - suiteSHA384 - // suiteDefaultOff indicates that this cipher suite is not included by - // default. - suiteDefaultOff -) - -type CipherSuite struct { - *cipherSuiteTLS13 -} - -func (c *CipherSuite) Hash() crypto.Hash { return c.hash } -func (c *CipherSuite) KeyLen() int { return c.keyLen } -func (c *CipherSuite) IVLen() int { return aeadNonceLength } -func (c *CipherSuite) AEAD(key, fixedNonce []byte) cipher.AEAD { return c.aead(key, fixedNonce) } - -// A cipherSuite is a specific combination of key agreement, cipher and MAC function. -type cipherSuite struct { - id uint16 - // the lengths, in bytes, of the key material needed for each component. - keyLen int - macLen int - ivLen int - ka func(version uint16) keyAgreement - // flags is a bitmask of the suite* values, above. - flags int - cipher func(key, iv []byte, isRead bool) interface{} - mac func(version uint16, macKey []byte) macFunction - aead func(key, fixedNonce []byte) aead -} - -var cipherSuites = []*cipherSuite{ - // Ciphersuite order is chosen so that ECDHE comes before plain RSA and - // AEADs are the top preference. - {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadChaCha20Poly1305}, - {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, nil, nil, aeadChaCha20Poly1305}, - {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadAESGCM}, - {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, nil, nil, aeadAESGCM}, - {TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM}, - {TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM}, - {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteDefaultOff, cipherAES, macSHA256, nil}, - {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil}, - {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12 | suiteDefaultOff, cipherAES, macSHA256, nil}, - {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherAES, macSHA1, nil}, - {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil}, - {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherAES, macSHA1, nil}, - {TLS_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, rsaKA, suiteTLS12, nil, nil, aeadAESGCM}, - {TLS_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, rsaKA, suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM}, - {TLS_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, rsaKA, suiteTLS12 | suiteDefaultOff, cipherAES, macSHA256, nil}, - {TLS_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil}, - {TLS_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil}, - {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, ecdheRSAKA, suiteECDHE, cipher3DES, macSHA1, nil}, - {TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, rsaKA, 0, cipher3DES, macSHA1, nil}, - - // RC4-based cipher suites are disabled by default. - {TLS_RSA_WITH_RC4_128_SHA, 16, 20, 0, rsaKA, suiteDefaultOff, cipherRC4, macSHA1, nil}, - {TLS_ECDHE_RSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheRSAKA, suiteECDHE | suiteDefaultOff, cipherRC4, macSHA1, nil}, - {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteDefaultOff, cipherRC4, macSHA1, nil}, -} - -// A cipherSuiteTLS13 defines only the pair of the AEAD algorithm and hash -// algorithm to be used with HKDF. See RFC 8446, Appendix B.4. -type cipherSuiteTLS13 struct { - id uint16 - keyLen int - aead func(key, fixedNonce []byte) aead - hash crypto.Hash -} - -var cipherSuitesTLS13 = []*cipherSuiteTLS13{ - {TLS_AES_128_GCM_SHA256, 16, aeadAESGCMTLS13, crypto.SHA256}, - {TLS_CHACHA20_POLY1305_SHA256, 32, aeadChaCha20Poly1305, crypto.SHA256}, - {TLS_AES_256_GCM_SHA384, 32, aeadAESGCMTLS13, crypto.SHA384}, -} - -func cipherRC4(key, iv []byte, isRead bool) interface{} { - cipher, _ := rc4.NewCipher(key) - return cipher -} - -func cipher3DES(key, iv []byte, isRead bool) interface{} { - block, _ := des.NewTripleDESCipher(key) - if isRead { - return cipher.NewCBCDecrypter(block, iv) - } - return cipher.NewCBCEncrypter(block, iv) -} - -func cipherAES(key, iv []byte, isRead bool) interface{} { - block, _ := aes.NewCipher(key) - if isRead { - return cipher.NewCBCDecrypter(block, iv) - } - return cipher.NewCBCEncrypter(block, iv) -} - -// macSHA1 returns a macFunction for the given protocol version. -func macSHA1(version uint16, key []byte) macFunction { - if version == VersionSSL30 { - mac := ssl30MAC{ - h: sha1.New(), - key: make([]byte, len(key)), - } - copy(mac.key, key) - return mac - } - return tls10MAC{h: hmac.New(newConstantTimeHash(sha1.New), key)} -} - -// macSHA256 returns a SHA-256 based MAC. These are only supported in TLS 1.2 -// so the given version is ignored. -func macSHA256(version uint16, key []byte) macFunction { - return tls10MAC{h: hmac.New(sha256.New, key)} -} - -type macFunction interface { - // Size returns the length of the MAC. - Size() int - // MAC appends the MAC of (seq, header, data) to out. The extra data is fed - // into the MAC after obtaining the result to normalize timing. The result - // is only valid until the next invocation of MAC as the buffer is reused. - MAC(seq, header, data, extra []byte) []byte -} - -type aead interface { - cipher.AEAD - - // explicitNonceLen returns the number of bytes of explicit nonce - // included in each record. This is eight for older AEADs and - // zero for modern ones. - explicitNonceLen() int -} - -const ( - aeadNonceLength = 12 - noncePrefixLength = 4 -) - -// prefixNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to -// each call. -type prefixNonceAEAD struct { - // nonce contains the fixed part of the nonce in the first four bytes. - nonce [aeadNonceLength]byte - aead cipher.AEAD -} - -func (f *prefixNonceAEAD) NonceSize() int { return aeadNonceLength - noncePrefixLength } -func (f *prefixNonceAEAD) Overhead() int { return f.aead.Overhead() } -func (f *prefixNonceAEAD) explicitNonceLen() int { return f.NonceSize() } - -func (f *prefixNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte { - copy(f.nonce[4:], nonce) - return f.aead.Seal(out, f.nonce[:], plaintext, additionalData) -} - -func (f *prefixNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) { - copy(f.nonce[4:], nonce) - return f.aead.Open(out, f.nonce[:], ciphertext, additionalData) -} - -// xoredNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce -// before each call. -type xorNonceAEAD struct { - nonceMask [aeadNonceLength]byte - aead cipher.AEAD -} - -func (f *xorNonceAEAD) NonceSize() int { return 8 } // 64-bit sequence number -func (f *xorNonceAEAD) Overhead() int { return f.aead.Overhead() } -func (f *xorNonceAEAD) explicitNonceLen() int { return 0 } - -func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte { - for i, b := range nonce { - f.nonceMask[4+i] ^= b - } - result := f.aead.Seal(out, f.nonceMask[:], plaintext, additionalData) - for i, b := range nonce { - f.nonceMask[4+i] ^= b - } - - return result -} - -func (f *xorNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) { - for i, b := range nonce { - f.nonceMask[4+i] ^= b - } - result, err := f.aead.Open(out, f.nonceMask[:], ciphertext, additionalData) - for i, b := range nonce { - f.nonceMask[4+i] ^= b - } - - return result, err -} - -func aeadAESGCM(key, noncePrefix []byte) aead { - if len(noncePrefix) != noncePrefixLength { - panic("tls: internal error: wrong nonce length") - } - aes, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - aead, err := cipher.NewGCM(aes) - if err != nil { - panic(err) - } - - ret := &prefixNonceAEAD{aead: aead} - copy(ret.nonce[:], noncePrefix) - return ret -} - -// AEADAESGCMTLS13 creates a new AES-GCM AEAD for TLS 1.3 -func AEADAESGCMTLS13(key, fixedNonce []byte) cipher.AEAD { - return aeadAESGCMTLS13(key, fixedNonce) -} - -func aeadAESGCMTLS13(key, nonceMask []byte) aead { - if len(nonceMask) != aeadNonceLength { - panic("tls: internal error: wrong nonce length") - } - aes, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - aead, err := cipher.NewGCM(aes) - if err != nil { - panic(err) - } - - ret := &xorNonceAEAD{aead: aead} - copy(ret.nonceMask[:], nonceMask) - return ret -} - -func aeadChaCha20Poly1305(key, nonceMask []byte) aead { - if len(nonceMask) != aeadNonceLength { - panic("tls: internal error: wrong nonce length") - } - aead, err := chacha20poly1305.New(key) - if err != nil { - panic(err) - } - - ret := &xorNonceAEAD{aead: aead} - copy(ret.nonceMask[:], nonceMask) - return ret -} - -// ssl30MAC implements the SSLv3 MAC function, as defined in -// www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt section 5.2.3.1 -type ssl30MAC struct { - h hash.Hash - key []byte - buf []byte -} - -func (s ssl30MAC) Size() int { - return s.h.Size() -} - -var ssl30Pad1 = [48]byte{0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36} - -var ssl30Pad2 = [48]byte{0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c} - -// MAC does not offer constant timing guarantees for SSL v3.0, since it's deemed -// useless considering the similar, protocol-level POODLE vulnerability. -func (s ssl30MAC) MAC(seq, header, data, extra []byte) []byte { - padLength := 48 - if s.h.Size() == 20 { - padLength = 40 - } - - s.h.Reset() - s.h.Write(s.key) - s.h.Write(ssl30Pad1[:padLength]) - s.h.Write(seq) - s.h.Write(header[:1]) - s.h.Write(header[3:5]) - s.h.Write(data) - s.buf = s.h.Sum(s.buf[:0]) - - s.h.Reset() - s.h.Write(s.key) - s.h.Write(ssl30Pad2[:padLength]) - s.h.Write(s.buf) - return s.h.Sum(s.buf[:0]) -} - -type constantTimeHash interface { - hash.Hash - ConstantTimeSum(b []byte) []byte -} - -// cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces -// with that all calls to Sum. It's used to obtain a ConstantTimeSum-based HMAC. -type cthWrapper struct { - h constantTimeHash -} - -func (c *cthWrapper) Size() int { return c.h.Size() } -func (c *cthWrapper) BlockSize() int { return c.h.BlockSize() } -func (c *cthWrapper) Reset() { c.h.Reset() } -func (c *cthWrapper) Write(p []byte) (int, error) { return c.h.Write(p) } -func (c *cthWrapper) Sum(b []byte) []byte { return c.h.ConstantTimeSum(b) } - -func newConstantTimeHash(h func() hash.Hash) func() hash.Hash { - return func() hash.Hash { - return &cthWrapper{h().(constantTimeHash)} - } -} - -// tls10MAC implements the TLS 1.0 MAC function. RFC 2246, Section 6.2.3. -type tls10MAC struct { - h hash.Hash - buf []byte -} - -func (s tls10MAC) Size() int { - return s.h.Size() -} - -// MAC is guaranteed to take constant time, as long as -// len(seq)+len(header)+len(data)+len(extra) is constant. extra is not fed into -// the MAC, but is only provided to make the timing profile constant. -func (s tls10MAC) MAC(seq, header, data, extra []byte) []byte { - s.h.Reset() - s.h.Write(seq) - s.h.Write(header) - s.h.Write(data) - res := s.h.Sum(s.buf[:0]) - if extra != nil { - s.h.Write(extra) - } - return res -} - -func rsaKA(version uint16) keyAgreement { - return rsaKeyAgreement{} -} - -func ecdheECDSAKA(version uint16) keyAgreement { - return &ecdheKeyAgreement{ - isRSA: false, - version: version, - } -} - -func ecdheRSAKA(version uint16) keyAgreement { - return &ecdheKeyAgreement{ - isRSA: true, - version: version, - } -} - -// mutualCipherSuite returns a cipherSuite given a list of supported -// ciphersuites and the id requested by the peer. -func mutualCipherSuite(have []uint16, want uint16) *cipherSuite { - for _, id := range have { - if id == want { - return cipherSuiteByID(id) - } - } - return nil -} - -func cipherSuiteByID(id uint16) *cipherSuite { - for _, cipherSuite := range cipherSuites { - if cipherSuite.id == id { - return cipherSuite - } - } - return nil -} - -func mutualCipherSuiteTLS13(have []uint16, want uint16) *cipherSuiteTLS13 { - for _, id := range have { - if id == want { - return cipherSuiteTLS13ByID(id) - } - } - return nil -} - -func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 { - for _, cipherSuite := range cipherSuitesTLS13 { - if cipherSuite.id == id { - return cipherSuite - } - } - return nil -} - -// A list of cipher suite IDs that are, or have been, implemented by this -// package. -// -// Taken from https://www.iana.org/assignments/tls-parameters/tls-parameters.xml -const ( - // TLS 1.0 - 1.2 cipher suites. - TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005 - TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000a - TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002f - TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035 - TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003c - TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009c - TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009d - TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xc007 - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xc009 - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xc00a - TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xc011 - TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012 - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xc013 - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xc014 - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc023 - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc027 - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02f - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc030 - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc02c - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305 uint16 = 0xcca8 - TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 uint16 = 0xcca9 - - // TLS 1.3 cipher suites. - TLS_AES_128_GCM_SHA256 uint16 = 0x1301 - TLS_AES_256_GCM_SHA384 uint16 = 0x1302 - TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303 - - // TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator - // that the client is doing version fallback. See RFC 7507. - TLS_FALLBACK_SCSV uint16 = 0x5600 -) diff --git a/vendor/github.com/marten-seemann/qtls/common.go b/vendor/github.com/marten-seemann/qtls/common.go deleted file mode 100644 index df4c98e868..0000000000 --- a/vendor/github.com/marten-seemann/qtls/common.go +++ /dev/null @@ -1,1148 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "container/list" - "crypto/rand" - "crypto/sha512" - "crypto/tls" - "crypto/x509" - "errors" - "fmt" - "io" - "math/big" - "os" - "strings" - "sync" - "time" - - "golang.org/x/sys/cpu" -) - -const ( - VersionSSL30 = 0x0300 - VersionTLS10 = 0x0301 - VersionTLS11 = 0x0302 - VersionTLS12 = 0x0303 - VersionTLS13 = 0x0304 -) - -const ( - maxPlaintext = 16384 // maximum plaintext payload length - maxCiphertext = 16384 + 2048 // maximum ciphertext payload length - maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3 - recordHeaderLen = 5 // record header length - maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB) - maxUselessRecords = 16 // maximum number of consecutive non-advancing records -) - -// TLS record types. -type recordType uint8 - -const ( - recordTypeChangeCipherSpec recordType = 20 - recordTypeAlert recordType = 21 - recordTypeHandshake recordType = 22 - recordTypeApplicationData recordType = 23 -) - -// TLS handshake message types. -const ( - typeHelloRequest uint8 = 0 - typeClientHello uint8 = 1 - typeServerHello uint8 = 2 - typeNewSessionTicket uint8 = 4 - typeEndOfEarlyData uint8 = 5 - typeEncryptedExtensions uint8 = 8 - typeCertificate uint8 = 11 - typeServerKeyExchange uint8 = 12 - typeCertificateRequest uint8 = 13 - typeServerHelloDone uint8 = 14 - typeCertificateVerify uint8 = 15 - typeClientKeyExchange uint8 = 16 - typeFinished uint8 = 20 - typeCertificateStatus uint8 = 22 - typeKeyUpdate uint8 = 24 - typeNextProtocol uint8 = 67 // Not IANA assigned - typeMessageHash uint8 = 254 // synthetic message -) - -// TLS compression types. -const ( - compressionNone uint8 = 0 -) - -type Extension struct { - Type uint16 - Data []byte -} - -// TLS extension numbers -const ( - extensionServerName uint16 = 0 - extensionStatusRequest uint16 = 5 - extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7 - extensionSupportedPoints uint16 = 11 - extensionSignatureAlgorithms uint16 = 13 - extensionALPN uint16 = 16 - extensionSCT uint16 = 18 - extensionSessionTicket uint16 = 35 - extensionPreSharedKey uint16 = 41 - extensionEarlyData uint16 = 42 - extensionSupportedVersions uint16 = 43 - extensionCookie uint16 = 44 - extensionPSKModes uint16 = 45 - extensionCertificateAuthorities uint16 = 47 - extensionSignatureAlgorithmsCert uint16 = 50 - extensionKeyShare uint16 = 51 - extensionNextProtoNeg uint16 = 13172 // not IANA assigned - extensionRenegotiationInfo uint16 = 0xff01 -) - -// TLS signaling cipher suite values -const ( - scsvRenegotiation uint16 = 0x00ff -) - -// CurveID is a tls.CurveID -type CurveID = tls.CurveID - -const ( - CurveP256 CurveID = 23 - CurveP384 CurveID = 24 - CurveP521 CurveID = 25 - X25519 CurveID = 29 -) - -// TLS 1.3 Key Share. See RFC 8446, Section 4.2.8. -type keyShare struct { - group CurveID - data []byte -} - -// TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9. -const ( - pskModePlain uint8 = 0 - pskModeDHE uint8 = 1 -) - -// TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved -// session. See RFC 8446, Section 4.2.11. -type pskIdentity struct { - label []byte - obfuscatedTicketAge uint32 -} - -// TLS Elliptic Curve Point Formats -// https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9 -const ( - pointFormatUncompressed uint8 = 0 -) - -// TLS CertificateStatusType (RFC 3546) -const ( - statusTypeOCSP uint8 = 1 -) - -// Certificate types (for certificateRequestMsg) -const ( - certTypeRSASign = 1 - certTypeECDSASign = 64 // RFC 4492, Section 5.5 -) - -// Signature algorithms (for internal signaling use). Starting at 16 to avoid overlap with -// TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do. -const ( - signaturePKCS1v15 uint8 = iota + 16 - signatureECDSA - signatureRSAPSS -) - -// supportedSignatureAlgorithms contains the signature and hash algorithms that -// the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+ -// CertificateRequest. The two fields are merged to match with TLS 1.3. -// Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc. -var supportedSignatureAlgorithms = []SignatureScheme{ - PSSWithSHA256, - PSSWithSHA384, - PSSWithSHA512, - PKCS1WithSHA256, - ECDSAWithP256AndSHA256, - PKCS1WithSHA384, - ECDSAWithP384AndSHA384, - PKCS1WithSHA512, - ECDSAWithP521AndSHA512, - PKCS1WithSHA1, - ECDSAWithSHA1, -} - -// RSA-PSS is disabled in TLS 1.2 for Go 1.12. See Issue 30055. -var supportedSignatureAlgorithmsTLS12 = supportedSignatureAlgorithms[3:] - -// helloRetryRequestRandom is set as the Random value of a ServerHello -// to signal that the message is actually a HelloRetryRequest. -var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3. - 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, - 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, - 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, - 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C, -} - -const ( - // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server - // random as a downgrade protection if the server would be capable of - // negotiating a higher version. See RFC 8446, Section 4.1.3. - downgradeCanaryTLS12 = "DOWNGRD\x01" - downgradeCanaryTLS11 = "DOWNGRD\x00" -) - -// ConnectionState records basic TLS details about the connection. -type ConnectionState struct { - Version uint16 // TLS version used by the connection (e.g. VersionTLS12) - HandshakeComplete bool // TLS handshake is complete - DidResume bool // connection resumes a previous TLS connection - CipherSuite uint16 // cipher suite in use (TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, ...) - NegotiatedProtocol string // negotiated next protocol (not guaranteed to be from Config.NextProtos) - NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server (client side only) - ServerName string // server name requested by client, if any (server side only) - PeerCertificates []*x509.Certificate // certificate chain presented by remote peer - VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates - SignedCertificateTimestamps [][]byte // SCTs from the peer, if any - OCSPResponse []byte // stapled OCSP response from peer, if any - - // ekm is a closure exposed via ExportKeyingMaterial. - ekm func(label string, context []byte, length int) ([]byte, error) - - // TLSUnique contains the "tls-unique" channel binding value (see RFC - // 5929, section 3). For resumed sessions this value will be nil - // because resumption does not include enough context (see - // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will - // change in future versions of Go once the TLS master-secret fix has - // been standardized and implemented. It is not defined in TLS 1.3. - TLSUnique []byte -} - -// ExportKeyingMaterial returns length bytes of exported key material in a new -// slice as defined in RFC 5705. If context is nil, it is not used as part of -// the seed. If the connection was set to allow renegotiation via -// Config.Renegotiation, this function will return an error. -func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) { - return cs.ekm(label, context, length) -} - -// ClientAuthType is tls.ClientAuthType -type ClientAuthType = tls.ClientAuthType - -const ( - NoClientCert ClientAuthType = iota - RequestClientCert - RequireAnyClientCert - VerifyClientCertIfGiven - RequireAndVerifyClientCert -) - -// requiresClientCert reports whether the ClientAuthType requires a client -// certificate to be provided. -func requiresClientCert(c ClientAuthType) bool { - switch c { - case RequireAnyClientCert, RequireAndVerifyClientCert: - return true - default: - return false - } -} - -// ClientSessionState contains the state needed by clients to resume TLS -// sessions. -type ClientSessionState struct { - sessionTicket []uint8 // Encrypted ticket used for session resumption with server - vers uint16 // SSL/TLS version negotiated for the session - cipherSuite uint16 // Ciphersuite negotiated for the session - masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret - serverCertificates []*x509.Certificate // Certificate chain presented by the server - verifiedChains [][]*x509.Certificate // Certificate chains we built for verification - receivedAt time.Time // When the session ticket was received from the server - - // TLS 1.3 fields. - nonce []byte // Ticket nonce sent by the server, to derive PSK - useBy time.Time // Expiration of the ticket lifetime as set by the server - ageAdd uint32 // Random obfuscation factor for sending the ticket age -} - -// ClientSessionCache is a cache of ClientSessionState objects that can be used -// by a client to resume a TLS session with a given server. ClientSessionCache -// implementations should expect to be called concurrently from different -// goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not -// SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which -// are supported via this interface. -type ClientSessionCache interface { - // Get searches for a ClientSessionState associated with the given key. - // On return, ok is true if one was found. - Get(sessionKey string) (session *ClientSessionState, ok bool) - - // Put adds the ClientSessionState to the cache with the given key. It might - // get called multiple times in a connection if a TLS 1.3 server provides - // more than one session ticket. If called with a nil *ClientSessionState, - // it should remove the cache entry. - Put(sessionKey string, cs *ClientSessionState) -} - -// SignatureScheme is a tls.SignatureScheme -type SignatureScheme = tls.SignatureScheme - -const ( - // RSASSA-PKCS1-v1_5 algorithms. - PKCS1WithSHA256 SignatureScheme = 0x0401 - PKCS1WithSHA384 SignatureScheme = 0x0501 - PKCS1WithSHA512 SignatureScheme = 0x0601 - - // RSASSA-PSS algorithms with public key OID rsaEncryption. - PSSWithSHA256 SignatureScheme = 0x0804 - PSSWithSHA384 SignatureScheme = 0x0805 - PSSWithSHA512 SignatureScheme = 0x0806 - - // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3. - ECDSAWithP256AndSHA256 SignatureScheme = 0x0403 - ECDSAWithP384AndSHA384 SignatureScheme = 0x0503 - ECDSAWithP521AndSHA512 SignatureScheme = 0x0603 - - // Legacy signature and hash algorithms for TLS 1.2. - PKCS1WithSHA1 SignatureScheme = 0x0201 - ECDSAWithSHA1 SignatureScheme = 0x0203 -) - -// A ClientHelloInfo is a tls.ClientHelloInfo -type ClientHelloInfo = tls.ClientHelloInfo - -// The CertificateRequestInfo is a tls.CertificateRequestInfo -type CertificateRequestInfo = tls.CertificateRequestInfo - -// RenegotiationSupport enumerates the different levels of support for TLS -// renegotiation. TLS renegotiation is the act of performing subsequent -// handshakes on a connection after the first. This significantly complicates -// the state machine and has been the source of numerous, subtle security -// issues. Initiating a renegotiation is not supported, but support for -// accepting renegotiation requests may be enabled. -// -// Even when enabled, the server may not change its identity between handshakes -// (i.e. the leaf certificate must be the same). Additionally, concurrent -// handshake and application data flow is not permitted so renegotiation can -// only be used with protocols that synchronise with the renegotiation, such as -// HTTPS. -// -// Renegotiation is not defined in TLS 1.3. -type RenegotiationSupport int - -const ( - // RenegotiateNever disables renegotiation. - RenegotiateNever RenegotiationSupport = iota - - // RenegotiateOnceAsClient allows a remote server to request - // renegotiation once per connection. - RenegotiateOnceAsClient - - // RenegotiateFreelyAsClient allows a remote server to repeatedly - // request renegotiation. - RenegotiateFreelyAsClient -) - -// A Config structure is used to configure a TLS client or server. -// After one has been passed to a TLS function it must not be -// modified. A Config may be reused; the tls package will also not -// modify it. -type Config struct { - // Rand provides the source of entropy for nonces and RSA blinding. - // If Rand is nil, TLS uses the cryptographic random reader in package - // crypto/rand. - // The Reader must be safe for use by multiple goroutines. - Rand io.Reader - - // Time returns the current time as the number of seconds since the epoch. - // If Time is nil, TLS uses time.Now. - Time func() time.Time - - // Certificates contains one or more certificate chains to present to - // the other side of the connection. Server configurations must include - // at least one certificate or else set GetCertificate. Clients doing - // client-authentication may set either Certificates or - // GetClientCertificate. - Certificates []Certificate - - // NameToCertificate maps from a certificate name to an element of - // Certificates. Note that a certificate name can be of the form - // '*.example.com' and so doesn't have to be a domain name as such. - // See Config.BuildNameToCertificate - // The nil value causes the first element of Certificates to be used - // for all connections. - NameToCertificate map[string]*Certificate - - // GetCertificate returns a Certificate based on the given - // ClientHelloInfo. It will only be called if the client supplies SNI - // information or if Certificates is empty. - // - // If GetCertificate is nil or returns nil, then the certificate is - // retrieved from NameToCertificate. If NameToCertificate is nil, the - // first element of Certificates will be used. - GetCertificate func(*ClientHelloInfo) (*Certificate, error) - - // GetClientCertificate, if not nil, is called when a server requests a - // certificate from a client. If set, the contents of Certificates will - // be ignored. - // - // If GetClientCertificate returns an error, the handshake will be - // aborted and that error will be returned. Otherwise - // GetClientCertificate must return a non-nil Certificate. If - // Certificate.Certificate is empty then no certificate will be sent to - // the server. If this is unacceptable to the server then it may abort - // the handshake. - // - // GetClientCertificate may be called multiple times for the same - // connection if renegotiation occurs or if TLS 1.3 is in use. - GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error) - - // GetConfigForClient, if not nil, is called after a ClientHello is - // received from a client. It may return a non-nil Config in order to - // change the Config that will be used to handle this connection. If - // the returned Config is nil, the original Config will be used. The - // Config returned by this callback may not be subsequently modified. - // - // If GetConfigForClient is nil, the Config passed to Server() will be - // used for all connections. - // - // Uniquely for the fields in the returned Config, session ticket keys - // will be duplicated from the original Config if not set. - // Specifically, if SetSessionTicketKeys was called on the original - // config but not on the returned config then the ticket keys from the - // original config will be copied into the new config before use. - // Otherwise, if SessionTicketKey was set in the original config but - // not in the returned config then it will be copied into the returned - // config before use. If neither of those cases applies then the key - // material from the returned config will be used for session tickets. - GetConfigForClient func(*ClientHelloInfo) (*Config, error) - - // VerifyPeerCertificate, if not nil, is called after normal - // certificate verification by either a TLS client or server. It - // receives the raw ASN.1 certificates provided by the peer and also - // any verified chains that normal processing found. If it returns a - // non-nil error, the handshake is aborted and that error results. - // - // If normal verification fails then the handshake will abort before - // considering this callback. If normal verification is disabled by - // setting InsecureSkipVerify, or (for a server) when ClientAuth is - // RequestClientCert or RequireAnyClientCert, then this callback will - // be considered but the verifiedChains argument will always be nil. - VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error - - // RootCAs defines the set of root certificate authorities - // that clients use when verifying server certificates. - // If RootCAs is nil, TLS uses the host's root CA set. - RootCAs *x509.CertPool - - // NextProtos is a list of supported application level protocols, in - // order of preference. - NextProtos []string - - // ServerName is used to verify the hostname on the returned - // certificates unless InsecureSkipVerify is given. It is also included - // in the client's handshake to support virtual hosting unless it is - // an IP address. - ServerName string - - // ClientAuth determines the server's policy for - // TLS Client Authentication. The default is NoClientCert. - ClientAuth ClientAuthType - - // ClientCAs defines the set of root certificate authorities - // that servers use if required to verify a client certificate - // by the policy in ClientAuth. - ClientCAs *x509.CertPool - - // InsecureSkipVerify controls whether a client verifies the - // server's certificate chain and host name. - // If InsecureSkipVerify is true, TLS accepts any certificate - // presented by the server and any host name in that certificate. - // In this mode, TLS is susceptible to man-in-the-middle attacks. - // This should be used only for testing. - InsecureSkipVerify bool - - // CipherSuites is a list of supported cipher suites for TLS versions up to - // TLS 1.2. If CipherSuites is nil, a default list of secure cipher suites - // is used, with a preference order based on hardware performance. The - // default cipher suites might change over Go versions. Note that TLS 1.3 - // ciphersuites are not configurable. - CipherSuites []uint16 - - // PreferServerCipherSuites controls whether the server selects the - // client's most preferred ciphersuite, or the server's most preferred - // ciphersuite. If true then the server's preference, as expressed in - // the order of elements in CipherSuites, is used. - PreferServerCipherSuites bool - - // SessionTicketsDisabled may be set to true to disable session ticket and - // PSK (resumption) support. Note that on clients, session ticket support is - // also disabled if ClientSessionCache is nil. - SessionTicketsDisabled bool - - // SessionTicketKey is used by TLS servers to provide session resumption. - // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled - // with random data before the first server handshake. - // - // If multiple servers are terminating connections for the same host - // they should all have the same SessionTicketKey. If the - // SessionTicketKey leaks, previously recorded and future TLS - // connections using that key might be compromised. - SessionTicketKey [32]byte - - // ClientSessionCache is a cache of ClientSessionState entries for TLS - // session resumption. It is only used by clients. - ClientSessionCache ClientSessionCache - - // MinVersion contains the minimum SSL/TLS version that is acceptable. - // If zero, then TLS 1.0 is taken as the minimum. - MinVersion uint16 - - // MaxVersion contains the maximum SSL/TLS version that is acceptable. - // If zero, then the maximum version supported by this package is used, - // which is currently TLS 1.3. - MaxVersion uint16 - - // CurvePreferences contains the elliptic curves that will be used in - // an ECDHE handshake, in preference order. If empty, the default will - // be used. The client will use the first preference as the type for - // its key share in TLS 1.3. This may change in the future. - CurvePreferences []CurveID - - // DynamicRecordSizingDisabled disables adaptive sizing of TLS records. - // When true, the largest possible TLS record size is always used. When - // false, the size of TLS records may be adjusted in an attempt to - // improve latency. - DynamicRecordSizingDisabled bool - - // Renegotiation controls what types of renegotiation are supported. - // The default, none, is correct for the vast majority of applications. - Renegotiation RenegotiationSupport - - // KeyLogWriter optionally specifies a destination for TLS master secrets - // in NSS key log format that can be used to allow external programs - // such as Wireshark to decrypt TLS connections. - // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. - // Use of KeyLogWriter compromises security and should only be - // used for debugging. - KeyLogWriter io.Writer - - // GetExtensions, if not nil, is called before a message that allows - // sending of extensions is sent. - // Currently only implemented for the ClientHello message (for the client) - // and for the EncryptedExtensions message (for the server). - // Only valid for TLS 1.3. - GetExtensions func(handshakeMessageType uint8) []Extension - - // ReceivedExtensions, if not nil, is called when a message that allows the - // inclusion of extensions is received. - // It is called with an empty slice of extensions, if the message didn't - // contain any extensions. - // Currently only implemented for the ClientHello message (sent by the - // client) and for the EncryptedExtensions message (sent by the server). - // Only valid for TLS 1.3. - ReceivedExtensions func(handshakeMessageType uint8, exts []Extension) - - serverInitOnce sync.Once // guards calling (*Config).serverInit - - // mutex protects sessionTicketKeys. - mutex sync.RWMutex - // sessionTicketKeys contains zero or more ticket keys. If the length - // is zero, SessionTicketsDisabled must be true. The first key is used - // for new tickets and any subsequent keys can be used to decrypt old - // tickets. - sessionTicketKeys []ticketKey - - // AlternativeRecordLayer is used by QUIC - AlternativeRecordLayer RecordLayer -} - -type RecordLayer interface { - SetReadKey(suite *CipherSuite, trafficSecret []byte) - SetWriteKey(suite *CipherSuite, trafficSecret []byte) - ReadHandshakeMessage() ([]byte, error) - WriteRecord([]byte) (int, error) - SendAlert(uint8) -} - -// ticketKeyNameLen is the number of bytes of identifier that is prepended to -// an encrypted session ticket in order to identify the key used to encrypt it. -const ticketKeyNameLen = 16 - -// ticketKey is the internal representation of a session ticket key. -type ticketKey struct { - // keyName is an opaque byte string that serves to identify the session - // ticket key. It's exposed as plaintext in every session ticket. - keyName [ticketKeyNameLen]byte - aesKey [16]byte - hmacKey [16]byte -} - -// ticketKeyFromBytes converts from the external representation of a session -// ticket key to a ticketKey. Externally, session ticket keys are 32 random -// bytes and this function expands that into sufficient name and key material. -func ticketKeyFromBytes(b [32]byte) (key ticketKey) { - hashed := sha512.Sum512(b[:]) - copy(key.keyName[:], hashed[:ticketKeyNameLen]) - copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16]) - copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32]) - return key -} - -// maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session -// ticket, and the lifetime we set for tickets we send. -const maxSessionTicketLifetime = 7 * 24 * time.Hour - -// Clone returns a shallow clone of c. It is safe to clone a Config that is -// being used concurrently by a TLS client or server. -func (c *Config) Clone() *Config { - // Running serverInit ensures that it's safe to read - // SessionTicketsDisabled. - c.serverInitOnce.Do(func() { c.serverInit(nil) }) - - var sessionTicketKeys []ticketKey - c.mutex.RLock() - sessionTicketKeys = c.sessionTicketKeys - c.mutex.RUnlock() - - return &Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - GetClientCertificate: c.GetClientCertificate, - GetConfigForClient: c.GetConfigForClient, - VerifyPeerCertificate: c.VerifyPeerCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, - Renegotiation: c.Renegotiation, - KeyLogWriter: c.KeyLogWriter, - GetExtensions: c.GetExtensions, - ReceivedExtensions: c.ReceivedExtensions, - sessionTicketKeys: sessionTicketKeys, - } -} - -// serverInit is run under c.serverInitOnce to do initialization of c. If c was -// returned by a GetConfigForClient callback then the argument should be the -// Config that was passed to Server, otherwise it should be nil. -func (c *Config) serverInit(originalConfig *Config) { - if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 { - return - } - - alreadySet := false - for _, b := range c.SessionTicketKey { - if b != 0 { - alreadySet = true - break - } - } - - if !alreadySet { - if originalConfig != nil { - copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:]) - } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil { - c.SessionTicketsDisabled = true - return - } - } - - if originalConfig != nil { - originalConfig.mutex.RLock() - c.sessionTicketKeys = originalConfig.sessionTicketKeys - originalConfig.mutex.RUnlock() - } else { - c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)} - } -} - -func (c *Config) ticketKeys() []ticketKey { - c.mutex.RLock() - // c.sessionTicketKeys is constant once created. SetSessionTicketKeys - // will only update it by replacing it with a new value. - ret := c.sessionTicketKeys - c.mutex.RUnlock() - return ret -} - -// SetSessionTicketKeys updates the session ticket keys for a server. The first -// key will be used when creating new tickets, while all keys can be used for -// decrypting tickets. It is safe to call this function while the server is -// running in order to rotate the session ticket keys. The function will panic -// if keys is empty. -func (c *Config) SetSessionTicketKeys(keys [][32]byte) { - if len(keys) == 0 { - panic("tls: keys must have at least one key") - } - - newKeys := make([]ticketKey, len(keys)) - for i, bytes := range keys { - newKeys[i] = ticketKeyFromBytes(bytes) - } - - c.mutex.Lock() - c.sessionTicketKeys = newKeys - c.mutex.Unlock() -} - -func (c *Config) rand() io.Reader { - r := c.Rand - if r == nil { - return rand.Reader - } - return r -} - -func (c *Config) time() time.Time { - t := c.Time - if t == nil { - t = time.Now - } - return t() -} - -func (c *Config) cipherSuites() []uint16 { - s := c.CipherSuites - if s == nil { - s = defaultCipherSuites() - } - return s -} - -var supportedVersions = []uint16{ - VersionTLS13, - VersionTLS12, - VersionTLS11, - VersionTLS10, - VersionSSL30, -} - -func (c *Config) supportedVersions(isClient bool) []uint16 { - versions := make([]uint16, 0, len(supportedVersions)) - for _, v := range supportedVersions { - if c != nil && c.MinVersion != 0 && v < c.MinVersion { - continue - } - if c != nil && c.MaxVersion != 0 && v > c.MaxVersion { - continue - } - // TLS 1.0 is the minimum version supported as a client. - if isClient && v < VersionTLS10 { - continue - } - // TLS 1.3 is opt-in in Go 1.12. - if v == VersionTLS13 && !isTLS13Supported() { - continue - } - versions = append(versions, v) - } - return versions -} - -// tls13Support caches the result for isTLS13Supported. -var tls13Support struct { - sync.Once - cached bool -} - -// isTLS13Supported returns whether the program opted into TLS 1.3 via -// GODEBUG=tls13=1. It's cached after the first execution. -func isTLS13Supported() bool { - return true - tls13Support.Do(func() { - tls13Support.cached = goDebugString("tls13") == "1" - }) - return tls13Support.cached -} - -// goDebugString returns the value of the named GODEBUG key. -// GODEBUG is of the form "key=val,key2=val2". -func goDebugString(key string) string { - s := os.Getenv("GODEBUG") - for i := 0; i < len(s)-len(key)-1; i++ { - if i > 0 && s[i-1] != ',' { - continue - } - afterKey := s[i+len(key):] - if afterKey[0] != '=' || s[i:i+len(key)] != key { - continue - } - val := afterKey[1:] - for i, b := range val { - if b == ',' { - return val[:i] - } - } - return val - } - return "" -} - -func (c *Config) maxSupportedVersion(isClient bool) uint16 { - supportedVersions := c.supportedVersions(isClient) - if len(supportedVersions) == 0 { - return 0 - } - return supportedVersions[0] -} - -// supportedVersionsFromMax returns a list of supported versions derived from a -// legacy maximum version value. Note that only versions supported by this -// library are returned. Any newer peer will use supportedVersions anyway. -func supportedVersionsFromMax(maxVersion uint16) []uint16 { - versions := make([]uint16, 0, len(supportedVersions)) - for _, v := range supportedVersions { - if v > maxVersion { - continue - } - versions = append(versions, v) - } - return versions -} - -var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521} - -func (c *Config) curvePreferences() []CurveID { - if c == nil || len(c.CurvePreferences) == 0 { - return defaultCurvePreferences - } - return c.CurvePreferences -} - -// mutualVersion returns the protocol version to use given the advertised -// versions of the peer. Priority is given to the peer preference order. -func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) { - supportedVersions := c.supportedVersions(isClient) - for _, peerVersion := range peerVersions { - for _, v := range supportedVersions { - if v == peerVersion { - return v, true - } - } - } - return 0, false -} - -// getCertificate returns the best certificate for the given ClientHelloInfo, -// defaulting to the first element of c.Certificates. -func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) { - if c.GetCertificate != nil && - (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) { - cert, err := c.GetCertificate(clientHello) - if cert != nil || err != nil { - return cert, err - } - } - - if len(c.Certificates) == 0 { - return nil, errors.New("tls: no certificates configured") - } - - if len(c.Certificates) == 1 || c.NameToCertificate == nil { - // There's only one choice, so no point doing any work. - return &c.Certificates[0], nil - } - - name := strings.ToLower(clientHello.ServerName) - for len(name) > 0 && name[len(name)-1] == '.' { - name = name[:len(name)-1] - } - - if cert, ok := c.NameToCertificate[name]; ok { - return cert, nil - } - - // try replacing labels in the name with wildcards until we get a - // match. - labels := strings.Split(name, ".") - for i := range labels { - labels[i] = "*" - candidate := strings.Join(labels, ".") - if cert, ok := c.NameToCertificate[candidate]; ok { - return cert, nil - } - } - - // If nothing matches, return the first certificate. - return &c.Certificates[0], nil -} - -// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate -// from the CommonName and SubjectAlternateName fields of each of the leaf -// certificates. -func (c *Config) BuildNameToCertificate() { - c.NameToCertificate = make(map[string]*Certificate) - for i := range c.Certificates { - cert := &c.Certificates[i] - x509Cert := cert.Leaf - if x509Cert == nil { - var err error - x509Cert, err = x509.ParseCertificate(cert.Certificate[0]) - if err != nil { - continue - } - } - if len(x509Cert.Subject.CommonName) > 0 { - c.NameToCertificate[x509Cert.Subject.CommonName] = cert - } - for _, san := range x509Cert.DNSNames { - c.NameToCertificate[san] = cert - } - } -} - -const ( - keyLogLabelTLS12 = "CLIENT_RANDOM" - keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET" - keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET" - keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0" - keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0" -) - -func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error { - if c.KeyLogWriter == nil { - return nil - } - - logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret)) - - writerMutex.Lock() - _, err := c.KeyLogWriter.Write(logLine) - writerMutex.Unlock() - - return err -} - -// writerMutex protects all KeyLogWriters globally. It is rarely enabled, -// and is only for debugging, so a global mutex saves space. -var writerMutex sync.Mutex - -// A Certificate is a tls.Certificate -type Certificate = tls.Certificate - -type handshakeMessage interface { - marshal() []byte - unmarshal([]byte) bool -} - -// lruSessionCache is a ClientSessionCache implementation that uses an LRU -// caching strategy. -type lruSessionCache struct { - sync.Mutex - - m map[string]*list.Element - q *list.List - capacity int -} - -type lruSessionCacheEntry struct { - sessionKey string - state *ClientSessionState -} - -// NewLRUClientSessionCache returns a ClientSessionCache with the given -// capacity that uses an LRU strategy. If capacity is < 1, a default capacity -// is used instead. -func NewLRUClientSessionCache(capacity int) ClientSessionCache { - const defaultSessionCacheCapacity = 64 - - if capacity < 1 { - capacity = defaultSessionCacheCapacity - } - return &lruSessionCache{ - m: make(map[string]*list.Element), - q: list.New(), - capacity: capacity, - } -} - -// Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry -// corresponding to sessionKey is removed from the cache instead. -func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) { - c.Lock() - defer c.Unlock() - - if elem, ok := c.m[sessionKey]; ok { - if cs == nil { - c.q.Remove(elem) - delete(c.m, sessionKey) - } else { - entry := elem.Value.(*lruSessionCacheEntry) - entry.state = cs - c.q.MoveToFront(elem) - } - return - } - - if c.q.Len() < c.capacity { - entry := &lruSessionCacheEntry{sessionKey, cs} - c.m[sessionKey] = c.q.PushFront(entry) - return - } - - elem := c.q.Back() - entry := elem.Value.(*lruSessionCacheEntry) - delete(c.m, entry.sessionKey) - entry.sessionKey = sessionKey - entry.state = cs - c.q.MoveToFront(elem) - c.m[sessionKey] = elem -} - -// Get returns the ClientSessionState value associated with a given key. It -// returns (nil, false) if no value is found. -func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) { - c.Lock() - defer c.Unlock() - - if elem, ok := c.m[sessionKey]; ok { - c.q.MoveToFront(elem) - return elem.Value.(*lruSessionCacheEntry).state, true - } - return nil, false -} - -// TODO(jsing): Make these available to both crypto/x509 and crypto/tls. -type dsaSignature struct { - R, S *big.Int -} - -type ecdsaSignature dsaSignature - -var emptyConfig Config - -func defaultConfig() *Config { - return &emptyConfig -} - -var ( - once sync.Once - varDefaultCipherSuites []uint16 - varDefaultCipherSuitesTLS13 []uint16 -) - -func defaultCipherSuites() []uint16 { - once.Do(initDefaultCipherSuites) - return varDefaultCipherSuites -} - -func defaultCipherSuitesTLS13() []uint16 { - once.Do(initDefaultCipherSuites) - return varDefaultCipherSuitesTLS13 -} - -func initDefaultCipherSuites() { - var topCipherSuites []uint16 - - // Check the cpu flags for each platform that has optimized GCM implementations. - // Worst case, these variables will just all be false. - var ( - hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ - hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL - // Keep in sync with crypto/aes/cipher_s390x.go. - // TODO: check for s390 - // hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM) - hasGCMAsmS390X = false - - hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X - ) - - if hasGCMAsm { - // If AES-GCM hardware is provided then prioritise AES-GCM - // cipher suites. - topCipherSuites = []uint16{ - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, - TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, - } - varDefaultCipherSuitesTLS13 = []uint16{ - TLS_AES_128_GCM_SHA256, - TLS_CHACHA20_POLY1305_SHA256, - TLS_AES_256_GCM_SHA384, - } - } else { - // Without AES-GCM hardware, we put the ChaCha20-Poly1305 - // cipher suites first. - topCipherSuites = []uint16{ - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, - TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - } - varDefaultCipherSuitesTLS13 = []uint16{ - TLS_CHACHA20_POLY1305_SHA256, - TLS_AES_128_GCM_SHA256, - TLS_AES_256_GCM_SHA384, - } - } - - varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites)) - varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...) - -NextCipherSuite: - for _, suite := range cipherSuites { - if suite.flags&suiteDefaultOff != 0 { - continue - } - for _, existing := range varDefaultCipherSuites { - if existing == suite.id { - continue NextCipherSuite - } - } - varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id) - } -} - -func unexpectedMessageError(wanted, got interface{}) error { - return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) -} - -func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool { - for _, s := range supportedSignatureAlgorithms { - if s == sigAlg { - return true - } - } - return false -} - -// signatureFromSignatureScheme maps a signature algorithm to the underlying -// signature method (without hash function). -func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 { - switch signatureAlgorithm { - case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512: - return signaturePKCS1v15 - case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512: - return signatureRSAPSS - case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512: - return signatureECDSA - default: - return 0 - } -} diff --git a/vendor/github.com/marten-seemann/qtls/conn.go b/vendor/github.com/marten-seemann/qtls/conn.go deleted file mode 100644 index bbb67e563b..0000000000 --- a/vendor/github.com/marten-seemann/qtls/conn.go +++ /dev/null @@ -1,1467 +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. - -// TLS low level connection and record layer - -package qtls - -import ( - "bytes" - "crypto/cipher" - "crypto/subtle" - "crypto/x509" - "errors" - "fmt" - "io" - "net" - "sync" - "sync/atomic" - "time" -) - -// A Conn represents a secured connection. -// It implements the net.Conn interface. -type Conn struct { - // constant - conn net.Conn - isClient bool - - // handshakeStatus is 1 if the connection is currently transferring - // application data (i.e. is not currently processing a handshake). - // This field is only to be accessed with sync/atomic. - handshakeStatus uint32 - // constant after handshake; protected by handshakeMutex - handshakeMutex sync.Mutex - handshakeErr error // error resulting from handshake - vers uint16 // TLS version - haveVers bool // version has been negotiated - config *Config // configuration passed to constructor - // handshakes counts the number of handshakes performed on the - // connection so far. If renegotiation is disabled then this is either - // zero or one. - handshakes int - didResume bool // whether this connection was a session resumption - cipherSuite uint16 - ocspResponse []byte // stapled OCSP response - scts [][]byte // signed certificate timestamps from server - peerCertificates []*x509.Certificate - // verifiedChains contains the certificate chains that we built, as - // opposed to the ones presented by the server. - verifiedChains [][]*x509.Certificate - // serverName contains the server name indicated by the client, if any. - serverName string - // secureRenegotiation is true if the server echoed the secure - // renegotiation extension. (This is meaningless as a server because - // renegotiation is not supported in that case.) - secureRenegotiation bool - // ekm is a closure for exporting keying material. - ekm func(label string, context []byte, length int) ([]byte, error) - // resumptionSecret is the resumption_master_secret for handling - // NewSessionTicket messages. nil if config.SessionTicketsDisabled. - resumptionSecret []byte - - // clientFinishedIsFirst is true if the client sent the first Finished - // message during the most recent handshake. This is recorded because - // the first transmitted Finished message is the tls-unique - // channel-binding value. - clientFinishedIsFirst bool - - // closeNotifyErr is any error from sending the alertCloseNotify record. - closeNotifyErr error - // closeNotifySent is true if the Conn attempted to send an - // alertCloseNotify record. - closeNotifySent bool - - // clientFinished and serverFinished contain the Finished message sent - // by the client or server in the most recent handshake. This is - // retained to support the renegotiation extension and tls-unique - // channel-binding. - clientFinished [12]byte - serverFinished [12]byte - - clientProtocol string - clientProtocolFallback bool - - // input/output - in, out halfConn - rawInput bytes.Buffer // raw input, starting with a record header - input bytes.Reader // application data waiting to be read, from rawInput.Next - hand bytes.Buffer // handshake data waiting to be read - outBuf []byte // scratch buffer used by out.encrypt - buffering bool // whether records are buffered in sendBuf - sendBuf []byte // a buffer of records waiting to be sent - - // bytesSent counts the bytes of application data sent. - // packetsSent counts packets. - bytesSent int64 - packetsSent int64 - - // retryCount counts the number of consecutive non-advancing records - // received by Conn.readRecord. That is, records that neither advance the - // handshake, nor deliver application data. Protected by in.Mutex. - retryCount int - - // activeCall is an atomic int32; the low bit is whether Close has - // been called. the rest of the bits are the number of goroutines - // in Conn.Write. - activeCall int32 - - tmp [16]byte -} - -// Access to net.Conn methods. -// Cannot just embed net.Conn because that would -// export the struct field too. - -// LocalAddr returns the local network address. -func (c *Conn) LocalAddr() net.Addr { - return c.conn.LocalAddr() -} - -// RemoteAddr returns the remote network address. -func (c *Conn) RemoteAddr() net.Addr { - return c.conn.RemoteAddr() -} - -// SetDeadline sets the read and write deadlines associated with the connection. -// A zero value for t means Read and Write will not time out. -// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. -func (c *Conn) SetDeadline(t time.Time) error { - return c.conn.SetDeadline(t) -} - -// SetReadDeadline sets the read deadline on the underlying connection. -// A zero value for t means Read will not time out. -func (c *Conn) SetReadDeadline(t time.Time) error { - return c.conn.SetReadDeadline(t) -} - -// SetWriteDeadline sets the write deadline on the underlying connection. -// A zero value for t means Write will not time out. -// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. -func (c *Conn) SetWriteDeadline(t time.Time) error { - return c.conn.SetWriteDeadline(t) -} - -// A halfConn represents one direction of the record layer -// connection, either sending or receiving. -type halfConn struct { - sync.Mutex - - err error // first permanent error - version uint16 // protocol version - cipher interface{} // cipher algorithm - mac macFunction - seq [8]byte // 64-bit sequence number - additionalData [13]byte // to avoid allocs; interface method args escape - - nextCipher interface{} // next encryption state - nextMac macFunction // next MAC algorithm - - trafficSecret []byte // current TLS 1.3 traffic secret - - setKeyCallback func(suite *CipherSuite, trafficSecret []byte) -} - -func (hc *halfConn) setErrorLocked(err error) error { - hc.err = err - return err -} - -// prepareCipherSpec sets the encryption and MAC states -// that a subsequent changeCipherSpec will use. -func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) { - hc.version = version - hc.nextCipher = cipher - hc.nextMac = mac -} - -// changeCipherSpec changes the encryption and MAC states -// to the ones previously passed to prepareCipherSpec. -func (hc *halfConn) changeCipherSpec() error { - if hc.nextCipher == nil || hc.version == VersionTLS13 { - return alertInternalError - } - hc.cipher = hc.nextCipher - hc.mac = hc.nextMac - hc.nextCipher = nil - hc.nextMac = nil - for i := range hc.seq { - hc.seq[i] = 0 - } - return nil -} - -func (hc *halfConn) exportKey(suite *cipherSuiteTLS13, trafficSecret []byte) { - if hc.setKeyCallback != nil { - hc.setKeyCallback(&CipherSuite{suite}, trafficSecret) - } -} - -func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, secret []byte) { - hc.trafficSecret = secret - key, iv := suite.trafficKey(secret) - hc.cipher = suite.aead(key, iv) - for i := range hc.seq { - hc.seq[i] = 0 - } -} - -// incSeq increments the sequence number. -func (hc *halfConn) incSeq() { - for i := 7; i >= 0; i-- { - hc.seq[i]++ - if hc.seq[i] != 0 { - return - } - } - - // Not allowed to let sequence number wrap. - // Instead, must renegotiate before it does. - // Not likely enough to bother. - panic("TLS: sequence number wraparound") -} - -// explicitNonceLen returns the number of bytes of explicit nonce or IV included -// in each record. Explicit nonces are present only in CBC modes after TLS 1.0 -// and in certain AEAD modes in TLS 1.2. -func (hc *halfConn) explicitNonceLen() int { - if hc.cipher == nil { - return 0 - } - - switch c := hc.cipher.(type) { - case cipher.Stream: - return 0 - case aead: - return c.explicitNonceLen() - case cbcMode: - // TLS 1.1 introduced a per-record explicit IV to fix the BEAST attack. - if hc.version >= VersionTLS11 { - return c.BlockSize() - } - return 0 - default: - panic("unknown cipher type") - } -} - -// extractPadding returns, in constant time, the length of the padding to remove -// from the end of payload. It also returns a byte which is equal to 255 if the -// padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2. -func extractPadding(payload []byte) (toRemove int, good byte) { - if len(payload) < 1 { - return 0, 0 - } - - paddingLen := payload[len(payload)-1] - t := uint(len(payload)-1) - uint(paddingLen) - // if len(payload) >= (paddingLen - 1) then the MSB of t is zero - good = byte(int32(^t) >> 31) - - // The maximum possible padding length plus the actual length field - toCheck := 256 - // The length of the padded data is public, so we can use an if here - if toCheck > len(payload) { - toCheck = len(payload) - } - - for i := 0; i < toCheck; i++ { - t := uint(paddingLen) - uint(i) - // if i <= paddingLen then the MSB of t is zero - mask := byte(int32(^t) >> 31) - b := payload[len(payload)-1-i] - good &^= mask&paddingLen ^ mask&b - } - - // We AND together the bits of good and replicate the result across - // all the bits. - good &= good << 4 - good &= good << 2 - good &= good << 1 - good = uint8(int8(good) >> 7) - - toRemove = int(paddingLen) + 1 - return -} - -// extractPaddingSSL30 is a replacement for extractPadding in the case that the -// protocol version is SSLv3. In this version, the contents of the padding -// are random and cannot be checked. -func extractPaddingSSL30(payload []byte) (toRemove int, good byte) { - if len(payload) < 1 { - return 0, 0 - } - - paddingLen := int(payload[len(payload)-1]) + 1 - if paddingLen > len(payload) { - return 0, 0 - } - - return paddingLen, 255 -} - -func roundUp(a, b int) int { - return a + (b-a%b)%b -} - -// cbcMode is an interface for block ciphers using cipher block chaining. -type cbcMode interface { - cipher.BlockMode - SetIV([]byte) -} - -// decrypt authenticates and decrypts the record if protection is active at -// this stage. The returned plaintext might overlap with the input. -func (hc *halfConn) decrypt(record []byte) ([]byte, recordType, error) { - var plaintext []byte - typ := recordType(record[0]) - payload := record[recordHeaderLen:] - - // In TLS 1.3, change_cipher_spec messages are to be ignored without being - // decrypted. See RFC 8446, Appendix D.4. - if hc.version == VersionTLS13 && typ == recordTypeChangeCipherSpec { - return payload, typ, nil - } - - paddingGood := byte(255) - paddingLen := 0 - - explicitNonceLen := hc.explicitNonceLen() - - if hc.cipher != nil { - switch c := hc.cipher.(type) { - case cipher.Stream: - c.XORKeyStream(payload, payload) - case aead: - if len(payload) < explicitNonceLen { - return nil, 0, alertBadRecordMAC - } - nonce := payload[:explicitNonceLen] - if len(nonce) == 0 { - nonce = hc.seq[:] - } - payload = payload[explicitNonceLen:] - - additionalData := hc.additionalData[:] - if hc.version == VersionTLS13 { - additionalData = record[:recordHeaderLen] - } else { - copy(additionalData, hc.seq[:]) - copy(additionalData[8:], record[:3]) - n := len(payload) - c.Overhead() - additionalData[11] = byte(n >> 8) - additionalData[12] = byte(n) - } - - var err error - plaintext, err = c.Open(payload[:0], nonce, payload, additionalData) - if err != nil { - return nil, 0, alertBadRecordMAC - } - case cbcMode: - blockSize := c.BlockSize() - minPayload := explicitNonceLen + roundUp(hc.mac.Size()+1, blockSize) - if len(payload)%blockSize != 0 || len(payload) < minPayload { - return nil, 0, alertBadRecordMAC - } - - if explicitNonceLen > 0 { - c.SetIV(payload[:explicitNonceLen]) - payload = payload[explicitNonceLen:] - } - c.CryptBlocks(payload, payload) - - // In a limited attempt to protect against CBC padding oracles like - // Lucky13, the data past paddingLen (which is secret) is passed to - // the MAC function as extra data, to be fed into the HMAC after - // computing the digest. This makes the MAC roughly constant time as - // long as the digest computation is constant time and does not - // affect the subsequent write, modulo cache effects. - if hc.version == VersionSSL30 { - paddingLen, paddingGood = extractPaddingSSL30(payload) - } else { - paddingLen, paddingGood = extractPadding(payload) - } - default: - panic("unknown cipher type") - } - - if hc.version == VersionTLS13 { - if typ != recordTypeApplicationData { - return nil, 0, alertUnexpectedMessage - } - if len(plaintext) > maxPlaintext+1 { - return nil, 0, alertRecordOverflow - } - // Remove padding and find the ContentType scanning from the end. - for i := len(plaintext) - 1; i >= 0; i-- { - if plaintext[i] != 0 { - typ = recordType(plaintext[i]) - plaintext = plaintext[:i] - break - } - if i == 0 { - return nil, 0, alertUnexpectedMessage - } - } - } - } else { - plaintext = payload - } - - if hc.mac != nil { - macSize := hc.mac.Size() - if len(payload) < macSize { - return nil, 0, alertBadRecordMAC - } - - n := len(payload) - macSize - paddingLen - n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 } - record[3] = byte(n >> 8) - record[4] = byte(n) - remoteMAC := payload[n : n+macSize] - localMAC := hc.mac.MAC(hc.seq[0:], record[:recordHeaderLen], payload[:n], payload[n+macSize:]) - - if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 { - return nil, 0, alertBadRecordMAC - } - - plaintext = payload[:n] - } - - hc.incSeq() - return plaintext, typ, nil -} - -func (c *Conn) setAlternativeRecordLayer() { - if c.config.AlternativeRecordLayer != nil { - c.in.setKeyCallback = c.config.AlternativeRecordLayer.SetReadKey - c.out.setKeyCallback = c.config.AlternativeRecordLayer.SetWriteKey - } -} - -// sliceForAppend extends the input slice by n bytes. head is the full extended -// slice, while tail is the appended part. If the original slice has sufficient -// capacity no allocation is performed. -func sliceForAppend(in []byte, n int) (head, tail []byte) { - if total := len(in) + n; cap(in) >= total { - head = in[:total] - } else { - head = make([]byte, total) - copy(head, in) - } - tail = head[len(in):] - return -} - -// encrypt encrypts payload, adding the appropriate nonce and/or MAC, and -// appends it to record, which contains the record header. -func (hc *halfConn) encrypt(record, payload []byte, rand io.Reader) ([]byte, error) { - if hc.cipher == nil { - return append(record, payload...), nil - } - - var explicitNonce []byte - if explicitNonceLen := hc.explicitNonceLen(); explicitNonceLen > 0 { - record, explicitNonce = sliceForAppend(record, explicitNonceLen) - if _, isCBC := hc.cipher.(cbcMode); !isCBC && explicitNonceLen < 16 { - // The AES-GCM construction in TLS has an explicit nonce so that the - // nonce can be random. However, the nonce is only 8 bytes which is - // too small for a secure, random nonce. Therefore we use the - // sequence number as the nonce. The 3DES-CBC construction also has - // an 8 bytes nonce but its nonces must be unpredictable (see RFC - // 5246, Appendix F.3), forcing us to use randomness. That's not - // 3DES' biggest problem anyway because the birthday bound on block - // collision is reached first due to its simlarly small block size - // (see the Sweet32 attack). - copy(explicitNonce, hc.seq[:]) - } else { - if _, err := io.ReadFull(rand, explicitNonce); err != nil { - return nil, err - } - } - } - - var mac []byte - if hc.mac != nil { - mac = hc.mac.MAC(hc.seq[:], record[:recordHeaderLen], payload, nil) - } - - var dst []byte - switch c := hc.cipher.(type) { - case cipher.Stream: - record, dst = sliceForAppend(record, len(payload)+len(mac)) - c.XORKeyStream(dst[:len(payload)], payload) - c.XORKeyStream(dst[len(payload):], mac) - case aead: - nonce := explicitNonce - if len(nonce) == 0 { - nonce = hc.seq[:] - } - - if hc.version == VersionTLS13 { - record = append(record, payload...) - - // Encrypt the actual ContentType and replace the plaintext one. - record = append(record, record[0]) - record[0] = byte(recordTypeApplicationData) - - n := len(payload) + 1 + c.Overhead() - record[3] = byte(n >> 8) - record[4] = byte(n) - - record = c.Seal(record[:recordHeaderLen], - nonce, record[recordHeaderLen:], record[:recordHeaderLen]) - } else { - copy(hc.additionalData[:], hc.seq[:]) - copy(hc.additionalData[8:], record) - record = c.Seal(record, nonce, payload, hc.additionalData[:]) - } - case cbcMode: - blockSize := c.BlockSize() - plaintextLen := len(payload) + len(mac) - paddingLen := blockSize - plaintextLen%blockSize - record, dst = sliceForAppend(record, plaintextLen+paddingLen) - copy(dst, payload) - copy(dst[len(payload):], mac) - for i := plaintextLen; i < len(dst); i++ { - dst[i] = byte(paddingLen - 1) - } - if len(explicitNonce) > 0 { - c.SetIV(explicitNonce) - } - c.CryptBlocks(dst, dst) - default: - panic("unknown cipher type") - } - - // Update length to include nonce, MAC and any block padding needed. - n := len(record) - recordHeaderLen - record[3] = byte(n >> 8) - record[4] = byte(n) - hc.incSeq() - - return record, nil -} - -// RecordHeaderError is returned when a TLS record header is invalid. -type RecordHeaderError struct { - // Msg contains a human readable string that describes the error. - Msg string - // RecordHeader contains the five bytes of TLS record header that - // triggered the error. - RecordHeader [5]byte - // Conn provides the underlying net.Conn in the case that a client - // sent an initial handshake that didn't look like TLS. - // It is nil if there's already been a handshake or a TLS alert has - // been written to the connection. - Conn net.Conn -} - -func (e RecordHeaderError) Error() string { return "tls: " + e.Msg } - -func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err RecordHeaderError) { - err.Msg = msg - err.Conn = conn - copy(err.RecordHeader[:], c.rawInput.Bytes()) - return err -} - -func (c *Conn) readRecord() error { - return c.readRecordOrCCS(false) -} - -func (c *Conn) readChangeCipherSpec() error { - return c.readRecordOrCCS(true) -} - -// readRecordOrCCS reads one or more TLS records from the connection and -// updates the record layer state. Some invariants: -// * c.in must be locked -// * c.input must be empty -// During the handshake one and only one of the following will happen: -// - c.hand grows -// - c.in.changeCipherSpec is called -// - an error is returned -// After the handshake one and only one of the following will happen: -// - c.hand grows -// - c.input is set -// - an error is returned -func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error { - if c.in.err != nil { - return c.in.err - } - handshakeComplete := c.handshakeComplete() - - // This function modifies c.rawInput, which owns the c.input memory. - if c.input.Len() != 0 { - return c.in.setErrorLocked(errors.New("tls: internal error: attempted to read record with pending application data")) - } - c.input.Reset(nil) - - // Read header, payload. - if err := c.readFromUntil(c.conn, recordHeaderLen); err != nil { - // RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify - // is an error, but popular web sites seem to do this, so we accept it - // if and only if at the record boundary. - if err == io.ErrUnexpectedEOF && c.rawInput.Len() == 0 { - err = io.EOF - } - if e, ok := err.(net.Error); !ok || !e.Temporary() { - c.in.setErrorLocked(err) - } - return err - } - hdr := c.rawInput.Bytes()[:recordHeaderLen] - typ := recordType(hdr[0]) - - // No valid TLS record has a type of 0x80, however SSLv2 handshakes - // start with a uint16 length where the MSB is set and the first record - // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests - // an SSLv2 client. - if !handshakeComplete && typ == 0x80 { - c.sendAlert(alertProtocolVersion) - return c.in.setErrorLocked(c.newRecordHeaderError(nil, "unsupported SSLv2 handshake received")) - } - - vers := uint16(hdr[1])<<8 | uint16(hdr[2]) - n := int(hdr[3])<<8 | int(hdr[4]) - if c.haveVers && c.vers != VersionTLS13 && vers != c.vers { - c.sendAlert(alertProtocolVersion) - msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, c.vers) - return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg)) - } - if !c.haveVers { - // First message, be extra suspicious: this might not be a TLS - // client. Bail out before reading a full 'body', if possible. - // The current max version is 3.3 so if the version is >= 16.0, - // it's probably not real. - if (typ != recordTypeAlert && typ != recordTypeHandshake) || vers >= 0x1000 { - return c.in.setErrorLocked(c.newRecordHeaderError(c.conn, "first record does not look like a TLS handshake")) - } - } - if c.vers == VersionTLS13 && n > maxCiphertextTLS13 || n > maxCiphertext { - c.sendAlert(alertRecordOverflow) - msg := fmt.Sprintf("oversized record received with length %d", n) - return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg)) - } - if err := c.readFromUntil(c.conn, recordHeaderLen+n); err != nil { - if e, ok := err.(net.Error); !ok || !e.Temporary() { - c.in.setErrorLocked(err) - } - return err - } - - // Process message. - record := c.rawInput.Next(recordHeaderLen + n) - data, typ, err := c.in.decrypt(record) - if err != nil { - return c.in.setErrorLocked(c.sendAlert(err.(alert))) - } - if len(data) > maxPlaintext { - return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow)) - } - - // Application Data messages are always protected. - if c.in.cipher == nil && typ == recordTypeApplicationData { - return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - - if typ != recordTypeAlert && typ != recordTypeChangeCipherSpec && len(data) > 0 { - // This is a state-advancing message: reset the retry count. - c.retryCount = 0 - } - - // Handshake messages MUST NOT be interleaved with other record types in TLS 1.3. - if c.vers == VersionTLS13 && typ != recordTypeHandshake && c.hand.Len() > 0 { - return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - - switch typ { - default: - return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - - case recordTypeAlert: - if len(data) != 2 { - return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - if alert(data[1]) == alertCloseNotify { - return c.in.setErrorLocked(io.EOF) - } - if c.vers == VersionTLS13 { - return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) - } - switch data[0] { - case alertLevelWarning: - // Drop the record on the floor and retry. - return c.retryReadRecord(expectChangeCipherSpec) - case alertLevelError: - return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) - default: - return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - - case recordTypeChangeCipherSpec: - if len(data) != 1 || data[0] != 1 { - return c.in.setErrorLocked(c.sendAlert(alertDecodeError)) - } - // Handshake messages are not allowed to fragment across the CCS. - if c.hand.Len() > 0 { - return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - // In TLS 1.3, change_cipher_spec records are ignored until the - // Finished. See RFC 8446, Appendix D.4. Note that according to Section - // 5, a server can send a ChangeCipherSpec before its ServerHello, when - // c.vers is still unset. That's not useful though and suspicious if the - // server then selects a lower protocol version, so don't allow that. - if c.vers == VersionTLS13 { - return c.retryReadRecord(expectChangeCipherSpec) - } - if !expectChangeCipherSpec { - return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - if err := c.in.changeCipherSpec(); err != nil { - return c.in.setErrorLocked(c.sendAlert(err.(alert))) - } - - case recordTypeApplicationData: - if !handshakeComplete || expectChangeCipherSpec { - return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - // Some OpenSSL servers send empty records in order to randomize the - // CBC IV. Ignore a limited number of empty records. - if len(data) == 0 { - return c.retryReadRecord(expectChangeCipherSpec) - } - // Note that data is owned by c.rawInput, following the Next call above, - // to avoid copying the plaintext. This is safe because c.rawInput is - // not read from or written to until c.input is drained. - c.input.Reset(data) - - case recordTypeHandshake: - if len(data) == 0 || expectChangeCipherSpec { - return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - c.hand.Write(data) - } - - return nil -} - -// retryReadRecord recurses into readRecordOrCCS to drop a non-advancing record, like -// a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3. -func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error { - c.retryCount++ - if c.retryCount > maxUselessRecords { - c.sendAlert(alertUnexpectedMessage) - return c.in.setErrorLocked(errors.New("tls: too many ignored records")) - } - return c.readRecordOrCCS(expectChangeCipherSpec) -} - -// atLeastReader reads from R, stopping with EOF once at least N bytes have been -// read. It is different from an io.LimitedReader in that it doesn't cut short -// the last Read call, and in that it considers an early EOF an error. -type atLeastReader struct { - R io.Reader - N int64 -} - -func (r *atLeastReader) Read(p []byte) (int, error) { - if r.N <= 0 { - return 0, io.EOF - } - n, err := r.R.Read(p) - r.N -= int64(n) // won't underflow unless len(p) >= n > 9223372036854775809 - if r.N > 0 && err == io.EOF { - return n, io.ErrUnexpectedEOF - } - if r.N <= 0 && err == nil { - return n, io.EOF - } - return n, err -} - -// readFromUntil reads from r into c.rawInput until c.rawInput contains -// at least n bytes or else returns an error. -func (c *Conn) readFromUntil(r io.Reader, n int) error { - if c.rawInput.Len() >= n { - return nil - } - needs := n - c.rawInput.Len() - // There might be extra input waiting on the wire. Make a best effort - // attempt to fetch it so that it can be used in (*Conn).Read to - // "predict" closeNotify alerts. - c.rawInput.Grow(needs + bytes.MinRead) - _, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)}) - return err -} - -// sendAlert sends a TLS alert message. -func (c *Conn) sendAlertLocked(err alert) error { - switch err { - case alertNoRenegotiation, alertCloseNotify: - c.tmp[0] = alertLevelWarning - default: - c.tmp[0] = alertLevelError - } - c.tmp[1] = byte(err) - - _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2]) - if err == alertCloseNotify { - // closeNotify is a special case in that it isn't an error. - return writeErr - } - - return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) -} - -// sendAlert sends a TLS alert message. -func (c *Conn) sendAlert(err alert) error { - if c.config.AlternativeRecordLayer != nil { - c.config.AlternativeRecordLayer.SendAlert(uint8(err)) - return &net.OpError{Op: "local error", Err: err} - } - - c.out.Lock() - defer c.out.Unlock() - return c.sendAlertLocked(err) -} - -const ( - // tcpMSSEstimate is a conservative estimate of the TCP maximum segment - // size (MSS). A constant is used, rather than querying the kernel for - // the actual MSS, to avoid complexity. The value here is the IPv6 - // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40 - // bytes) and a TCP header with timestamps (32 bytes). - tcpMSSEstimate = 1208 - - // recordSizeBoostThreshold is the number of bytes of application data - // sent after which the TLS record size will be increased to the - // maximum. - recordSizeBoostThreshold = 128 * 1024 -) - -// maxPayloadSizeForWrite returns the maximum TLS payload size to use for the -// next application data record. There is the following trade-off: -// -// - For latency-sensitive applications, such as web browsing, each TLS -// record should fit in one TCP segment. -// - For throughput-sensitive applications, such as large file transfers, -// larger TLS records better amortize framing and encryption overheads. -// -// A simple heuristic that works well in practice is to use small records for -// the first 1MB of data, then use larger records for subsequent data, and -// reset back to smaller records after the connection becomes idle. See "High -// Performance Web Networking", Chapter 4, or: -// https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/ -// -// In the interests of simplicity and determinism, this code does not attempt -// to reset the record size once the connection is idle, however. -func (c *Conn) maxPayloadSizeForWrite(typ recordType) int { - if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData { - return maxPlaintext - } - - if c.bytesSent >= recordSizeBoostThreshold { - return maxPlaintext - } - - // Subtract TLS overheads to get the maximum payload size. - payloadBytes := tcpMSSEstimate - recordHeaderLen - c.out.explicitNonceLen() - if c.out.cipher != nil { - switch ciph := c.out.cipher.(type) { - case cipher.Stream: - payloadBytes -= c.out.mac.Size() - case cipher.AEAD: - payloadBytes -= ciph.Overhead() - case cbcMode: - blockSize := ciph.BlockSize() - // The payload must fit in a multiple of blockSize, with - // room for at least one padding byte. - payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1 - // The MAC is appended before padding so affects the - // payload size directly. - payloadBytes -= c.out.mac.Size() - default: - panic("unknown cipher type") - } - } - if c.vers == VersionTLS13 { - payloadBytes-- // encrypted ContentType - } - - // Allow packet growth in arithmetic progression up to max. - pkt := c.packetsSent - c.packetsSent++ - if pkt > 1000 { - return maxPlaintext // avoid overflow in multiply below - } - - n := payloadBytes * int(pkt+1) - if n > maxPlaintext { - n = maxPlaintext - } - return n -} - -func (c *Conn) write(data []byte) (int, error) { - if c.buffering { - c.sendBuf = append(c.sendBuf, data...) - return len(data), nil - } - - n, err := c.conn.Write(data) - c.bytesSent += int64(n) - return n, err -} - -func (c *Conn) flush() (int, error) { - if len(c.sendBuf) == 0 { - return 0, nil - } - - n, err := c.conn.Write(c.sendBuf) - c.bytesSent += int64(n) - c.sendBuf = nil - c.buffering = false - return n, err -} - -// writeRecordLocked writes a TLS record with the given type and payload to the -// connection and updates the record layer state. -func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) { - var n int - for len(data) > 0 { - m := len(data) - if maxPayload := c.maxPayloadSizeForWrite(typ); m > maxPayload { - m = maxPayload - } - - _, c.outBuf = sliceForAppend(c.outBuf[:0], recordHeaderLen) - c.outBuf[0] = byte(typ) - vers := c.vers - if vers == 0 { - // Some TLS servers fail if the record version is - // greater than TLS 1.0 for the initial ClientHello. - vers = VersionTLS10 - } else if vers == VersionTLS13 { - // TLS 1.3 froze the record layer version to 1.2. - // See RFC 8446, Section 5.1. - vers = VersionTLS12 - } - c.outBuf[1] = byte(vers >> 8) - c.outBuf[2] = byte(vers) - c.outBuf[3] = byte(m >> 8) - c.outBuf[4] = byte(m) - - var err error - c.outBuf, err = c.out.encrypt(c.outBuf, data[:m], c.config.rand()) - if err != nil { - return n, err - } - if _, err := c.write(c.outBuf); err != nil { - return n, err - } - n += m - data = data[m:] - } - - if typ == recordTypeChangeCipherSpec && c.vers != VersionTLS13 { - if err := c.out.changeCipherSpec(); err != nil { - return n, c.sendAlertLocked(err.(alert)) - } - } - - return n, nil -} - -// writeRecord writes a TLS record with the given type and payload to the -// connection and updates the record layer state. -func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) { - if c.config.AlternativeRecordLayer != nil { - if typ == recordTypeChangeCipherSpec { - return len(data), nil - } - return c.config.AlternativeRecordLayer.WriteRecord(data) - } - - c.out.Lock() - defer c.out.Unlock() - - return c.writeRecordLocked(typ, data) -} - -// readHandshake reads the next handshake message from -// the record layer. -func (c *Conn) readHandshake() (interface{}, error) { - var data []byte - if c.config.AlternativeRecordLayer != nil { - var err error - data, err = c.config.AlternativeRecordLayer.ReadHandshakeMessage() - if err != nil { - return nil, err - } - } else { - for c.hand.Len() < 4 { - if err := c.readRecord(); err != nil { - return nil, err - } - } - - data = c.hand.Bytes() - n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) - if n > maxHandshake { - c.sendAlertLocked(alertInternalError) - return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake)) - } - for c.hand.Len() < 4+n { - if err := c.readRecord(); err != nil { - return nil, err - } - } - data = c.hand.Next(4 + n) - } - var m handshakeMessage - switch data[0] { - case typeHelloRequest: - m = new(helloRequestMsg) - case typeClientHello: - m = new(clientHelloMsg) - case typeServerHello: - m = new(serverHelloMsg) - case typeNewSessionTicket: - if c.vers == VersionTLS13 { - m = new(newSessionTicketMsgTLS13) - } else { - m = new(newSessionTicketMsg) - } - case typeCertificate: - if c.vers == VersionTLS13 { - m = new(certificateMsgTLS13) - } else { - m = new(certificateMsg) - } - case typeCertificateRequest: - if c.vers == VersionTLS13 { - m = new(certificateRequestMsgTLS13) - } else { - m = &certificateRequestMsg{ - hasSignatureAlgorithm: c.vers >= VersionTLS12, - } - } - case typeCertificateStatus: - m = new(certificateStatusMsg) - case typeServerKeyExchange: - m = new(serverKeyExchangeMsg) - case typeServerHelloDone: - m = new(serverHelloDoneMsg) - case typeClientKeyExchange: - m = new(clientKeyExchangeMsg) - case typeCertificateVerify: - m = &certificateVerifyMsg{ - hasSignatureAlgorithm: c.vers >= VersionTLS12, - } - case typeNextProtocol: - m = new(nextProtoMsg) - case typeFinished: - m = new(finishedMsg) - case typeEncryptedExtensions: - m = new(encryptedExtensionsMsg) - case typeEndOfEarlyData: - m = new(endOfEarlyDataMsg) - case typeKeyUpdate: - m = new(keyUpdateMsg) - default: - return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - - // The handshake message unmarshalers - // expect to be able to keep references to data, - // so pass in a fresh copy that won't be overwritten. - data = append([]byte(nil), data...) - - if !m.unmarshal(data) { - return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - return m, nil -} - -var ( - errClosed = errors.New("tls: use of closed connection") - errShutdown = errors.New("tls: protocol is shutdown") -) - -// Write writes data to the connection. -func (c *Conn) Write(b []byte) (int, error) { - // interlock with Close below - for { - x := atomic.LoadInt32(&c.activeCall) - if x&1 != 0 { - return 0, errClosed - } - if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) { - defer atomic.AddInt32(&c.activeCall, -2) - break - } - } - - if err := c.Handshake(); err != nil { - return 0, err - } - - c.out.Lock() - defer c.out.Unlock() - - if err := c.out.err; err != nil { - return 0, err - } - - if !c.handshakeComplete() { - return 0, alertInternalError - } - - if c.closeNotifySent { - return 0, errShutdown - } - - // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext - // attack when using block mode ciphers due to predictable IVs. - // This can be prevented by splitting each Application Data - // record into two records, effectively randomizing the IV. - // - // https://www.openssl.org/~bodo/tls-cbc.txt - // https://bugzilla.mozilla.org/show_bug.cgi?id=665814 - // https://www.imperialviolet.org/2012/01/15/beastfollowup.html - - var m int - if len(b) > 1 && c.vers <= VersionTLS10 { - if _, ok := c.out.cipher.(cipher.BlockMode); ok { - n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1]) - if err != nil { - return n, c.out.setErrorLocked(err) - } - m, b = 1, b[1:] - } - } - - n, err := c.writeRecordLocked(recordTypeApplicationData, b) - return n + m, c.out.setErrorLocked(err) -} - -// handleRenegotiation processes a HelloRequest handshake message. -func (c *Conn) handleRenegotiation() error { - if c.vers == VersionTLS13 { - return errors.New("tls: internal error: unexpected renegotiation") - } - - msg, err := c.readHandshake() - if err != nil { - return err - } - - helloReq, ok := msg.(*helloRequestMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(helloReq, msg) - } - - if !c.isClient { - return c.sendAlert(alertNoRenegotiation) - } - - switch c.config.Renegotiation { - case RenegotiateNever: - return c.sendAlert(alertNoRenegotiation) - case RenegotiateOnceAsClient: - if c.handshakes > 1 { - return c.sendAlert(alertNoRenegotiation) - } - case RenegotiateFreelyAsClient: - // Ok. - default: - c.sendAlert(alertInternalError) - return errors.New("tls: unknown Renegotiation value") - } - - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - - atomic.StoreUint32(&c.handshakeStatus, 0) - if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil { - c.handshakes++ - } - return c.handshakeErr -} - -func (c *Conn) HandlePostHandshakeMessage() error { - return c.handlePostHandshakeMessage() -} - -// handlePostHandshakeMessage processes a handshake message arrived after the -// handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation. -func (c *Conn) handlePostHandshakeMessage() error { - if c.vers != VersionTLS13 { - return c.handleRenegotiation() - } - - msg, err := c.readHandshake() - if err != nil { - return err - } - - c.retryCount++ - if c.retryCount > maxUselessRecords { - c.sendAlert(alertUnexpectedMessage) - return c.in.setErrorLocked(errors.New("tls: too many non-advancing records")) - } - - switch msg := msg.(type) { - case *newSessionTicketMsgTLS13: - return c.handleNewSessionTicket(msg) - case *keyUpdateMsg: - return c.handleKeyUpdate(msg) - default: - c.sendAlert(alertUnexpectedMessage) - return fmt.Errorf("tls: received unexpected handshake message of type %T", msg) - } -} - -func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error { - cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) - if cipherSuite == nil { - return c.in.setErrorLocked(c.sendAlert(alertInternalError)) - } - - newSecret := cipherSuite.nextTrafficSecret(c.in.trafficSecret) - c.in.setTrafficSecret(cipherSuite, newSecret) - - if keyUpdate.updateRequested { - c.out.Lock() - defer c.out.Unlock() - - msg := &keyUpdateMsg{} - _, err := c.writeRecordLocked(recordTypeHandshake, msg.marshal()) - if err != nil { - // Surface the error at the next write. - c.out.setErrorLocked(err) - return nil - } - - newSecret := cipherSuite.nextTrafficSecret(c.out.trafficSecret) - c.out.setTrafficSecret(cipherSuite, newSecret) - } - - return nil -} - -// Read can be made to time out and return a net.Error with Timeout() == true -// after a fixed time limit; see SetDeadline and SetReadDeadline. -func (c *Conn) Read(b []byte) (int, error) { - if err := c.Handshake(); err != nil { - return 0, err - } - if len(b) == 0 { - // Put this after Handshake, in case people were calling - // Read(nil) for the side effect of the Handshake. - return 0, nil - } - - c.in.Lock() - defer c.in.Unlock() - - for c.input.Len() == 0 { - if err := c.readRecord(); err != nil { - return 0, err - } - for c.hand.Len() > 0 { - if err := c.handlePostHandshakeMessage(); err != nil { - return 0, err - } - } - } - - n, _ := c.input.Read(b) - - // If a close-notify alert is waiting, read it so that we can return (n, - // EOF) instead of (n, nil), to signal to the HTTP response reading - // goroutine that the connection is now closed. This eliminates a race - // where the HTTP response reading goroutine would otherwise not observe - // the EOF until its next read, by which time a client goroutine might - // have already tried to reuse the HTTP connection for a new request. - // See https://golang.org/cl/76400046 and https://golang.org/issue/3514 - if n != 0 && c.input.Len() == 0 && c.rawInput.Len() > 0 && - recordType(c.rawInput.Bytes()[0]) == recordTypeAlert { - if err := c.readRecord(); err != nil { - return n, err // will be io.EOF on closeNotify - } - } - - return n, nil -} - -// Close closes the connection. -func (c *Conn) Close() error { - // Interlock with Conn.Write above. - var x int32 - for { - x = atomic.LoadInt32(&c.activeCall) - if x&1 != 0 { - return errClosed - } - if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) { - break - } - } - if x != 0 { - // io.Writer and io.Closer should not be used concurrently. - // If Close is called while a Write is currently in-flight, - // interpret that as a sign that this Close is really just - // being used to break the Write and/or clean up resources and - // avoid sending the alertCloseNotify, which may block - // waiting on handshakeMutex or the c.out mutex. - return c.conn.Close() - } - - var alertErr error - - if c.handshakeComplete() { - alertErr = c.closeNotify() - } - - if err := c.conn.Close(); err != nil { - return err - } - return alertErr -} - -var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete") - -// CloseWrite shuts down the writing side of the connection. It should only be -// called once the handshake has completed and does not call CloseWrite on the -// underlying connection. Most callers should just use Close. -func (c *Conn) CloseWrite() error { - if !c.handshakeComplete() { - return errEarlyCloseWrite - } - - return c.closeNotify() -} - -func (c *Conn) closeNotify() error { - c.out.Lock() - defer c.out.Unlock() - - if !c.closeNotifySent { - c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify) - c.closeNotifySent = true - } - return c.closeNotifyErr -} - -// Handshake runs the client or server handshake -// protocol if it has not yet been run. -// Most uses of this package need not call Handshake -// explicitly: the first Read or Write will call it automatically. -func (c *Conn) Handshake() error { - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - - if err := c.handshakeErr; err != nil { - return err - } - if c.handshakeComplete() { - return nil - } - - c.in.Lock() - defer c.in.Unlock() - - if c.isClient { - c.handshakeErr = c.clientHandshake() - } else { - c.handshakeErr = c.serverHandshake() - } - if c.handshakeErr == nil { - c.handshakes++ - } else { - // If an error occurred during the hadshake try to flush the - // alert that might be left in the buffer. - c.flush() - } - - if c.handshakeErr == nil && !c.handshakeComplete() { - c.handshakeErr = errors.New("tls: internal error: handshake should have had a result") - } - - return c.handshakeErr -} - -// ConnectionState returns basic TLS details about the connection. -func (c *Conn) ConnectionState() ConnectionState { - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - - var state ConnectionState - state.HandshakeComplete = c.handshakeComplete() - state.ServerName = c.serverName - - if state.HandshakeComplete { - state.Version = c.vers - state.NegotiatedProtocol = c.clientProtocol - state.DidResume = c.didResume - state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback - state.CipherSuite = c.cipherSuite - state.PeerCertificates = c.peerCertificates - state.VerifiedChains = c.verifiedChains - state.SignedCertificateTimestamps = c.scts - state.OCSPResponse = c.ocspResponse - if !c.didResume && c.vers != VersionTLS13 { - if c.clientFinishedIsFirst { - state.TLSUnique = c.clientFinished[:] - } else { - state.TLSUnique = c.serverFinished[:] - } - } - if c.config.Renegotiation != RenegotiateNever { - state.ekm = noExportedKeyingMaterial - } else { - state.ekm = c.ekm - } - } - - return state -} - -// OCSPResponse returns the stapled OCSP response from the TLS server, if -// any. (Only valid for client connections.) -func (c *Conn) OCSPResponse() []byte { - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - - return c.ocspResponse -} - -// VerifyHostname checks that the peer certificate chain is valid for -// connecting to host. If so, it returns nil; if not, it returns an error -// describing the problem. -func (c *Conn) VerifyHostname(host string) error { - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - if !c.isClient { - return errors.New("tls: VerifyHostname called on TLS server connection") - } - if !c.handshakeComplete() { - return errors.New("tls: handshake has not yet been performed") - } - if len(c.verifiedChains) == 0 { - return errors.New("tls: handshake did not verify certificate chain") - } - return c.peerCertificates[0].VerifyHostname(host) -} - -func (c *Conn) handshakeComplete() bool { - return atomic.LoadUint32(&c.handshakeStatus) == 1 -} diff --git a/vendor/github.com/marten-seemann/qtls/generate_cert.go b/vendor/github.com/marten-seemann/qtls/generate_cert.go deleted file mode 100644 index 8d012be75c..0000000000 --- a/vendor/github.com/marten-seemann/qtls/generate_cert.go +++ /dev/null @@ -1,169 +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 - -// Generate a self-signed X.509 certificate for a TLS server. Outputs to -// 'cert.pem' and 'key.pem' and will overwrite existing files. - -package main - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "flag" - "fmt" - "log" - "math/big" - "net" - "os" - "strings" - "time" -) - -var ( - host = flag.String("host", "", "Comma-separated hostnames and IPs to generate a certificate for") - validFrom = flag.String("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011") - validFor = flag.Duration("duration", 365*24*time.Hour, "Duration that certificate is valid for") - isCA = flag.Bool("ca", false, "whether this cert should be its own Certificate Authority") - rsaBits = flag.Int("rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set") - ecdsaCurve = flag.String("ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256 (recommended), P384, P521") -) - -func publicKey(priv interface{}) interface{} { - switch k := priv.(type) { - case *rsa.PrivateKey: - return &k.PublicKey - case *ecdsa.PrivateKey: - return &k.PublicKey - default: - return nil - } -} - -func pemBlockForKey(priv interface{}) *pem.Block { - switch k := priv.(type) { - case *rsa.PrivateKey: - return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)} - case *ecdsa.PrivateKey: - b, err := x509.MarshalECPrivateKey(k) - if err != nil { - fmt.Fprintf(os.Stderr, "Unable to marshal ECDSA private key: %v", err) - os.Exit(2) - } - return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b} - default: - return nil - } -} - -func main() { - flag.Parse() - - if len(*host) == 0 { - log.Fatalf("Missing required --host parameter") - } - - var priv interface{} - var err error - switch *ecdsaCurve { - case "": - priv, err = rsa.GenerateKey(rand.Reader, *rsaBits) - case "P224": - priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader) - case "P256": - priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - case "P384": - priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) - case "P521": - priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - default: - fmt.Fprintf(os.Stderr, "Unrecognized elliptic curve: %q", *ecdsaCurve) - os.Exit(1) - } - if err != nil { - log.Fatalf("failed to generate private key: %s", err) - } - - var notBefore time.Time - if len(*validFrom) == 0 { - notBefore = time.Now() - } else { - notBefore, err = time.Parse("Jan 2 15:04:05 2006", *validFrom) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to parse creation date: %s\n", err) - os.Exit(1) - } - } - - notAfter := notBefore.Add(*validFor) - - serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) - serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) - if err != nil { - log.Fatalf("failed to generate serial number: %s", err) - } - - template := x509.Certificate{ - SerialNumber: serialNumber, - Subject: pkix.Name{ - Organization: []string{"Acme Co"}, - }, - NotBefore: notBefore, - NotAfter: notAfter, - - KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, - BasicConstraintsValid: true, - } - - hosts := strings.Split(*host, ",") - for _, h := range hosts { - if ip := net.ParseIP(h); ip != nil { - template.IPAddresses = append(template.IPAddresses, ip) - } else { - template.DNSNames = append(template.DNSNames, h) - } - } - - if *isCA { - template.IsCA = true - template.KeyUsage |= x509.KeyUsageCertSign - } - - derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv) - if err != nil { - log.Fatalf("Failed to create certificate: %s", err) - } - - certOut, err := os.Create("cert.pem") - if err != nil { - log.Fatalf("failed to open cert.pem for writing: %s", err) - } - if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { - log.Fatalf("failed to write data to cert.pem: %s", err) - } - if err := certOut.Close(); err != nil { - log.Fatalf("error closing cert.pem: %s", err) - } - log.Print("wrote cert.pem\n") - - keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) - if err != nil { - log.Print("failed to open key.pem for writing:", err) - return - } - if err := pem.Encode(keyOut, pemBlockForKey(priv)); err != nil { - log.Fatalf("failed to write data to key.pem: %s", err) - } - if err := keyOut.Close(); err != nil { - log.Fatalf("error closing key.pem: %s", err) - } - log.Print("wrote key.pem\n") -} diff --git a/vendor/github.com/marten-seemann/qtls/go.mod b/vendor/github.com/marten-seemann/qtls/go.mod deleted file mode 100644 index 9cd2ced536..0000000000 --- a/vendor/github.com/marten-seemann/qtls/go.mod +++ /dev/null @@ -1,8 +0,0 @@ -module github.com/marten-seemann/qtls - -go 1.12 - -require ( - golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25 - golang.org/x/sys v0.0.0-20190228124157-a34e9553db1e -) diff --git a/vendor/github.com/marten-seemann/qtls/go.sum b/vendor/github.com/marten-seemann/qtls/go.sum deleted file mode 100644 index a47aabd297..0000000000 --- a/vendor/github.com/marten-seemann/qtls/go.sum +++ /dev/null @@ -1,5 +0,0 @@ -golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25 h1:jsG6UpNLt9iAsb0S2AGW28DveNzzgmbXR+ENoPjUeIU= -golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190228124157-a34e9553db1e h1:ZytStCyV048ZqDsWHiYDdoI2Vd4msMcrDECFxS+tL9c= -golang.org/x/sys v0.0.0-20190228124157-a34e9553db1e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/marten-seemann/qtls/handshake_client.go b/vendor/github.com/marten-seemann/qtls/handshake_client.go deleted file mode 100644 index 1d2903d56a..0000000000 --- a/vendor/github.com/marten-seemann/qtls/handshake_client.go +++ /dev/null @@ -1,1023 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "bytes" - "crypto" - "crypto/ecdsa" - "crypto/rsa" - "crypto/subtle" - "crypto/x509" - "errors" - "fmt" - "io" - "net" - "strconv" - "strings" - "sync/atomic" - "time" -) - -type clientHandshakeState struct { - c *Conn - serverHello *serverHelloMsg - hello *clientHelloMsg - suite *cipherSuite - finishedHash finishedHash - masterSecret []byte - session *ClientSessionState -} - -func (c *Conn) makeClientHello() (*clientHelloMsg, ecdheParameters, error) { - config := c.config - if len(config.ServerName) == 0 && !config.InsecureSkipVerify { - return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config") - } - - nextProtosLength := 0 - for _, proto := range config.NextProtos { - if l := len(proto); l == 0 || l > 255 { - return nil, nil, errors.New("tls: invalid NextProtos value") - } else { - nextProtosLength += 1 + l - } - } - if nextProtosLength > 0xffff { - return nil, nil, errors.New("tls: NextProtos values too large") - } - - supportedVersions := config.supportedVersions(true) - if len(supportedVersions) == 0 { - return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion") - } - - clientHelloVersion := supportedVersions[0] - // The version at the beginning of the ClientHello was capped at TLS 1.2 - // for compatibility reasons. The supported_versions extension is used - // to negotiate versions now. See RFC 8446, Section 4.2.1. - if clientHelloVersion > VersionTLS12 { - clientHelloVersion = VersionTLS12 - } - - hello := &clientHelloMsg{ - vers: clientHelloVersion, - compressionMethods: []uint8{compressionNone}, - random: make([]byte, 32), - sessionId: make([]byte, 32), - ocspStapling: true, - scts: true, - serverName: hostnameInSNI(config.ServerName), - supportedCurves: config.curvePreferences(), - supportedPoints: []uint8{pointFormatUncompressed}, - nextProtoNeg: len(config.NextProtos) > 0, - secureRenegotiationSupported: true, - alpnProtocols: config.NextProtos, - supportedVersions: supportedVersions, - } - - if c.handshakes > 0 { - hello.secureRenegotiation = c.clientFinished[:] - } - - possibleCipherSuites := config.cipherSuites() - hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites)) - -NextCipherSuite: - for _, suiteId := range possibleCipherSuites { - for _, suite := range cipherSuites { - if suite.id != suiteId { - continue - } - // Don't advertise TLS 1.2-only cipher suites unless - // we're attempting TLS 1.2. - if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 { - continue - } - hello.cipherSuites = append(hello.cipherSuites, suiteId) - continue NextCipherSuite - } - } - - _, err := io.ReadFull(config.rand(), hello.random) - if err != nil { - return nil, nil, errors.New("tls: short read from Rand: " + err.Error()) - } - - // A random session ID is used to detect when the server accepted a ticket - // and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as - // a compatibility measure (see RFC 8446, Section 4.1.2). - if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil { - return nil, nil, errors.New("tls: short read from Rand: " + err.Error()) - } - - if hello.vers >= VersionTLS12 { - hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms - } - - var params ecdheParameters - if hello.supportedVersions[0] == VersionTLS13 { - hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13()...) - - curveID := config.curvePreferences()[0] - if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { - return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve") - } - params, err = generateECDHEParameters(config.rand(), curveID) - if err != nil { - return nil, nil, err - } - hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}} - } - - if hello.supportedVersions[0] == VersionTLS13 && config.GetExtensions != nil { - hello.additionalExtensions = config.GetExtensions(typeClientHello) - } - - return hello, params, nil -} - -func (c *Conn) clientHandshake() (err error) { - if c.config == nil { - c.config = defaultConfig() - } - c.setAlternativeRecordLayer() - - // This may be a renegotiation handshake, in which case some fields - // need to be reset. - c.didResume = false - - hello, ecdheParams, err := c.makeClientHello() - if err != nil { - return err - } - - cacheKey, session, earlySecret, binderKey := c.loadSession(hello) - if cacheKey != "" && session != nil { - defer func() { - // If we got a handshake failure when resuming a session, throw away - // the session ticket. See RFC 5077, Section 3.2. - // - // RFC 8446 makes no mention of dropping tickets on failure, but it - // does require servers to abort on invalid binders, so we need to - // delete tickets to recover from a corrupted PSK. - if err != nil { - c.config.ClientSessionCache.Put(cacheKey, nil) - } - }() - } - - if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil { - return err - } - - msg, err := c.readHandshake() - if err != nil { - return err - } - - serverHello, ok := msg.(*serverHelloMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(serverHello, msg) - } - - if err := c.pickTLSVersion(serverHello); err != nil { - return err - } - - if c.vers == VersionTLS13 { - hs := &clientHandshakeStateTLS13{ - c: c, - serverHello: serverHello, - hello: hello, - ecdheParams: ecdheParams, - session: session, - earlySecret: earlySecret, - binderKey: binderKey, - } - - // In TLS 1.3, session tickets are delivered after the handshake. - return hs.handshake() - } - - hs := &clientHandshakeState{ - c: c, - serverHello: serverHello, - hello: hello, - session: session, - } - - if err := hs.handshake(); err != nil { - return err - } - - // If we had a successful handshake and hs.session is different from - // the one already cached - cache a new one. - if cacheKey != "" && hs.session != nil && session != hs.session { - c.config.ClientSessionCache.Put(cacheKey, hs.session) - } - - return nil -} - -func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string, - session *ClientSessionState, earlySecret, binderKey []byte) { - if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { - return "", nil, nil, nil - } - - hello.ticketSupported = true - - if hello.supportedVersions[0] == VersionTLS13 { - // Require DHE on resumption as it guarantees forward secrecy against - // compromise of the session ticket key. See RFC 8446, Section 4.2.9. - hello.pskModes = []uint8{pskModeDHE} - } - - // Session resumption is not allowed if renegotiating because - // renegotiation is primarily used to allow a client to send a client - // certificate, which would be skipped if session resumption occurred. - if c.handshakes != 0 { - return "", nil, nil, nil - } - - // Try to resume a previously negotiated TLS session, if available. - cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config) - session, ok := c.config.ClientSessionCache.Get(cacheKey) - if !ok || session == nil { - return cacheKey, nil, nil, nil - } - - // Check that version used for the previous session is still valid. - versOk := false - for _, v := range hello.supportedVersions { - if v == session.vers { - versOk = true - break - } - } - if !versOk { - return cacheKey, nil, nil, nil - } - - // Check that the cached server certificate is not expired, and that it's - // valid for the ServerName. This should be ensured by the cache key, but - // protect the application from a faulty ClientSessionCache implementation. - if !c.config.InsecureSkipVerify { - if len(session.verifiedChains) == 0 { - // The original connection had InsecureSkipVerify, while this doesn't. - return cacheKey, nil, nil, nil - } - serverCert := session.serverCertificates[0] - if c.config.time().After(serverCert.NotAfter) { - // Expired certificate, delete the entry. - c.config.ClientSessionCache.Put(cacheKey, nil) - return cacheKey, nil, nil, nil - } - if err := serverCert.VerifyHostname(c.config.ServerName); err != nil { - return cacheKey, nil, nil, nil - } - } - - if session.vers != VersionTLS13 { - // In TLS 1.2 the cipher suite must match the resumed session. Ensure we - // are still offering it. - if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil { - return cacheKey, nil, nil, nil - } - - hello.sessionTicket = session.sessionTicket - return - } - - // Check that the session ticket is not expired. - if c.config.time().After(session.useBy) { - c.config.ClientSessionCache.Put(cacheKey, nil) - return cacheKey, nil, nil, nil - } - - // In TLS 1.3 the KDF hash must match the resumed session. Ensure we - // offer at least one cipher suite with that hash. - cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite) - if cipherSuite == nil { - return cacheKey, nil, nil, nil - } - cipherSuiteOk := false - for _, offeredID := range hello.cipherSuites { - offeredSuite := cipherSuiteTLS13ByID(offeredID) - if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash { - cipherSuiteOk = true - break - } - } - if !cipherSuiteOk { - return cacheKey, nil, nil, nil - } - - // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1. - ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond) - identity := pskIdentity{ - label: session.sessionTicket, - obfuscatedTicketAge: ticketAge + session.ageAdd, - } - hello.pskIdentities = []pskIdentity{identity} - hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())} - - // Compute the PSK binders. See RFC 8446, Section 4.2.11.2. - psk := cipherSuite.expandLabel(session.masterSecret, "resumption", - session.nonce, cipherSuite.hash.Size()) - earlySecret = cipherSuite.extract(psk, nil) - binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil) - transcript := cipherSuite.hash.New() - transcript.Write(hello.marshalWithoutBinders()) - pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)} - hello.updateBinders(pskBinders) - - return -} - -func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error { - peerVersion := serverHello.vers - if serverHello.supportedVersion != 0 { - peerVersion = serverHello.supportedVersion - } - - vers, ok := c.config.mutualVersion(true, []uint16{peerVersion}) - if !ok { - c.sendAlert(alertProtocolVersion) - return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion) - } - - c.vers = vers - c.haveVers = true - c.in.version = vers - c.out.version = vers - - return nil -} - -// Does the handshake, either a full one or resumes old session. Requires hs.c, -// hs.hello, hs.serverHello, and, optionally, hs.session to be set. -func (hs *clientHandshakeState) handshake() error { - c := hs.c - - isResume, err := hs.processServerHello() - if err != nil { - return err - } - - hs.finishedHash = newFinishedHash(c.vers, hs.suite) - - // No signatures of the handshake are needed in a resumption. - // Otherwise, in a full handshake, if we don't have any certificates - // configured then we will never send a CertificateVerify message and - // thus no signatures are needed in that case either. - if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) { - hs.finishedHash.discardHandshakeBuffer() - } - - hs.finishedHash.Write(hs.hello.marshal()) - hs.finishedHash.Write(hs.serverHello.marshal()) - - c.buffering = true - if isResume { - if err := hs.establishKeys(); err != nil { - return err - } - if err := hs.readSessionTicket(); err != nil { - return err - } - if err := hs.readFinished(c.serverFinished[:]); err != nil { - return err - } - c.clientFinishedIsFirst = false - if err := hs.sendFinished(c.clientFinished[:]); err != nil { - return err - } - if _, err := c.flush(); err != nil { - return err - } - } else { - if err := hs.doFullHandshake(); err != nil { - return err - } - if err := hs.establishKeys(); err != nil { - return err - } - if err := hs.sendFinished(c.clientFinished[:]); err != nil { - return err - } - if _, err := c.flush(); err != nil { - return err - } - c.clientFinishedIsFirst = true - if err := hs.readSessionTicket(); err != nil { - return err - } - if err := hs.readFinished(c.serverFinished[:]); err != nil { - return err - } - } - - c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random) - c.didResume = isResume - atomic.StoreUint32(&c.handshakeStatus, 1) - - return nil -} - -func (hs *clientHandshakeState) pickCipherSuite() error { - if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil { - hs.c.sendAlert(alertHandshakeFailure) - return errors.New("tls: server chose an unconfigured cipher suite") - } - - hs.c.cipherSuite = hs.suite.id - return nil -} - -func (hs *clientHandshakeState) doFullHandshake() error { - c := hs.c - - msg, err := c.readHandshake() - if err != nil { - return err - } - certMsg, ok := msg.(*certificateMsg) - if !ok || len(certMsg.certificates) == 0 { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(certMsg, msg) - } - hs.finishedHash.Write(certMsg.marshal()) - - if c.handshakes == 0 { - // If this is the first handshake on a connection, process and - // (optionally) verify the server's certificates. - if err := c.verifyServerCertificate(certMsg.certificates); err != nil { - return err - } - } else { - // This is a renegotiation handshake. We require that the - // server's identity (i.e. leaf certificate) is unchanged and - // thus any previous trust decision is still valid. - // - // See https://mitls.org/pages/attacks/3SHAKE for the - // motivation behind this requirement. - if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) { - c.sendAlert(alertBadCertificate) - return errors.New("tls: server's identity changed during renegotiation") - } - } - - msg, err = c.readHandshake() - if err != nil { - return err - } - - cs, ok := msg.(*certificateStatusMsg) - if ok { - // RFC4366 on Certificate Status Request: - // The server MAY return a "certificate_status" message. - - if !hs.serverHello.ocspStapling { - // If a server returns a "CertificateStatus" message, then the - // server MUST have included an extension of type "status_request" - // with empty "extension_data" in the extended server hello. - - c.sendAlert(alertUnexpectedMessage) - return errors.New("tls: received unexpected CertificateStatus message") - } - hs.finishedHash.Write(cs.marshal()) - - c.ocspResponse = cs.response - - msg, err = c.readHandshake() - if err != nil { - return err - } - } - - keyAgreement := hs.suite.ka(c.vers) - - skx, ok := msg.(*serverKeyExchangeMsg) - if ok { - hs.finishedHash.Write(skx.marshal()) - err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx) - if err != nil { - c.sendAlert(alertUnexpectedMessage) - return err - } - - msg, err = c.readHandshake() - if err != nil { - return err - } - } - - var chainToSend *Certificate - var certRequested bool - certReq, ok := msg.(*certificateRequestMsg) - if ok { - certRequested = true - hs.finishedHash.Write(certReq.marshal()) - - cri := certificateRequestInfoFromMsg(certReq) - if chainToSend, err = c.getClientCertificate(cri); err != nil { - c.sendAlert(alertInternalError) - return err - } - - msg, err = c.readHandshake() - if err != nil { - return err - } - } - - shd, ok := msg.(*serverHelloDoneMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(shd, msg) - } - hs.finishedHash.Write(shd.marshal()) - - // If the server requested a certificate then we have to send a - // Certificate message, even if it's empty because we don't have a - // certificate to send. - if certRequested { - certMsg = new(certificateMsg) - certMsg.certificates = chainToSend.Certificate - hs.finishedHash.Write(certMsg.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { - return err - } - } - - preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0]) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - if ckx != nil { - hs.finishedHash.Write(ckx.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil { - return err - } - } - - if chainToSend != nil && len(chainToSend.Certificate) > 0 { - certVerify := &certificateVerifyMsg{ - hasSignatureAlgorithm: c.vers >= VersionTLS12, - } - - key, ok := chainToSend.PrivateKey.(crypto.Signer) - if !ok { - c.sendAlert(alertInternalError) - return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey) - } - - signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - // SignatureAndHashAlgorithm was introduced in TLS 1.2. - if certVerify.hasSignatureAlgorithm { - certVerify.signatureAlgorithm = signatureAlgorithm - } - digest, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - signOpts := crypto.SignerOpts(hashFunc) - if sigType == signatureRSAPSS { - signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc} - } - certVerify.signature, err = key.Sign(c.config.rand(), digest, signOpts) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - - hs.finishedHash.Write(certVerify.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil { - return err - } - } - - hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random) - if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil { - c.sendAlert(alertInternalError) - return errors.New("tls: failed to write to key log: " + err.Error()) - } - - hs.finishedHash.discardHandshakeBuffer() - - return nil -} - -func (hs *clientHandshakeState) establishKeys() error { - c := hs.c - - clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := - keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) - var clientCipher, serverCipher interface{} - var clientHash, serverHash macFunction - if hs.suite.cipher != nil { - clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) - clientHash = hs.suite.mac(c.vers, clientMAC) - serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */) - serverHash = hs.suite.mac(c.vers, serverMAC) - } else { - clientCipher = hs.suite.aead(clientKey, clientIV) - serverCipher = hs.suite.aead(serverKey, serverIV) - } - - c.in.prepareCipherSpec(c.vers, serverCipher, serverHash) - c.out.prepareCipherSpec(c.vers, clientCipher, clientHash) - return nil -} - -func (hs *clientHandshakeState) serverResumedSession() bool { - // If the server responded with the same sessionId then it means the - // sessionTicket is being used to resume a TLS session. - return hs.session != nil && hs.hello.sessionId != nil && - bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId) -} - -func (hs *clientHandshakeState) processServerHello() (bool, error) { - c := hs.c - - if err := hs.pickCipherSuite(); err != nil { - return false, err - } - - if hs.serverHello.compressionMethod != compressionNone { - c.sendAlert(alertUnexpectedMessage) - return false, errors.New("tls: server selected unsupported compression format") - } - - if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported { - c.secureRenegotiation = true - if len(hs.serverHello.secureRenegotiation) != 0 { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("tls: initial handshake had non-empty renegotiation extension") - } - } - - if c.handshakes > 0 && c.secureRenegotiation { - var expectedSecureRenegotiation [24]byte - copy(expectedSecureRenegotiation[:], c.clientFinished[:]) - copy(expectedSecureRenegotiation[12:], c.serverFinished[:]) - if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("tls: incorrect renegotiation extension contents") - } - } - - clientDidNPN := hs.hello.nextProtoNeg - clientDidALPN := len(hs.hello.alpnProtocols) > 0 - serverHasNPN := hs.serverHello.nextProtoNeg - serverHasALPN := len(hs.serverHello.alpnProtocol) > 0 - - if !clientDidNPN && serverHasNPN { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("tls: server advertised unrequested NPN extension") - } - - if !clientDidALPN && serverHasALPN { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("tls: server advertised unrequested ALPN extension") - } - - if serverHasNPN && serverHasALPN { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("tls: server advertised both NPN and ALPN extensions") - } - - if serverHasALPN { - c.clientProtocol = hs.serverHello.alpnProtocol - c.clientProtocolFallback = false - } - c.scts = hs.serverHello.scts - - if !hs.serverResumedSession() { - return false, nil - } - - if hs.session.vers != c.vers { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("tls: server resumed a session with a different version") - } - - if hs.session.cipherSuite != hs.suite.id { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("tls: server resumed a session with a different cipher suite") - } - - // Restore masterSecret and peerCerts from previous state - hs.masterSecret = hs.session.masterSecret - c.peerCertificates = hs.session.serverCertificates - c.verifiedChains = hs.session.verifiedChains - return true, nil -} - -func (hs *clientHandshakeState) readFinished(out []byte) error { - c := hs.c - - if err := c.readChangeCipherSpec(); err != nil { - return err - } - - msg, err := c.readHandshake() - if err != nil { - return err - } - serverFinished, ok := msg.(*finishedMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(serverFinished, msg) - } - - verify := hs.finishedHash.serverSum(hs.masterSecret) - if len(verify) != len(serverFinished.verifyData) || - subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: server's Finished message was incorrect") - } - hs.finishedHash.Write(serverFinished.marshal()) - copy(out, verify) - return nil -} - -func (hs *clientHandshakeState) readSessionTicket() error { - if !hs.serverHello.ticketSupported { - return nil - } - - c := hs.c - msg, err := c.readHandshake() - if err != nil { - return err - } - sessionTicketMsg, ok := msg.(*newSessionTicketMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(sessionTicketMsg, msg) - } - hs.finishedHash.Write(sessionTicketMsg.marshal()) - - hs.session = &ClientSessionState{ - sessionTicket: sessionTicketMsg.ticket, - vers: c.vers, - cipherSuite: hs.suite.id, - masterSecret: hs.masterSecret, - serverCertificates: c.peerCertificates, - verifiedChains: c.verifiedChains, - receivedAt: c.config.time(), - } - - return nil -} - -func (hs *clientHandshakeState) sendFinished(out []byte) error { - c := hs.c - - if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil { - return err - } - if hs.serverHello.nextProtoNeg { - nextProto := new(nextProtoMsg) - proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos) - nextProto.proto = proto - c.clientProtocol = proto - c.clientProtocolFallback = fallback - - hs.finishedHash.Write(nextProto.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil { - return err - } - } - - finished := new(finishedMsg) - finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret) - hs.finishedHash.Write(finished.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { - return err - } - copy(out, finished.verifyData) - return nil -} - -// verifyServerCertificate parses and verifies the provided chain, setting -// c.verifiedChains and c.peerCertificates or sending the appropriate alert. -func (c *Conn) verifyServerCertificate(certificates [][]byte) error { - certs := make([]*x509.Certificate, len(certificates)) - for i, asn1Data := range certificates { - cert, err := x509.ParseCertificate(asn1Data) - if err != nil { - c.sendAlert(alertBadCertificate) - return errors.New("tls: failed to parse certificate from server: " + err.Error()) - } - certs[i] = cert - } - - if !c.config.InsecureSkipVerify { - opts := x509.VerifyOptions{ - Roots: c.config.RootCAs, - CurrentTime: c.config.time(), - DNSName: c.config.ServerName, - Intermediates: x509.NewCertPool(), - } - - for i, cert := range certs { - if i == 0 { - continue - } - opts.Intermediates.AddCert(cert) - } - var err error - c.verifiedChains, err = certs[0].Verify(opts) - if err != nil { - c.sendAlert(alertBadCertificate) - return err - } - } - - if c.config.VerifyPeerCertificate != nil { - if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil { - c.sendAlert(alertBadCertificate) - return err - } - } - - switch certs[0].PublicKey.(type) { - case *rsa.PublicKey, *ecdsa.PublicKey: - break - default: - c.sendAlert(alertUnsupportedCertificate) - return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey) - } - - c.peerCertificates = certs - - return nil -} - -// tls11SignatureSchemes contains the signature schemes that we synthesise for -// a TLS <= 1.1 connection, based on the supported certificate types. -var ( - tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1} - tls11SignatureSchemesECDSA = tls11SignatureSchemes[:3] - tls11SignatureSchemesRSA = tls11SignatureSchemes[3:] -) - -// certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS -// <= 1.2 CertificateRequest, making an effort to fill in missing information. -func certificateRequestInfoFromMsg(certReq *certificateRequestMsg) *CertificateRequestInfo { - var rsaAvail, ecdsaAvail bool - for _, certType := range certReq.certificateTypes { - switch certType { - case certTypeRSASign: - rsaAvail = true - case certTypeECDSASign: - ecdsaAvail = true - } - } - - cri := &CertificateRequestInfo{ - AcceptableCAs: certReq.certificateAuthorities, - } - - if !certReq.hasSignatureAlgorithm { - // Prior to TLS 1.2, the signature schemes were not - // included in the certificate request message. In this - // case we use a plausible list based on the acceptable - // certificate types. - switch { - case rsaAvail && ecdsaAvail: - cri.SignatureSchemes = tls11SignatureSchemes - case rsaAvail: - cri.SignatureSchemes = tls11SignatureSchemesRSA - case ecdsaAvail: - cri.SignatureSchemes = tls11SignatureSchemesECDSA - } - return cri - } - - // In TLS 1.2, the signature schemes apply to both the certificate chain and - // the leaf key, while the certificate types only apply to the leaf key. - // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated"). - // Filter the signature schemes based on the certificate type. - cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms)) - for _, sigScheme := range certReq.supportedSignatureAlgorithms { - switch signatureFromSignatureScheme(sigScheme) { - case signatureECDSA: - if ecdsaAvail { - cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme) - } - case signatureRSAPSS, signaturePKCS1v15: - if rsaAvail { - cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme) - } - } - } - - return cri -} - -func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) { - if c.config.GetClientCertificate != nil { - return c.config.GetClientCertificate(cri) - } - - // We need to search our list of client certs for one - // where SignatureAlgorithm is acceptable to the server and the - // Issuer is in AcceptableCAs. - for i, chain := range c.config.Certificates { - sigOK := false - for _, alg := range signatureSchemesForCertificate(c.vers, &chain) { - if isSupportedSignatureAlgorithm(alg, cri.SignatureSchemes) { - sigOK = true - break - } - } - if !sigOK { - continue - } - - if len(cri.AcceptableCAs) == 0 { - return &chain, nil - } - - for j, cert := range chain.Certificate { - x509Cert := chain.Leaf - // Parse the certificate if this isn't the leaf node, or if - // chain.Leaf was nil. - if j != 0 || x509Cert == nil { - var err error - if x509Cert, err = x509.ParseCertificate(cert); err != nil { - c.sendAlert(alertInternalError) - return nil, errors.New("tls: failed to parse configured certificate chain #" + strconv.Itoa(i) + ": " + err.Error()) - } - } - - for _, ca := range cri.AcceptableCAs { - if bytes.Equal(x509Cert.RawIssuer, ca) { - return &chain, nil - } - } - } - } - - // No acceptable certificate found. Don't send a certificate. - return new(Certificate), nil -} - -// clientSessionCacheKey returns a key used to cache sessionTickets that could -// be used to resume previously negotiated TLS sessions with a server. -func clientSessionCacheKey(serverAddr net.Addr, config *Config) string { - if len(config.ServerName) > 0 { - return config.ServerName - } - return serverAddr.String() -} - -// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol -// given list of possible protocols and a list of the preference order. The -// first list must not be empty. It returns the resulting protocol and flag -// indicating if the fallback case was reached. -func mutualProtocol(protos, preferenceProtos []string) (string, bool) { - for _, s := range preferenceProtos { - for _, c := range protos { - if s == c { - return s, false - } - } - } - - return protos[0], true -} - -// hostnameInSNI converts name into an approriate hostname for SNI. -// Literal IP addresses and absolute FQDNs are not permitted as SNI values. -// See RFC 6066, Section 3. -func hostnameInSNI(name string) string { - host := name - if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' { - host = host[1 : len(host)-1] - } - if i := strings.LastIndex(host, "%"); i > 0 { - host = host[:i] - } - if net.ParseIP(host) != nil { - return "" - } - for len(name) > 0 && name[len(name)-1] == '.' { - name = name[:len(name)-1] - } - return name -} diff --git a/vendor/github.com/marten-seemann/qtls/handshake_client_tls13.go b/vendor/github.com/marten-seemann/qtls/handshake_client_tls13.go deleted file mode 100644 index 9d8e0f7bef..0000000000 --- a/vendor/github.com/marten-seemann/qtls/handshake_client_tls13.go +++ /dev/null @@ -1,680 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "bytes" - "crypto" - "crypto/hmac" - "crypto/rsa" - "errors" - "hash" - "sync/atomic" - "time" -) - -type clientHandshakeStateTLS13 struct { - c *Conn - serverHello *serverHelloMsg - hello *clientHelloMsg - ecdheParams ecdheParameters - - session *ClientSessionState - earlySecret []byte - binderKey []byte - - certReq *certificateRequestMsgTLS13 - usingPSK bool - sentDummyCCS bool - suite *cipherSuiteTLS13 - transcript hash.Hash - masterSecret []byte - trafficSecret []byte // client_application_traffic_secret_0 -} - -// handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and, -// optionally, hs.session, hs.earlySecret and hs.binderKey to be set. -func (hs *clientHandshakeStateTLS13) handshake() error { - c := hs.c - - // The server must not select TLS 1.3 in a renegotiation. See RFC 8446, - // sections 4.1.2 and 4.1.3. - if c.handshakes > 0 { - c.sendAlert(alertProtocolVersion) - return errors.New("tls: server selected TLS 1.3 in a renegotiation") - } - - // Consistency check on the presence of a keyShare and its parameters. - if hs.ecdheParams == nil || len(hs.hello.keyShares) != 1 { - return c.sendAlert(alertInternalError) - } - - if err := hs.checkServerHelloOrHRR(); err != nil { - return err - } - - hs.transcript = hs.suite.hash.New() - hs.transcript.Write(hs.hello.marshal()) - - if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { - if err := hs.sendDummyChangeCipherSpec(); err != nil { - return err - } - if err := hs.processHelloRetryRequest(); err != nil { - return err - } - } - - hs.transcript.Write(hs.serverHello.marshal()) - - c.buffering = true - if err := hs.processServerHello(); err != nil { - return err - } - if err := hs.sendDummyChangeCipherSpec(); err != nil { - return err - } - if err := hs.establishHandshakeKeys(); err != nil { - return err - } - if err := hs.readServerParameters(); err != nil { - return err - } - if err := hs.readServerCertificate(); err != nil { - return err - } - if err := hs.readServerFinished(); err != nil { - return err - } - if err := hs.sendClientCertificate(); err != nil { - return err - } - if err := hs.sendClientFinished(); err != nil { - return err - } - if _, err := c.flush(); err != nil { - return err - } - - atomic.StoreUint32(&c.handshakeStatus, 1) - - return nil -} - -// checkServerHelloOrHRR does validity checks that apply to both ServerHello and -// HelloRetryRequest messages. It sets hs.suite. -func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error { - c := hs.c - - if hs.serverHello.supportedVersion == 0 { - c.sendAlert(alertMissingExtension) - return errors.New("tls: server selected TLS 1.3 using the legacy version field") - } - - if hs.serverHello.supportedVersion != VersionTLS13 { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server selected an invalid version after a HelloRetryRequest") - } - - if hs.serverHello.vers != VersionTLS12 { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server sent an incorrect legacy version") - } - - if hs.serverHello.nextProtoNeg || - len(hs.serverHello.nextProtos) != 0 || - hs.serverHello.ocspStapling || - hs.serverHello.ticketSupported || - hs.serverHello.secureRenegotiationSupported || - len(hs.serverHello.secureRenegotiation) != 0 || - len(hs.serverHello.alpnProtocol) != 0 || - len(hs.serverHello.scts) != 0 { - c.sendAlert(alertUnsupportedExtension) - return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3") - } - - if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server did not echo the legacy session ID") - } - - if hs.serverHello.compressionMethod != compressionNone { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server selected unsupported compression format") - } - - selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite) - if hs.suite != nil && selectedSuite != hs.suite { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server changed cipher suite after a HelloRetryRequest") - } - if selectedSuite == nil { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server chose an unconfigured cipher suite") - } - hs.suite = selectedSuite - c.cipherSuite = hs.suite.id - - return nil -} - -// sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility -// with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. -func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error { - if hs.sentDummyCCS { - return nil - } - hs.sentDummyCCS = true - - _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) - return err -} - -// processHelloRetryRequest handles the HRR in hs.serverHello, modifies and -// resends hs.hello, and reads the new ServerHello into hs.serverHello. -func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { - c := hs.c - - // The first ClientHello gets double-hashed into the transcript upon a - // HelloRetryRequest. See RFC 8446, Section 4.4.1. - chHash := hs.transcript.Sum(nil) - hs.transcript.Reset() - hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) - hs.transcript.Write(chHash) - hs.transcript.Write(hs.serverHello.marshal()) - - if hs.serverHello.serverShare.group != 0 { - c.sendAlert(alertDecodeError) - return errors.New("tls: received malformed key_share extension") - } - - curveID := hs.serverHello.selectedGroup - if curveID == 0 { - c.sendAlert(alertMissingExtension) - return errors.New("tls: received HelloRetryRequest without selected group") - } - curveOK := false - for _, id := range hs.hello.supportedCurves { - if id == curveID { - curveOK = true - break - } - } - if !curveOK { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server selected unsupported group") - } - if hs.ecdheParams.CurveID() == curveID { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server sent an unnecessary HelloRetryRequest message") - } - if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { - c.sendAlert(alertInternalError) - return errors.New("tls: CurvePreferences includes unsupported curve") - } - params, err := generateECDHEParameters(c.config.rand(), curveID) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - hs.ecdheParams = params - hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}} - - hs.hello.cookie = hs.serverHello.cookie - - hs.hello.raw = nil - if len(hs.hello.pskIdentities) > 0 { - pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) - if pskSuite == nil { - return c.sendAlert(alertInternalError) - } - if pskSuite.hash == hs.suite.hash { - // Update binders and obfuscated_ticket_age. - ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond) - hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd - - transcript := hs.suite.hash.New() - transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) - transcript.Write(chHash) - transcript.Write(hs.serverHello.marshal()) - transcript.Write(hs.hello.marshalWithoutBinders()) - pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)} - hs.hello.updateBinders(pskBinders) - } else { - // Server selected a cipher suite incompatible with the PSK. - hs.hello.pskIdentities = nil - hs.hello.pskBinders = nil - } - } - - hs.transcript.Write(hs.hello.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { - return err - } - - msg, err := c.readHandshake() - if err != nil { - return err - } - - serverHello, ok := msg.(*serverHelloMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(serverHello, msg) - } - hs.serverHello = serverHello - - if err := hs.checkServerHelloOrHRR(); err != nil { - return err - } - - return nil -} - -func (hs *clientHandshakeStateTLS13) processServerHello() error { - c := hs.c - - if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { - c.sendAlert(alertUnexpectedMessage) - return errors.New("tls: server sent two HelloRetryRequest messages") - } - - if len(hs.serverHello.cookie) != 0 { - c.sendAlert(alertUnsupportedExtension) - return errors.New("tls: server sent a cookie in a normal ServerHello") - } - - if hs.serverHello.selectedGroup != 0 { - c.sendAlert(alertDecodeError) - return errors.New("tls: malformed key_share extension") - } - - if hs.serverHello.serverShare.group == 0 { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server did not send a key share") - } - if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server selected unsupported group") - } - - if !hs.serverHello.selectedIdentityPresent { - return nil - } - - if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server selected an invalid PSK") - } - - if len(hs.hello.pskIdentities) != 1 || hs.session == nil { - return c.sendAlert(alertInternalError) - } - pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) - if pskSuite == nil { - return c.sendAlert(alertInternalError) - } - if pskSuite.hash != hs.suite.hash { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: server selected an invalid PSK and cipher suite pair") - } - - hs.usingPSK = true - c.didResume = true - c.peerCertificates = hs.session.serverCertificates - c.verifiedChains = hs.session.verifiedChains - return nil -} - -func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error { - c := hs.c - - sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data) - if sharedKey == nil { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: invalid server key share") - } - - earlySecret := hs.earlySecret - if !hs.usingPSK { - earlySecret = hs.suite.extract(nil, nil) - } - handshakeSecret := hs.suite.extract(sharedKey, - hs.suite.deriveSecret(earlySecret, "derived", nil)) - - clientSecret := hs.suite.deriveSecret(handshakeSecret, - clientHandshakeTrafficLabel, hs.transcript) - c.out.exportKey(hs.suite, clientSecret) - c.out.setTrafficSecret(hs.suite, clientSecret) - serverSecret := hs.suite.deriveSecret(handshakeSecret, - serverHandshakeTrafficLabel, hs.transcript) - c.in.exportKey(hs.suite, serverSecret) - c.in.setTrafficSecret(hs.suite, serverSecret) - - err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - - hs.masterSecret = hs.suite.extract(nil, - hs.suite.deriveSecret(handshakeSecret, "derived", nil)) - - return nil -} - -func (hs *clientHandshakeStateTLS13) readServerParameters() error { - c := hs.c - - msg, err := c.readHandshake() - if err != nil { - return err - } - - encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(encryptedExtensions, msg) - } - if hs.c.config.ReceivedExtensions != nil { - hs.c.config.ReceivedExtensions(typeEncryptedExtensions, encryptedExtensions.additionalExtensions) - } - hs.transcript.Write(encryptedExtensions.marshal()) - - if len(encryptedExtensions.alpnProtocol) != 0 && len(hs.hello.alpnProtocols) == 0 { - c.sendAlert(alertUnsupportedExtension) - return errors.New("tls: server advertised unrequested ALPN extension") - } - c.clientProtocol = encryptedExtensions.alpnProtocol - - return nil -} - -func (hs *clientHandshakeStateTLS13) readServerCertificate() error { - c := hs.c - - // Either a PSK or a certificate is always used, but not both. - // See RFC 8446, Section 4.1.1. - if hs.usingPSK { - return nil - } - - msg, err := c.readHandshake() - if err != nil { - return err - } - - certReq, ok := msg.(*certificateRequestMsgTLS13) - if ok { - hs.transcript.Write(certReq.marshal()) - - hs.certReq = certReq - - msg, err = c.readHandshake() - if err != nil { - return err - } - } - - certMsg, ok := msg.(*certificateMsgTLS13) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(certMsg, msg) - } - if len(certMsg.certificate.Certificate) == 0 { - c.sendAlert(alertDecodeError) - return errors.New("tls: received empty certificates message") - } - hs.transcript.Write(certMsg.marshal()) - - c.scts = certMsg.certificate.SignedCertificateTimestamps - c.ocspResponse = certMsg.certificate.OCSPStaple - - if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil { - return err - } - - msg, err = c.readHandshake() - if err != nil { - return err - } - - certVerify, ok := msg.(*certificateVerifyMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(certVerify, msg) - } - - // See RFC 8446, Section 4.4.3. - if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: invalid certificate signature algorithm") - } - sigType := signatureFromSignatureScheme(certVerify.signatureAlgorithm) - sigHash, err := hashFromSignatureScheme(certVerify.signatureAlgorithm) - if sigType == 0 || err != nil { - c.sendAlert(alertInternalError) - return err - } - if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: invalid certificate signature algorithm") - } - h := sigHash.New() - writeSignedMessage(h, serverSignatureContext, hs.transcript) - if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, - sigHash, h.Sum(nil), certVerify.signature); err != nil { - c.sendAlert(alertDecryptError) - return errors.New("tls: invalid certificate signature") - } - - hs.transcript.Write(certVerify.marshal()) - - return nil -} - -func (hs *clientHandshakeStateTLS13) readServerFinished() error { - c := hs.c - - msg, err := c.readHandshake() - if err != nil { - return err - } - - finished, ok := msg.(*finishedMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(finished, msg) - } - - expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) - if !hmac.Equal(expectedMAC, finished.verifyData) { - c.sendAlert(alertDecryptError) - return errors.New("tls: invalid server finished hash") - } - - hs.transcript.Write(finished.marshal()) - - // Derive secrets that take context through the server Finished. - - hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, - clientApplicationTrafficLabel, hs.transcript) - serverSecret := hs.suite.deriveSecret(hs.masterSecret, - serverApplicationTrafficLabel, hs.transcript) - c.in.exportKey(hs.suite, serverSecret) - c.in.setTrafficSecret(hs.suite, serverSecret) - - err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - - c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) - - return nil -} - -func (hs *clientHandshakeStateTLS13) sendClientCertificate() error { - c := hs.c - - if hs.certReq == nil { - return nil - } - - cert, err := c.getClientCertificate(&CertificateRequestInfo{ - AcceptableCAs: hs.certReq.certificateAuthorities, - SignatureSchemes: hs.certReq.supportedSignatureAlgorithms, - }) - if err != nil { - return err - } - - certMsg := new(certificateMsgTLS13) - - certMsg.certificate = *cert - certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0 - certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0 - - hs.transcript.Write(certMsg.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { - return err - } - - // If we sent an empty certificate message, skip the CertificateVerify. - if len(cert.Certificate) == 0 { - return nil - } - - certVerifyMsg := new(certificateVerifyMsg) - certVerifyMsg.hasSignatureAlgorithm = true - - supportedAlgs := signatureSchemesForCertificate(c.vers, cert) - if supportedAlgs == nil { - c.sendAlert(alertInternalError) - return unsupportedCertificateError(cert) - } - // Pick signature scheme in server preference order, as the client - // preference order is not configurable. - for _, preferredAlg := range hs.certReq.supportedSignatureAlgorithms { - if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) { - certVerifyMsg.signatureAlgorithm = preferredAlg - break - } - } - if certVerifyMsg.signatureAlgorithm == 0 { - // getClientCertificate returned a certificate incompatible with the - // CertificateRequestInfo supported signature algorithms. - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: server doesn't support selected certificate") - } - - sigType := signatureFromSignatureScheme(certVerifyMsg.signatureAlgorithm) - sigHash, err := hashFromSignatureScheme(certVerifyMsg.signatureAlgorithm) - if sigType == 0 || err != nil { - return c.sendAlert(alertInternalError) - } - h := sigHash.New() - writeSignedMessage(h, clientSignatureContext, hs.transcript) - - signOpts := crypto.SignerOpts(sigHash) - if sigType == signatureRSAPSS { - signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} - } - sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), h.Sum(nil), signOpts) - if err != nil { - c.sendAlert(alertInternalError) - return errors.New("tls: failed to sign handshake: " + err.Error()) - } - certVerifyMsg.signature = sig - - hs.transcript.Write(certVerifyMsg.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil { - return err - } - - return nil -} - -func (hs *clientHandshakeStateTLS13) sendClientFinished() error { - c := hs.c - - finished := &finishedMsg{ - verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), - } - - hs.transcript.Write(finished.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { - return err - } - - c.out.exportKey(hs.suite, hs.trafficSecret) - c.out.setTrafficSecret(hs.suite, hs.trafficSecret) - - if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil { - c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, - resumptionLabel, hs.transcript) - } - - return nil -} - -func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error { - if !c.isClient { - c.sendAlert(alertUnexpectedMessage) - return errors.New("tls: received new session ticket from a client") - } - - if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { - return nil - } - - // See RFC 8446, Section 4.6.1. - if msg.lifetime == 0 { - return nil - } - lifetime := time.Duration(msg.lifetime) * time.Second - if lifetime > maxSessionTicketLifetime { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: received a session ticket with invalid lifetime") - } - - cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) - if cipherSuite == nil || c.resumptionSecret == nil { - return c.sendAlert(alertInternalError) - } - - // Save the resumption_master_secret and nonce instead of deriving the PSK - // to do the least amount of work on NewSessionTicket messages before we - // know if the ticket will be used. Forward secrecy of resumed connections - // is guaranteed by the requirement for pskModeDHE. - session := &ClientSessionState{ - sessionTicket: msg.label, - vers: c.vers, - cipherSuite: c.cipherSuite, - masterSecret: c.resumptionSecret, - serverCertificates: c.peerCertificates, - verifiedChains: c.verifiedChains, - receivedAt: c.config.time(), - nonce: msg.nonce, - useBy: c.config.time().Add(lifetime), - ageAdd: msg.ageAdd, - } - - cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config) - c.config.ClientSessionCache.Put(cacheKey, session) - - return nil -} diff --git a/vendor/github.com/marten-seemann/qtls/handshake_messages.go b/vendor/github.com/marten-seemann/qtls/handshake_messages.go deleted file mode 100644 index 9c2ffa1d88..0000000000 --- a/vendor/github.com/marten-seemann/qtls/handshake_messages.go +++ /dev/null @@ -1,1900 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "fmt" - "strings" - - "golang.org/x/crypto/cryptobyte" -) - -// The marshalingFunction type is an adapter to allow the use of ordinary -// functions as cryptobyte.MarshalingValue. -type marshalingFunction func(b *cryptobyte.Builder) error - -func (f marshalingFunction) Marshal(b *cryptobyte.Builder) error { - return f(b) -} - -// addBytesWithLength appends a sequence of bytes to the cryptobyte.Builder. If -// the length of the sequence is not the value specified, it produces an error. -func addBytesWithLength(b *cryptobyte.Builder, v []byte, n int) { - b.AddValue(marshalingFunction(func(b *cryptobyte.Builder) error { - if len(v) != n { - return fmt.Errorf("invalid value length: expected %d, got %d", n, len(v)) - } - b.AddBytes(v) - return nil - })) -} - -// addUint64 appends a big-endian, 64-bit value to the cryptobyte.Builder. -func addUint64(b *cryptobyte.Builder, v uint64) { - b.AddUint32(uint32(v >> 32)) - b.AddUint32(uint32(v)) -} - -// readUint64 decodes a big-endian, 64-bit value into out and advances over it. -// It reports whether the read was successful. -func readUint64(s *cryptobyte.String, out *uint64) bool { - var hi, lo uint32 - if !s.ReadUint32(&hi) || !s.ReadUint32(&lo) { - return false - } - *out = uint64(hi)<<32 | uint64(lo) - return true -} - -// readUint8LengthPrefixed acts like s.ReadUint8LengthPrefixed, but targets a -// []byte instead of a cryptobyte.String. -func readUint8LengthPrefixed(s *cryptobyte.String, out *[]byte) bool { - return s.ReadUint8LengthPrefixed((*cryptobyte.String)(out)) -} - -// readUint16LengthPrefixed acts like s.ReadUint16LengthPrefixed, but targets a -// []byte instead of a cryptobyte.String. -func readUint16LengthPrefixed(s *cryptobyte.String, out *[]byte) bool { - return s.ReadUint16LengthPrefixed((*cryptobyte.String)(out)) -} - -// readUint24LengthPrefixed acts like s.ReadUint24LengthPrefixed, but targets a -// []byte instead of a cryptobyte.String. -func readUint24LengthPrefixed(s *cryptobyte.String, out *[]byte) bool { - return s.ReadUint24LengthPrefixed((*cryptobyte.String)(out)) -} - -type clientHelloMsg struct { - raw []byte - vers uint16 - random []byte - sessionId []byte - cipherSuites []uint16 - compressionMethods []uint8 - nextProtoNeg bool - serverName string - ocspStapling bool - supportedCurves []CurveID - supportedPoints []uint8 - ticketSupported bool - sessionTicket []uint8 - supportedSignatureAlgorithms []SignatureScheme - supportedSignatureAlgorithmsCert []SignatureScheme - secureRenegotiationSupported bool - secureRenegotiation []byte - alpnProtocols []string - scts bool - supportedVersions []uint16 - cookie []byte - keyShares []keyShare - earlyData bool - pskModes []uint8 - pskIdentities []pskIdentity - pskBinders [][]byte - additionalExtensions []Extension -} - -func (m *clientHelloMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - - var b cryptobyte.Builder - b.AddUint8(typeClientHello) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16(m.vers) - addBytesWithLength(b, m.random, 32) - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.sessionId) - }) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, suite := range m.cipherSuites { - b.AddUint16(suite) - } - }) - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.compressionMethods) - }) - - // If extensions aren't present, omit them. - var extensionsPresent bool - bWithoutExtensions := *b - - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - if m.nextProtoNeg { - // draft-agl-tls-nextprotoneg-04 - b.AddUint16(extensionNextProtoNeg) - b.AddUint16(0) // empty extension_data - } - if len(m.serverName) > 0 { - // RFC 6066, Section 3 - b.AddUint16(extensionServerName) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8(0) // name_type = host_name - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes([]byte(m.serverName)) - }) - }) - }) - } - if m.ocspStapling { - // RFC 4366, Section 3.6 - b.AddUint16(extensionStatusRequest) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8(1) // status_type = ocsp - b.AddUint16(0) // empty responder_id_list - b.AddUint16(0) // empty request_extensions - }) - } - if len(m.supportedCurves) > 0 { - // RFC 4492, sections 5.1.1 and RFC 8446, Section 4.2.7 - b.AddUint16(extensionSupportedCurves) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, curve := range m.supportedCurves { - b.AddUint16(uint16(curve)) - } - }) - }) - } - if len(m.supportedPoints) > 0 { - // RFC 4492, Section 5.1.2 - b.AddUint16(extensionSupportedPoints) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.supportedPoints) - }) - }) - } - if m.ticketSupported { - // RFC 5077, Section 3.2 - b.AddUint16(extensionSessionTicket) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.sessionTicket) - }) - } - if len(m.supportedSignatureAlgorithms) > 0 { - // RFC 5246, Section 7.4.1.4.1 - b.AddUint16(extensionSignatureAlgorithms) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, sigAlgo := range m.supportedSignatureAlgorithms { - b.AddUint16(uint16(sigAlgo)) - } - }) - }) - } - if len(m.supportedSignatureAlgorithmsCert) > 0 { - // RFC 8446, Section 4.2.3 - b.AddUint16(extensionSignatureAlgorithmsCert) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, sigAlgo := range m.supportedSignatureAlgorithmsCert { - b.AddUint16(uint16(sigAlgo)) - } - }) - }) - } - if m.secureRenegotiationSupported { - // RFC 5746, Section 3.2 - b.AddUint16(extensionRenegotiationInfo) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.secureRenegotiation) - }) - }) - } - if len(m.alpnProtocols) > 0 { - // RFC 7301, Section 3.1 - b.AddUint16(extensionALPN) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, proto := range m.alpnProtocols { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes([]byte(proto)) - }) - } - }) - }) - } - if m.scts { - // RFC 6962, Section 3.3.1 - b.AddUint16(extensionSCT) - b.AddUint16(0) // empty extension_data - } - if len(m.supportedVersions) > 0 { - // RFC 8446, Section 4.2.1 - b.AddUint16(extensionSupportedVersions) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - for _, vers := range m.supportedVersions { - b.AddUint16(vers) - } - }) - }) - } - if len(m.cookie) > 0 { - // RFC 8446, Section 4.2.2 - b.AddUint16(extensionCookie) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.cookie) - }) - }) - } - if len(m.keyShares) > 0 { - // RFC 8446, Section 4.2.8 - b.AddUint16(extensionKeyShare) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, ks := range m.keyShares { - b.AddUint16(uint16(ks.group)) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(ks.data) - }) - } - }) - }) - } - if m.earlyData { - // RFC 8446, Section 4.2.10 - b.AddUint16(extensionEarlyData) - b.AddUint16(0) // empty extension_data - } - if len(m.pskModes) > 0 { - // RFC 8446, Section 4.2.9 - b.AddUint16(extensionPSKModes) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.pskModes) - }) - }) - } - for _, ext := range m.additionalExtensions { - b.AddUint16(ext.Type) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(ext.Data) - }) - } - if len(m.pskIdentities) > 0 { // pre_shared_key must be the last extension - // RFC 8446, Section 4.2.11 - b.AddUint16(extensionPreSharedKey) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, psk := range m.pskIdentities { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(psk.label) - }) - b.AddUint32(psk.obfuscatedTicketAge) - } - }) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, binder := range m.pskBinders { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(binder) - }) - } - }) - }) - } - - extensionsPresent = len(b.BytesOrPanic()) > 2 - }) - - if !extensionsPresent { - *b = bWithoutExtensions - } - }) - - m.raw = b.BytesOrPanic() - return m.raw -} - -// marshalWithoutBinders returns the ClientHello through the -// PreSharedKeyExtension.identities field, according to RFC 8446, Section -// 4.2.11.2. Note that m.pskBinders must be set to slices of the correct length. -func (m *clientHelloMsg) marshalWithoutBinders() []byte { - bindersLen := 2 // uint16 length prefix - for _, binder := range m.pskBinders { - bindersLen += 1 // uint8 length prefix - bindersLen += len(binder) - } - - fullMessage := m.marshal() - return fullMessage[:len(fullMessage)-bindersLen] -} - -// updateBinders updates the m.pskBinders field, if necessary updating the -// cached marshalled representation. The supplied binders must have the same -// length as the current m.pskBinders. -func (m *clientHelloMsg) updateBinders(pskBinders [][]byte) { - if len(pskBinders) != len(m.pskBinders) { - panic("tls: internal error: pskBinders length mismatch") - } - for i := range m.pskBinders { - if len(pskBinders[i]) != len(m.pskBinders[i]) { - panic("tls: internal error: pskBinders length mismatch") - } - } - m.pskBinders = pskBinders - if m.raw != nil { - lenWithoutBinders := len(m.marshalWithoutBinders()) - // TODO(filippo): replace with NewFixedBuilder once CL 148882 is imported. - b := cryptobyte.NewBuilder(m.raw[:lenWithoutBinders]) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, binder := range m.pskBinders { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(binder) - }) - } - }) - if len(b.BytesOrPanic()) != len(m.raw) { - panic("tls: internal error: failed to update binders") - } - } -} - -func (m *clientHelloMsg) unmarshal(data []byte) bool { - *m = clientHelloMsg{raw: data} - s := cryptobyte.String(data) - - if !s.Skip(4) || // message type and uint24 length field - !s.ReadUint16(&m.vers) || !s.ReadBytes(&m.random, 32) || - !readUint8LengthPrefixed(&s, &m.sessionId) { - return false - } - - var cipherSuites cryptobyte.String - if !s.ReadUint16LengthPrefixed(&cipherSuites) { - return false - } - m.cipherSuites = []uint16{} - m.secureRenegotiationSupported = false - for !cipherSuites.Empty() { - var suite uint16 - if !cipherSuites.ReadUint16(&suite) { - return false - } - if suite == scsvRenegotiation { - m.secureRenegotiationSupported = true - } - m.cipherSuites = append(m.cipherSuites, suite) - } - - if !readUint8LengthPrefixed(&s, &m.compressionMethods) { - return false - } - - if s.Empty() { - // ClientHello is optionally followed by extension data - return true - } - - var extensions cryptobyte.String - if !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() { - return false - } - - for !extensions.Empty() { - var ext uint16 - var extData cryptobyte.String - if !extensions.ReadUint16(&ext) || - !extensions.ReadUint16LengthPrefixed(&extData) { - return false - } - - switch ext { - case extensionServerName: - // RFC 6066, Section 3 - var nameList cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&nameList) || nameList.Empty() { - return false - } - for !nameList.Empty() { - var nameType uint8 - var serverName cryptobyte.String - if !nameList.ReadUint8(&nameType) || - !nameList.ReadUint16LengthPrefixed(&serverName) || - serverName.Empty() { - return false - } - if nameType != 0 { - continue - } - if len(m.serverName) != 0 { - // Multiple names of the same name_type are prohibited. - return false - } - m.serverName = string(serverName) - // An SNI value may not include a trailing dot. - if strings.HasSuffix(m.serverName, ".") { - return false - } - } - case extensionNextProtoNeg: - // draft-agl-tls-nextprotoneg-04 - m.nextProtoNeg = true - case extensionStatusRequest: - // RFC 4366, Section 3.6 - var statusType uint8 - var ignored cryptobyte.String - if !extData.ReadUint8(&statusType) || - !extData.ReadUint16LengthPrefixed(&ignored) || - !extData.ReadUint16LengthPrefixed(&ignored) { - return false - } - m.ocspStapling = statusType == statusTypeOCSP - case extensionSupportedCurves: - // RFC 4492, sections 5.1.1 and RFC 8446, Section 4.2.7 - var curves cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&curves) || curves.Empty() { - return false - } - for !curves.Empty() { - var curve uint16 - if !curves.ReadUint16(&curve) { - return false - } - m.supportedCurves = append(m.supportedCurves, CurveID(curve)) - } - case extensionSupportedPoints: - // RFC 4492, Section 5.1.2 - if !readUint8LengthPrefixed(&extData, &m.supportedPoints) || - len(m.supportedPoints) == 0 { - return false - } - case extensionSessionTicket: - // RFC 5077, Section 3.2 - m.ticketSupported = true - extData.ReadBytes(&m.sessionTicket, len(extData)) - case extensionSignatureAlgorithms: - // RFC 5246, Section 7.4.1.4.1 - var sigAndAlgs cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() { - return false - } - for !sigAndAlgs.Empty() { - var sigAndAlg uint16 - if !sigAndAlgs.ReadUint16(&sigAndAlg) { - return false - } - m.supportedSignatureAlgorithms = append( - m.supportedSignatureAlgorithms, SignatureScheme(sigAndAlg)) - } - case extensionSignatureAlgorithmsCert: - // RFC 8446, Section 4.2.3 - var sigAndAlgs cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() { - return false - } - for !sigAndAlgs.Empty() { - var sigAndAlg uint16 - if !sigAndAlgs.ReadUint16(&sigAndAlg) { - return false - } - m.supportedSignatureAlgorithmsCert = append( - m.supportedSignatureAlgorithmsCert, SignatureScheme(sigAndAlg)) - } - case extensionRenegotiationInfo: - // RFC 5746, Section 3.2 - if !readUint8LengthPrefixed(&extData, &m.secureRenegotiation) { - return false - } - m.secureRenegotiationSupported = true - case extensionALPN: - // RFC 7301, Section 3.1 - var protoList cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() { - return false - } - for !protoList.Empty() { - var proto cryptobyte.String - if !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() { - return false - } - m.alpnProtocols = append(m.alpnProtocols, string(proto)) - } - case extensionSCT: - // RFC 6962, Section 3.3.1 - m.scts = true - case extensionSupportedVersions: - // RFC 8446, Section 4.2.1 - var versList cryptobyte.String - if !extData.ReadUint8LengthPrefixed(&versList) || versList.Empty() { - return false - } - for !versList.Empty() { - var vers uint16 - if !versList.ReadUint16(&vers) { - return false - } - m.supportedVersions = append(m.supportedVersions, vers) - } - case extensionCookie: - // RFC 8446, Section 4.2.2 - if !readUint16LengthPrefixed(&extData, &m.cookie) || - len(m.cookie) == 0 { - return false - } - case extensionKeyShare: - // RFC 8446, Section 4.2.8 - var clientShares cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&clientShares) { - return false - } - for !clientShares.Empty() { - var ks keyShare - if !clientShares.ReadUint16((*uint16)(&ks.group)) || - !readUint16LengthPrefixed(&clientShares, &ks.data) || - len(ks.data) == 0 { - return false - } - m.keyShares = append(m.keyShares, ks) - } - case extensionEarlyData: - // RFC 8446, Section 4.2.10 - m.earlyData = true - case extensionPSKModes: - // RFC 8446, Section 4.2.9 - if !readUint8LengthPrefixed(&extData, &m.pskModes) { - return false - } - case extensionPreSharedKey: - // RFC 8446, Section 4.2.11 - if !extensions.Empty() { - return false // pre_shared_key must be the last extension - } - var identities cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&identities) || identities.Empty() { - return false - } - for !identities.Empty() { - var psk pskIdentity - if !readUint16LengthPrefixed(&identities, &psk.label) || - !identities.ReadUint32(&psk.obfuscatedTicketAge) || - len(psk.label) == 0 { - return false - } - m.pskIdentities = append(m.pskIdentities, psk) - } - var binders cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&binders) || binders.Empty() { - return false - } - for !binders.Empty() { - var binder []byte - if !readUint8LengthPrefixed(&binders, &binder) || - len(binder) == 0 { - return false - } - m.pskBinders = append(m.pskBinders, binder) - } - default: - m.additionalExtensions = append(m.additionalExtensions, Extension{Type: ext, Data: extData}) - continue - } - - if !extData.Empty() { - return false - } - } - - return true -} - -type serverHelloMsg struct { - raw []byte - vers uint16 - random []byte - sessionId []byte - cipherSuite uint16 - compressionMethod uint8 - nextProtoNeg bool - nextProtos []string - ocspStapling bool - ticketSupported bool - secureRenegotiationSupported bool - secureRenegotiation []byte - alpnProtocol string - scts [][]byte - supportedVersion uint16 - serverShare keyShare - selectedIdentityPresent bool - selectedIdentity uint16 - - // HelloRetryRequest extensions - cookie []byte - selectedGroup CurveID -} - -func (m *serverHelloMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - - var b cryptobyte.Builder - b.AddUint8(typeServerHello) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16(m.vers) - addBytesWithLength(b, m.random, 32) - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.sessionId) - }) - b.AddUint16(m.cipherSuite) - b.AddUint8(m.compressionMethod) - - // If extensions aren't present, omit them. - var extensionsPresent bool - bWithoutExtensions := *b - - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - if m.nextProtoNeg { - b.AddUint16(extensionNextProtoNeg) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, proto := range m.nextProtos { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes([]byte(proto)) - }) - } - }) - } - if m.ocspStapling { - b.AddUint16(extensionStatusRequest) - b.AddUint16(0) // empty extension_data - } - if m.ticketSupported { - b.AddUint16(extensionSessionTicket) - b.AddUint16(0) // empty extension_data - } - if m.secureRenegotiationSupported { - b.AddUint16(extensionRenegotiationInfo) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.secureRenegotiation) - }) - }) - } - if len(m.alpnProtocol) > 0 { - b.AddUint16(extensionALPN) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes([]byte(m.alpnProtocol)) - }) - }) - }) - } - if len(m.scts) > 0 { - b.AddUint16(extensionSCT) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, sct := range m.scts { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(sct) - }) - } - }) - }) - } - if m.supportedVersion != 0 { - b.AddUint16(extensionSupportedVersions) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16(m.supportedVersion) - }) - } - if m.serverShare.group != 0 { - b.AddUint16(extensionKeyShare) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16(uint16(m.serverShare.group)) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.serverShare.data) - }) - }) - } - if m.selectedIdentityPresent { - b.AddUint16(extensionPreSharedKey) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16(m.selectedIdentity) - }) - } - - if len(m.cookie) > 0 { - b.AddUint16(extensionCookie) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.cookie) - }) - }) - } - if m.selectedGroup != 0 { - b.AddUint16(extensionKeyShare) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16(uint16(m.selectedGroup)) - }) - } - - extensionsPresent = len(b.BytesOrPanic()) > 2 - }) - - if !extensionsPresent { - *b = bWithoutExtensions - } - }) - - m.raw = b.BytesOrPanic() - return m.raw -} - -func (m *serverHelloMsg) unmarshal(data []byte) bool { - *m = serverHelloMsg{raw: data} - s := cryptobyte.String(data) - - if !s.Skip(4) || // message type and uint24 length field - !s.ReadUint16(&m.vers) || !s.ReadBytes(&m.random, 32) || - !readUint8LengthPrefixed(&s, &m.sessionId) || - !s.ReadUint16(&m.cipherSuite) || - !s.ReadUint8(&m.compressionMethod) { - return false - } - - if s.Empty() { - // ServerHello is optionally followed by extension data - return true - } - - var extensions cryptobyte.String - if !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() { - return false - } - - for !extensions.Empty() { - var extension uint16 - var extData cryptobyte.String - if !extensions.ReadUint16(&extension) || - !extensions.ReadUint16LengthPrefixed(&extData) { - return false - } - - switch extension { - case extensionNextProtoNeg: - m.nextProtoNeg = true - for !extData.Empty() { - var proto cryptobyte.String - if !extData.ReadUint8LengthPrefixed(&proto) || - proto.Empty() { - return false - } - m.nextProtos = append(m.nextProtos, string(proto)) - } - case extensionStatusRequest: - m.ocspStapling = true - case extensionSessionTicket: - m.ticketSupported = true - case extensionRenegotiationInfo: - if !readUint8LengthPrefixed(&extData, &m.secureRenegotiation) { - return false - } - m.secureRenegotiationSupported = true - case extensionALPN: - var protoList cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() { - return false - } - var proto cryptobyte.String - if !protoList.ReadUint8LengthPrefixed(&proto) || - proto.Empty() || !protoList.Empty() { - return false - } - m.alpnProtocol = string(proto) - case extensionSCT: - var sctList cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&sctList) || sctList.Empty() { - return false - } - for !sctList.Empty() { - var sct []byte - if !readUint16LengthPrefixed(&sctList, &sct) || - len(sct) == 0 { - return false - } - m.scts = append(m.scts, sct) - } - case extensionSupportedVersions: - if !extData.ReadUint16(&m.supportedVersion) { - return false - } - case extensionCookie: - if !readUint16LengthPrefixed(&extData, &m.cookie) || - len(m.cookie) == 0 { - return false - } - case extensionKeyShare: - // This extension has different formats in SH and HRR, accept either - // and let the handshake logic decide. See RFC 8446, Section 4.2.8. - if len(extData) == 2 { - if !extData.ReadUint16((*uint16)(&m.selectedGroup)) { - return false - } - } else { - if !extData.ReadUint16((*uint16)(&m.serverShare.group)) || - !readUint16LengthPrefixed(&extData, &m.serverShare.data) { - return false - } - } - case extensionPreSharedKey: - m.selectedIdentityPresent = true - if !extData.ReadUint16(&m.selectedIdentity) { - return false - } - default: - // Ignore unknown extensions. - continue - } - - if !extData.Empty() { - return false - } - } - - return true -} - -type encryptedExtensionsMsg struct { - raw []byte - alpnProtocol string - - additionalExtensions []Extension -} - -func (m *encryptedExtensionsMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - - var b cryptobyte.Builder - b.AddUint8(typeEncryptedExtensions) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - if len(m.alpnProtocol) > 0 { - b.AddUint16(extensionALPN) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes([]byte(m.alpnProtocol)) - }) - }) - }) - } - for _, ext := range m.additionalExtensions { - b.AddUint16(ext.Type) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(ext.Data) - }) - } - }) - }) - - m.raw = b.BytesOrPanic() - return m.raw -} - -func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool { - *m = encryptedExtensionsMsg{raw: data} - s := cryptobyte.String(data) - - var extensions cryptobyte.String - if !s.Skip(4) || // message type and uint24 length field - !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() { - return false - } - - for !extensions.Empty() { - var ext uint16 - var extData cryptobyte.String - if !extensions.ReadUint16(&ext) || - !extensions.ReadUint16LengthPrefixed(&extData) { - return false - } - - switch ext { - case extensionALPN: - var protoList cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() { - return false - } - var proto cryptobyte.String - if !protoList.ReadUint8LengthPrefixed(&proto) || - proto.Empty() || !protoList.Empty() { - return false - } - m.alpnProtocol = string(proto) - default: - m.additionalExtensions = append(m.additionalExtensions, Extension{Type: ext, Data: extData}) - continue - } - - if !extData.Empty() { - return false - } - } - - return true -} - -type endOfEarlyDataMsg struct{} - -func (m *endOfEarlyDataMsg) marshal() []byte { - x := make([]byte, 4) - x[0] = typeEndOfEarlyData - return x -} - -func (m *endOfEarlyDataMsg) unmarshal(data []byte) bool { - return len(data) == 4 -} - -type keyUpdateMsg struct { - raw []byte - updateRequested bool -} - -func (m *keyUpdateMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - - var b cryptobyte.Builder - b.AddUint8(typeKeyUpdate) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - if m.updateRequested { - b.AddUint8(1) - } else { - b.AddUint8(0) - } - }) - - m.raw = b.BytesOrPanic() - return m.raw -} - -func (m *keyUpdateMsg) unmarshal(data []byte) bool { - m.raw = data - s := cryptobyte.String(data) - - var updateRequested uint8 - if !s.Skip(4) || // message type and uint24 length field - !s.ReadUint8(&updateRequested) || !s.Empty() { - return false - } - switch updateRequested { - case 0: - m.updateRequested = false - case 1: - m.updateRequested = true - default: - return false - } - return true -} - -type newSessionTicketMsgTLS13 struct { - raw []byte - lifetime uint32 - ageAdd uint32 - nonce []byte - label []byte - maxEarlyData uint32 -} - -func (m *newSessionTicketMsgTLS13) marshal() []byte { - if m.raw != nil { - return m.raw - } - - var b cryptobyte.Builder - b.AddUint8(typeNewSessionTicket) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint32(m.lifetime) - b.AddUint32(m.ageAdd) - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.nonce) - }) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.label) - }) - - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - if m.maxEarlyData > 0 { - b.AddUint16(extensionEarlyData) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint32(m.maxEarlyData) - }) - } - }) - }) - - m.raw = b.BytesOrPanic() - return m.raw -} - -func (m *newSessionTicketMsgTLS13) unmarshal(data []byte) bool { - *m = newSessionTicketMsgTLS13{raw: data} - s := cryptobyte.String(data) - - var extensions cryptobyte.String - if !s.Skip(4) || // message type and uint24 length field - !s.ReadUint32(&m.lifetime) || - !s.ReadUint32(&m.ageAdd) || - !readUint8LengthPrefixed(&s, &m.nonce) || - !readUint16LengthPrefixed(&s, &m.label) || - !s.ReadUint16LengthPrefixed(&extensions) || - !s.Empty() { - return false - } - - for !extensions.Empty() { - var extension uint16 - var extData cryptobyte.String - if !extensions.ReadUint16(&extension) || - !extensions.ReadUint16LengthPrefixed(&extData) { - return false - } - - switch extension { - case extensionEarlyData: - if !extData.ReadUint32(&m.maxEarlyData) { - return false - } - default: - // Ignore unknown extensions. - continue - } - - if !extData.Empty() { - return false - } - } - - return true -} - -type certificateRequestMsgTLS13 struct { - raw []byte - ocspStapling bool - scts bool - supportedSignatureAlgorithms []SignatureScheme - supportedSignatureAlgorithmsCert []SignatureScheme - certificateAuthorities [][]byte -} - -func (m *certificateRequestMsgTLS13) marshal() []byte { - if m.raw != nil { - return m.raw - } - - var b cryptobyte.Builder - b.AddUint8(typeCertificateRequest) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - // certificate_request_context (SHALL be zero length unless used for - // post-handshake authentication) - b.AddUint8(0) - - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - if m.ocspStapling { - b.AddUint16(extensionStatusRequest) - b.AddUint16(0) // empty extension_data - } - if m.scts { - // RFC 8446, Section 4.4.2.1 makes no mention of - // signed_certificate_timestamp in CertificateRequest, but - // "Extensions in the Certificate message from the client MUST - // correspond to extensions in the CertificateRequest message - // from the server." and it appears in the table in Section 4.2. - b.AddUint16(extensionSCT) - b.AddUint16(0) // empty extension_data - } - if len(m.supportedSignatureAlgorithms) > 0 { - b.AddUint16(extensionSignatureAlgorithms) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, sigAlgo := range m.supportedSignatureAlgorithms { - b.AddUint16(uint16(sigAlgo)) - } - }) - }) - } - if len(m.supportedSignatureAlgorithmsCert) > 0 { - b.AddUint16(extensionSignatureAlgorithmsCert) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, sigAlgo := range m.supportedSignatureAlgorithmsCert { - b.AddUint16(uint16(sigAlgo)) - } - }) - }) - } - if len(m.certificateAuthorities) > 0 { - b.AddUint16(extensionCertificateAuthorities) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, ca := range m.certificateAuthorities { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(ca) - }) - } - }) - }) - } - }) - }) - - m.raw = b.BytesOrPanic() - return m.raw -} - -func (m *certificateRequestMsgTLS13) unmarshal(data []byte) bool { - *m = certificateRequestMsgTLS13{raw: data} - s := cryptobyte.String(data) - - var context, extensions cryptobyte.String - if !s.Skip(4) || // message type and uint24 length field - !s.ReadUint8LengthPrefixed(&context) || !context.Empty() || - !s.ReadUint16LengthPrefixed(&extensions) || - !s.Empty() { - return false - } - - for !extensions.Empty() { - var extension uint16 - var extData cryptobyte.String - if !extensions.ReadUint16(&extension) || - !extensions.ReadUint16LengthPrefixed(&extData) { - return false - } - - switch extension { - case extensionStatusRequest: - m.ocspStapling = true - case extensionSCT: - m.scts = true - case extensionSignatureAlgorithms: - var sigAndAlgs cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() { - return false - } - for !sigAndAlgs.Empty() { - var sigAndAlg uint16 - if !sigAndAlgs.ReadUint16(&sigAndAlg) { - return false - } - m.supportedSignatureAlgorithms = append( - m.supportedSignatureAlgorithms, SignatureScheme(sigAndAlg)) - } - case extensionSignatureAlgorithmsCert: - var sigAndAlgs cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() { - return false - } - for !sigAndAlgs.Empty() { - var sigAndAlg uint16 - if !sigAndAlgs.ReadUint16(&sigAndAlg) { - return false - } - m.supportedSignatureAlgorithmsCert = append( - m.supportedSignatureAlgorithmsCert, SignatureScheme(sigAndAlg)) - } - case extensionCertificateAuthorities: - var auths cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&auths) || auths.Empty() { - return false - } - for !auths.Empty() { - var ca []byte - if !readUint16LengthPrefixed(&auths, &ca) || len(ca) == 0 { - return false - } - m.certificateAuthorities = append(m.certificateAuthorities, ca) - } - default: - // Ignore unknown extensions. - continue - } - - if !extData.Empty() { - return false - } - } - - return true -} - -type certificateMsg struct { - raw []byte - certificates [][]byte -} - -func (m *certificateMsg) marshal() (x []byte) { - if m.raw != nil { - return m.raw - } - - var i int - for _, slice := range m.certificates { - i += len(slice) - } - - length := 3 + 3*len(m.certificates) + i - x = make([]byte, 4+length) - x[0] = typeCertificate - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - - certificateOctets := length - 3 - x[4] = uint8(certificateOctets >> 16) - x[5] = uint8(certificateOctets >> 8) - x[6] = uint8(certificateOctets) - - y := x[7:] - for _, slice := range m.certificates { - y[0] = uint8(len(slice) >> 16) - y[1] = uint8(len(slice) >> 8) - y[2] = uint8(len(slice)) - copy(y[3:], slice) - y = y[3+len(slice):] - } - - m.raw = x - return -} - -func (m *certificateMsg) unmarshal(data []byte) bool { - if len(data) < 7 { - return false - } - - m.raw = data - certsLen := uint32(data[4])<<16 | uint32(data[5])<<8 | uint32(data[6]) - if uint32(len(data)) != certsLen+7 { - return false - } - - numCerts := 0 - d := data[7:] - for certsLen > 0 { - if len(d) < 4 { - return false - } - certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2]) - if uint32(len(d)) < 3+certLen { - return false - } - d = d[3+certLen:] - certsLen -= 3 + certLen - numCerts++ - } - - m.certificates = make([][]byte, numCerts) - d = data[7:] - for i := 0; i < numCerts; i++ { - certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2]) - m.certificates[i] = d[3 : 3+certLen] - d = d[3+certLen:] - } - - return true -} - -type certificateMsgTLS13 struct { - raw []byte - certificate Certificate - ocspStapling bool - scts bool -} - -func (m *certificateMsgTLS13) marshal() []byte { - if m.raw != nil { - return m.raw - } - - var b cryptobyte.Builder - b.AddUint8(typeCertificate) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8(0) // certificate_request_context - - certificate := m.certificate - if !m.ocspStapling { - certificate.OCSPStaple = nil - } - if !m.scts { - certificate.SignedCertificateTimestamps = nil - } - marshalCertificate(b, certificate) - }) - - m.raw = b.BytesOrPanic() - return m.raw -} - -func marshalCertificate(b *cryptobyte.Builder, certificate Certificate) { - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - for i, cert := range certificate.Certificate { - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(cert) - }) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - if i > 0 { - // This library only supports OCSP and SCT for leaf certificates. - return - } - if certificate.OCSPStaple != nil { - b.AddUint16(extensionStatusRequest) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8(statusTypeOCSP) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(certificate.OCSPStaple) - }) - }) - } - if certificate.SignedCertificateTimestamps != nil { - b.AddUint16(extensionSCT) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - for _, sct := range certificate.SignedCertificateTimestamps { - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(sct) - }) - } - }) - }) - } - }) - } - }) -} - -func (m *certificateMsgTLS13) unmarshal(data []byte) bool { - *m = certificateMsgTLS13{raw: data} - s := cryptobyte.String(data) - - var context cryptobyte.String - if !s.Skip(4) || // message type and uint24 length field - !s.ReadUint8LengthPrefixed(&context) || !context.Empty() || - !unmarshalCertificate(&s, &m.certificate) || - !s.Empty() { - return false - } - - m.scts = m.certificate.SignedCertificateTimestamps != nil - m.ocspStapling = m.certificate.OCSPStaple != nil - - return true -} - -func unmarshalCertificate(s *cryptobyte.String, certificate *Certificate) bool { - var certList cryptobyte.String - if !s.ReadUint24LengthPrefixed(&certList) { - return false - } - for !certList.Empty() { - var cert []byte - var extensions cryptobyte.String - if !readUint24LengthPrefixed(&certList, &cert) || - !certList.ReadUint16LengthPrefixed(&extensions) { - return false - } - certificate.Certificate = append(certificate.Certificate, cert) - for !extensions.Empty() { - var extension uint16 - var extData cryptobyte.String - if !extensions.ReadUint16(&extension) || - !extensions.ReadUint16LengthPrefixed(&extData) { - return false - } - if len(certificate.Certificate) > 1 { - // This library only supports OCSP and SCT for leaf certificates. - continue - } - - switch extension { - case extensionStatusRequest: - var statusType uint8 - if !extData.ReadUint8(&statusType) || statusType != statusTypeOCSP || - !readUint24LengthPrefixed(&extData, &certificate.OCSPStaple) || - len(certificate.OCSPStaple) == 0 { - return false - } - case extensionSCT: - var sctList cryptobyte.String - if !extData.ReadUint16LengthPrefixed(&sctList) || sctList.Empty() { - return false - } - for !sctList.Empty() { - var sct []byte - if !readUint16LengthPrefixed(&sctList, &sct) || - len(sct) == 0 { - return false - } - certificate.SignedCertificateTimestamps = append( - certificate.SignedCertificateTimestamps, sct) - } - default: - // Ignore unknown extensions. - continue - } - - if !extData.Empty() { - return false - } - } - } - return true -} - -type serverKeyExchangeMsg struct { - raw []byte - key []byte -} - -func (m *serverKeyExchangeMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - length := len(m.key) - x := make([]byte, length+4) - x[0] = typeServerKeyExchange - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - copy(x[4:], m.key) - - m.raw = x - return x -} - -func (m *serverKeyExchangeMsg) unmarshal(data []byte) bool { - m.raw = data - if len(data) < 4 { - return false - } - m.key = data[4:] - return true -} - -type certificateStatusMsg struct { - raw []byte - response []byte -} - -func (m *certificateStatusMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - - var b cryptobyte.Builder - b.AddUint8(typeCertificateStatus) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddUint8(statusTypeOCSP) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.response) - }) - }) - - m.raw = b.BytesOrPanic() - return m.raw -} - -func (m *certificateStatusMsg) unmarshal(data []byte) bool { - m.raw = data - s := cryptobyte.String(data) - - var statusType uint8 - if !s.Skip(4) || // message type and uint24 length field - !s.ReadUint8(&statusType) || statusType != statusTypeOCSP || - !readUint24LengthPrefixed(&s, &m.response) || - len(m.response) == 0 || !s.Empty() { - return false - } - return true -} - -type serverHelloDoneMsg struct{} - -func (m *serverHelloDoneMsg) marshal() []byte { - x := make([]byte, 4) - x[0] = typeServerHelloDone - return x -} - -func (m *serverHelloDoneMsg) unmarshal(data []byte) bool { - return len(data) == 4 -} - -type clientKeyExchangeMsg struct { - raw []byte - ciphertext []byte -} - -func (m *clientKeyExchangeMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - length := len(m.ciphertext) - x := make([]byte, length+4) - x[0] = typeClientKeyExchange - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - copy(x[4:], m.ciphertext) - - m.raw = x - return x -} - -func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool { - m.raw = data - if len(data) < 4 { - return false - } - l := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) - if l != len(data)-4 { - return false - } - m.ciphertext = data[4:] - return true -} - -type finishedMsg struct { - raw []byte - verifyData []byte -} - -func (m *finishedMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - - var b cryptobyte.Builder - b.AddUint8(typeFinished) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.verifyData) - }) - - m.raw = b.BytesOrPanic() - return m.raw -} - -func (m *finishedMsg) unmarshal(data []byte) bool { - m.raw = data - s := cryptobyte.String(data) - return s.Skip(1) && - readUint24LengthPrefixed(&s, &m.verifyData) && - s.Empty() -} - -type nextProtoMsg struct { - raw []byte - proto string -} - -func (m *nextProtoMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - l := len(m.proto) - if l > 255 { - l = 255 - } - - padding := 32 - (l+2)%32 - length := l + padding + 2 - x := make([]byte, length+4) - x[0] = typeNextProtocol - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - - y := x[4:] - y[0] = byte(l) - copy(y[1:], []byte(m.proto[0:l])) - y = y[1+l:] - y[0] = byte(padding) - - m.raw = x - - return x -} - -func (m *nextProtoMsg) unmarshal(data []byte) bool { - m.raw = data - - if len(data) < 5 { - return false - } - data = data[4:] - protoLen := int(data[0]) - data = data[1:] - if len(data) < protoLen { - return false - } - m.proto = string(data[0:protoLen]) - data = data[protoLen:] - - if len(data) < 1 { - return false - } - paddingLen := int(data[0]) - data = data[1:] - if len(data) != paddingLen { - return false - } - - return true -} - -type certificateRequestMsg struct { - raw []byte - // hasSignatureAlgorithm indicates whether this message includes a list of - // supported signature algorithms. This change was introduced with TLS 1.2. - hasSignatureAlgorithm bool - - certificateTypes []byte - supportedSignatureAlgorithms []SignatureScheme - certificateAuthorities [][]byte -} - -func (m *certificateRequestMsg) marshal() (x []byte) { - if m.raw != nil { - return m.raw - } - - // See RFC 4346, Section 7.4.4. - length := 1 + len(m.certificateTypes) + 2 - casLength := 0 - for _, ca := range m.certificateAuthorities { - casLength += 2 + len(ca) - } - length += casLength - - if m.hasSignatureAlgorithm { - length += 2 + 2*len(m.supportedSignatureAlgorithms) - } - - x = make([]byte, 4+length) - x[0] = typeCertificateRequest - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - - x[4] = uint8(len(m.certificateTypes)) - - copy(x[5:], m.certificateTypes) - y := x[5+len(m.certificateTypes):] - - if m.hasSignatureAlgorithm { - n := len(m.supportedSignatureAlgorithms) * 2 - y[0] = uint8(n >> 8) - y[1] = uint8(n) - y = y[2:] - for _, sigAlgo := range m.supportedSignatureAlgorithms { - y[0] = uint8(sigAlgo >> 8) - y[1] = uint8(sigAlgo) - y = y[2:] - } - } - - y[0] = uint8(casLength >> 8) - y[1] = uint8(casLength) - y = y[2:] - for _, ca := range m.certificateAuthorities { - y[0] = uint8(len(ca) >> 8) - y[1] = uint8(len(ca)) - y = y[2:] - copy(y, ca) - y = y[len(ca):] - } - - m.raw = x - return -} - -func (m *certificateRequestMsg) unmarshal(data []byte) bool { - m.raw = data - - if len(data) < 5 { - return false - } - - length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3]) - if uint32(len(data))-4 != length { - return false - } - - numCertTypes := int(data[4]) - data = data[5:] - if numCertTypes == 0 || len(data) <= numCertTypes { - return false - } - - m.certificateTypes = make([]byte, numCertTypes) - if copy(m.certificateTypes, data) != numCertTypes { - return false - } - - data = data[numCertTypes:] - - if m.hasSignatureAlgorithm { - if len(data) < 2 { - return false - } - sigAndHashLen := uint16(data[0])<<8 | uint16(data[1]) - data = data[2:] - if sigAndHashLen&1 != 0 { - return false - } - if len(data) < int(sigAndHashLen) { - return false - } - numSigAlgos := sigAndHashLen / 2 - m.supportedSignatureAlgorithms = make([]SignatureScheme, numSigAlgos) - for i := range m.supportedSignatureAlgorithms { - m.supportedSignatureAlgorithms[i] = SignatureScheme(data[0])<<8 | SignatureScheme(data[1]) - data = data[2:] - } - } - - if len(data) < 2 { - return false - } - casLength := uint16(data[0])<<8 | uint16(data[1]) - data = data[2:] - if len(data) < int(casLength) { - return false - } - cas := make([]byte, casLength) - copy(cas, data) - data = data[casLength:] - - m.certificateAuthorities = nil - for len(cas) > 0 { - if len(cas) < 2 { - return false - } - caLen := uint16(cas[0])<<8 | uint16(cas[1]) - cas = cas[2:] - - if len(cas) < int(caLen) { - return false - } - - m.certificateAuthorities = append(m.certificateAuthorities, cas[:caLen]) - cas = cas[caLen:] - } - - return len(data) == 0 -} - -type certificateVerifyMsg struct { - raw []byte - hasSignatureAlgorithm bool // format change introduced in TLS 1.2 - signatureAlgorithm SignatureScheme - signature []byte -} - -func (m *certificateVerifyMsg) marshal() (x []byte) { - if m.raw != nil { - return m.raw - } - - var b cryptobyte.Builder - b.AddUint8(typeCertificateVerify) - b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { - if m.hasSignatureAlgorithm { - b.AddUint16(uint16(m.signatureAlgorithm)) - } - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.signature) - }) - }) - - m.raw = b.BytesOrPanic() - return m.raw -} - -func (m *certificateVerifyMsg) unmarshal(data []byte) bool { - m.raw = data - s := cryptobyte.String(data) - - if !s.Skip(4) { // message type and uint24 length field - return false - } - if m.hasSignatureAlgorithm { - if !s.ReadUint16((*uint16)(&m.signatureAlgorithm)) { - return false - } - } - return readUint16LengthPrefixed(&s, &m.signature) && s.Empty() -} - -type newSessionTicketMsg struct { - raw []byte - ticket []byte -} - -func (m *newSessionTicketMsg) marshal() (x []byte) { - if m.raw != nil { - return m.raw - } - - // See RFC 5077, Section 3.3. - ticketLen := len(m.ticket) - length := 2 + 4 + ticketLen - x = make([]byte, 4+length) - x[0] = typeNewSessionTicket - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - x[8] = uint8(ticketLen >> 8) - x[9] = uint8(ticketLen) - copy(x[10:], m.ticket) - - m.raw = x - - return -} - -func (m *newSessionTicketMsg) unmarshal(data []byte) bool { - m.raw = data - - if len(data) < 10 { - return false - } - - length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3]) - if uint32(len(data))-4 != length { - return false - } - - ticketLen := int(data[8])<<8 + int(data[9]) - if len(data)-10 != ticketLen { - return false - } - - m.ticket = data[10:] - - return true -} - -type helloRequestMsg struct { -} - -func (*helloRequestMsg) marshal() []byte { - return []byte{typeHelloRequest, 0, 0, 0} -} - -func (*helloRequestMsg) unmarshal(data []byte) bool { - return len(data) == 4 -} diff --git a/vendor/github.com/marten-seemann/qtls/handshake_server.go b/vendor/github.com/marten-seemann/qtls/handshake_server.go deleted file mode 100644 index 2f3b414472..0000000000 --- a/vendor/github.com/marten-seemann/qtls/handshake_server.go +++ /dev/null @@ -1,822 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rsa" - "crypto/subtle" - "crypto/x509" - "errors" - "fmt" - "io" - "sync/atomic" -) - -// serverHandshakeState contains details of a server handshake in progress. -// It's discarded once the handshake has completed. -type serverHandshakeState struct { - c *Conn - clientHello *clientHelloMsg - hello *serverHelloMsg - suite *cipherSuite - ellipticOk bool - ecdsaOk bool - rsaDecryptOk bool - rsaSignOk bool - sessionState *sessionState - finishedHash finishedHash - masterSecret []byte - cert *Certificate -} - -// serverHandshake performs a TLS handshake as a server. -func (c *Conn) serverHandshake() error { - // If this is the first server handshake, we generate a random key to - // encrypt the tickets with. - c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) }) - c.setAlternativeRecordLayer() - - clientHello, err := c.readClientHello() - if err != nil { - return err - } - - if c.vers == VersionTLS13 { - hs := serverHandshakeStateTLS13{ - c: c, - clientHello: clientHello, - } - return hs.handshake() - } - - hs := serverHandshakeState{ - c: c, - clientHello: clientHello, - } - return hs.handshake() -} - -func (hs *serverHandshakeState) handshake() error { - c := hs.c - - if err := hs.processClientHello(); err != nil { - return err - } - - // For an overview of TLS handshaking, see RFC 5246, Section 7.3. - c.buffering = true - if hs.checkForResumption() { - // The client has included a session ticket and so we do an abbreviated handshake. - if err := hs.doResumeHandshake(); err != nil { - return err - } - if err := hs.establishKeys(); err != nil { - return err - } - // ticketSupported is set in a resumption handshake if the - // ticket from the client was encrypted with an old session - // ticket key and thus a refreshed ticket should be sent. - if hs.hello.ticketSupported { - if err := hs.sendSessionTicket(); err != nil { - return err - } - } - if err := hs.sendFinished(c.serverFinished[:]); err != nil { - return err - } - if _, err := c.flush(); err != nil { - return err - } - c.clientFinishedIsFirst = false - if err := hs.readFinished(nil); err != nil { - return err - } - c.didResume = true - } else { - // The client didn't include a session ticket, or it wasn't - // valid so we do a full handshake. - if err := hs.pickCipherSuite(); err != nil { - return err - } - if err := hs.doFullHandshake(); err != nil { - return err - } - if err := hs.establishKeys(); err != nil { - return err - } - if err := hs.readFinished(c.clientFinished[:]); err != nil { - return err - } - c.clientFinishedIsFirst = true - c.buffering = true - if err := hs.sendSessionTicket(); err != nil { - return err - } - if err := hs.sendFinished(nil); err != nil { - return err - } - if _, err := c.flush(); err != nil { - return err - } - } - - c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random) - atomic.StoreUint32(&c.handshakeStatus, 1) - - return nil -} - -// readClientHello reads a ClientHello message and selects the protocol version. -func (c *Conn) readClientHello() (*clientHelloMsg, error) { - msg, err := c.readHandshake() - if err != nil { - return nil, err - } - clientHello, ok := msg.(*clientHelloMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return nil, unexpectedMessageError(clientHello, msg) - } - - if c.config.GetConfigForClient != nil { - chi := clientHelloInfo(c, clientHello) - if newConfig, err := c.config.GetConfigForClient(chi); err != nil { - c.sendAlert(alertInternalError) - return nil, err - } else if newConfig != nil { - newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) }) - c.config = newConfig - } - } - - clientVersions := clientHello.supportedVersions - if len(clientHello.supportedVersions) == 0 { - clientVersions = supportedVersionsFromMax(clientHello.vers) - } - c.vers, ok = c.config.mutualVersion(false, clientVersions) - if !ok { - c.sendAlert(alertProtocolVersion) - return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions) - } - c.haveVers = true - c.in.version = c.vers - c.out.version = c.vers - - return clientHello, nil -} - -func (hs *serverHandshakeState) processClientHello() error { - c := hs.c - - hs.hello = new(serverHelloMsg) - hs.hello.vers = c.vers - - supportedCurve := false - preferredCurves := c.config.curvePreferences() -Curves: - for _, curve := range hs.clientHello.supportedCurves { - for _, supported := range preferredCurves { - if supported == curve { - supportedCurve = true - break Curves - } - } - } - - supportedPointFormat := false - for _, pointFormat := range hs.clientHello.supportedPoints { - if pointFormat == pointFormatUncompressed { - supportedPointFormat = true - break - } - } - hs.ellipticOk = supportedCurve && supportedPointFormat - - foundCompression := false - // We only support null compression, so check that the client offered it. - for _, compression := range hs.clientHello.compressionMethods { - if compression == compressionNone { - foundCompression = true - break - } - } - - if !foundCompression { - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: client does not support uncompressed connections") - } - - hs.hello.random = make([]byte, 32) - serverRandom := hs.hello.random - // Downgrade protection canaries. See RFC 8446, Section 4.1.3. - maxVers := c.config.maxSupportedVersion(false) - if maxVers >= VersionTLS12 && c.vers < maxVers { - if c.vers == VersionTLS12 { - copy(serverRandom[24:], downgradeCanaryTLS12) - } else { - copy(serverRandom[24:], downgradeCanaryTLS11) - } - serverRandom = serverRandom[:24] - } - _, err := io.ReadFull(c.config.rand(), serverRandom) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - - if len(hs.clientHello.secureRenegotiation) != 0 { - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: initial handshake had non-empty renegotiation extension") - } - - hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported - hs.hello.compressionMethod = compressionNone - if len(hs.clientHello.serverName) > 0 { - c.serverName = hs.clientHello.serverName - } - - if len(hs.clientHello.alpnProtocols) > 0 { - if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback { - hs.hello.alpnProtocol = selectedProto - c.clientProtocol = selectedProto - } - } else { - // Although sending an empty NPN extension is reasonable, Firefox has - // had a bug around this. Best to send nothing at all if - // c.config.NextProtos is empty. See - // https://golang.org/issue/5445. - if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 { - hs.hello.nextProtoNeg = true - hs.hello.nextProtos = c.config.NextProtos - } - } - - hs.cert, err = c.config.getCertificate(clientHelloInfo(c, hs.clientHello)) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - if hs.clientHello.scts { - hs.hello.scts = hs.cert.SignedCertificateTimestamps - } - - if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok { - switch priv.Public().(type) { - case *ecdsa.PublicKey: - hs.ecdsaOk = true - case *rsa.PublicKey: - hs.rsaSignOk = true - default: - c.sendAlert(alertInternalError) - return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public()) - } - } - if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok { - switch priv.Public().(type) { - case *rsa.PublicKey: - hs.rsaDecryptOk = true - default: - c.sendAlert(alertInternalError) - return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public()) - } - } - - return nil -} - -func (hs *serverHandshakeState) pickCipherSuite() error { - c := hs.c - - var preferenceList, supportedList []uint16 - if c.config.PreferServerCipherSuites { - preferenceList = c.config.cipherSuites() - supportedList = hs.clientHello.cipherSuites - } else { - preferenceList = hs.clientHello.cipherSuites - supportedList = c.config.cipherSuites() - } - - for _, id := range preferenceList { - if hs.setCipherSuite(id, supportedList, c.vers) { - break - } - } - - if hs.suite == nil { - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: no cipher suite supported by both client and server") - } - - for _, id := range hs.clientHello.cipherSuites { - if id == TLS_FALLBACK_SCSV { - // The client is doing a fallback connection. See RFC 7507. - if hs.clientHello.vers < c.config.maxSupportedVersion(false) { - c.sendAlert(alertInappropriateFallback) - return errors.New("tls: client using inappropriate protocol fallback") - } - break - } - } - - return nil -} - -// checkForResumption reports whether we should perform resumption on this connection. -func (hs *serverHandshakeState) checkForResumption() bool { - c := hs.c - - if c.config.SessionTicketsDisabled { - return false - } - - plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket) - if plaintext == nil { - return false - } - hs.sessionState = &sessionState{usedOldKey: usedOldKey} - ok := hs.sessionState.unmarshal(plaintext) - if !ok { - return false - } - - // Never resume a session for a different TLS version. - if c.vers != hs.sessionState.vers { - return false - } - - cipherSuiteOk := false - // Check that the client is still offering the ciphersuite in the session. - for _, id := range hs.clientHello.cipherSuites { - if id == hs.sessionState.cipherSuite { - cipherSuiteOk = true - break - } - } - if !cipherSuiteOk { - return false - } - - // Check that we also support the ciphersuite from the session. - if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) { - return false - } - - sessionHasClientCerts := len(hs.sessionState.certificates) != 0 - needClientCerts := requiresClientCert(c.config.ClientAuth) - if needClientCerts && !sessionHasClientCerts { - return false - } - if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { - return false - } - - return true -} - -func (hs *serverHandshakeState) doResumeHandshake() error { - c := hs.c - - hs.hello.cipherSuite = hs.suite.id - // We echo the client's session ID in the ServerHello to let it know - // that we're doing a resumption. - hs.hello.sessionId = hs.clientHello.sessionId - hs.hello.ticketSupported = hs.sessionState.usedOldKey - hs.finishedHash = newFinishedHash(c.vers, hs.suite) - hs.finishedHash.discardHandshakeBuffer() - hs.finishedHash.Write(hs.clientHello.marshal()) - hs.finishedHash.Write(hs.hello.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { - return err - } - - if err := c.processCertsFromClient(Certificate{ - Certificate: hs.sessionState.certificates, - }); err != nil { - return err - } - - hs.masterSecret = hs.sessionState.masterSecret - - return nil -} - -func (hs *serverHandshakeState) doFullHandshake() error { - c := hs.c - - if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 { - hs.hello.ocspStapling = true - } - - hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled - hs.hello.cipherSuite = hs.suite.id - - hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite) - if c.config.ClientAuth == NoClientCert { - // No need to keep a full record of the handshake if client - // certificates won't be used. - hs.finishedHash.discardHandshakeBuffer() - } - hs.finishedHash.Write(hs.clientHello.marshal()) - hs.finishedHash.Write(hs.hello.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { - return err - } - - certMsg := new(certificateMsg) - certMsg.certificates = hs.cert.Certificate - hs.finishedHash.Write(certMsg.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { - return err - } - - if hs.hello.ocspStapling { - certStatus := new(certificateStatusMsg) - certStatus.response = hs.cert.OCSPStaple - hs.finishedHash.Write(certStatus.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil { - return err - } - } - - keyAgreement := hs.suite.ka(c.vers) - skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello) - if err != nil { - c.sendAlert(alertHandshakeFailure) - return err - } - if skx != nil { - hs.finishedHash.Write(skx.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil { - return err - } - } - - if c.config.ClientAuth >= RequestClientCert { - // Request a client certificate - certReq := new(certificateRequestMsg) - certReq.certificateTypes = []byte{ - byte(certTypeRSASign), - byte(certTypeECDSASign), - } - if c.vers >= VersionTLS12 { - certReq.hasSignatureAlgorithm = true - certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithmsTLS12 - } - - // An empty list of certificateAuthorities signals to - // the client that it may send any certificate in response - // to our request. When we know the CAs we trust, then - // we can send them down, so that the client can choose - // an appropriate certificate to give to us. - if c.config.ClientCAs != nil { - certReq.certificateAuthorities = c.config.ClientCAs.Subjects() - } - hs.finishedHash.Write(certReq.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil { - return err - } - } - - helloDone := new(serverHelloDoneMsg) - hs.finishedHash.Write(helloDone.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil { - return err - } - - if _, err := c.flush(); err != nil { - return err - } - - var pub crypto.PublicKey // public key for client auth, if any - - msg, err := c.readHandshake() - if err != nil { - return err - } - - // If we requested a client certificate, then the client must send a - // certificate message, even if it's empty. - if c.config.ClientAuth >= RequestClientCert { - certMsg, ok := msg.(*certificateMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(certMsg, msg) - } - hs.finishedHash.Write(certMsg.marshal()) - - if err := c.processCertsFromClient(Certificate{ - Certificate: certMsg.certificates, - }); err != nil { - return err - } - if len(certMsg.certificates) != 0 { - pub = c.peerCertificates[0].PublicKey - } - - msg, err = c.readHandshake() - if err != nil { - return err - } - } - - // Get client key exchange - ckx, ok := msg.(*clientKeyExchangeMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(ckx, msg) - } - hs.finishedHash.Write(ckx.marshal()) - - preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers) - if err != nil { - c.sendAlert(alertHandshakeFailure) - return err - } - hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random) - if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil { - c.sendAlert(alertInternalError) - return err - } - - // If we received a client cert in response to our certificate request message, - // the client will send us a certificateVerifyMsg immediately after the - // clientKeyExchangeMsg. This message is a digest of all preceding - // handshake-layer messages that is signed using the private key corresponding - // to the client's certificate. This allows us to verify that the client is in - // possession of the private key of the certificate. - if len(c.peerCertificates) > 0 { - msg, err = c.readHandshake() - if err != nil { - return err - } - certVerify, ok := msg.(*certificateVerifyMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(certVerify, msg) - } - - // Determine the signature type. - _, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, supportedSignatureAlgorithmsTLS12, c.vers) - if err != nil { - c.sendAlert(alertIllegalParameter) - return err - } - - var digest []byte - if digest, err = hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret); err == nil { - err = verifyHandshakeSignature(sigType, pub, hashFunc, digest, certVerify.signature) - } - if err != nil { - c.sendAlert(alertBadCertificate) - return errors.New("tls: could not validate signature of connection nonces: " + err.Error()) - } - - hs.finishedHash.Write(certVerify.marshal()) - } - - hs.finishedHash.discardHandshakeBuffer() - - return nil -} - -func (hs *serverHandshakeState) establishKeys() error { - c := hs.c - - clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := - keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) - - var clientCipher, serverCipher interface{} - var clientHash, serverHash macFunction - - if hs.suite.aead == nil { - clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */) - clientHash = hs.suite.mac(c.vers, clientMAC) - serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */) - serverHash = hs.suite.mac(c.vers, serverMAC) - } else { - clientCipher = hs.suite.aead(clientKey, clientIV) - serverCipher = hs.suite.aead(serverKey, serverIV) - } - - c.in.prepareCipherSpec(c.vers, clientCipher, clientHash) - c.out.prepareCipherSpec(c.vers, serverCipher, serverHash) - - return nil -} - -func (hs *serverHandshakeState) readFinished(out []byte) error { - c := hs.c - - if err := c.readChangeCipherSpec(); err != nil { - return err - } - - if hs.hello.nextProtoNeg { - msg, err := c.readHandshake() - if err != nil { - return err - } - nextProto, ok := msg.(*nextProtoMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(nextProto, msg) - } - hs.finishedHash.Write(nextProto.marshal()) - c.clientProtocol = nextProto.proto - } - - msg, err := c.readHandshake() - if err != nil { - return err - } - clientFinished, ok := msg.(*finishedMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(clientFinished, msg) - } - - verify := hs.finishedHash.clientSum(hs.masterSecret) - if len(verify) != len(clientFinished.verifyData) || - subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: client's Finished message is incorrect") - } - - hs.finishedHash.Write(clientFinished.marshal()) - copy(out, verify) - return nil -} - -func (hs *serverHandshakeState) sendSessionTicket() error { - if !hs.hello.ticketSupported { - return nil - } - - c := hs.c - m := new(newSessionTicketMsg) - - var certsFromClient [][]byte - for _, cert := range c.peerCertificates { - certsFromClient = append(certsFromClient, cert.Raw) - } - state := sessionState{ - vers: c.vers, - cipherSuite: hs.suite.id, - masterSecret: hs.masterSecret, - certificates: certsFromClient, - } - var err error - m.ticket, err = c.encryptTicket(state.marshal()) - if err != nil { - return err - } - - hs.finishedHash.Write(m.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil { - return err - } - - return nil -} - -func (hs *serverHandshakeState) sendFinished(out []byte) error { - c := hs.c - - if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil { - return err - } - - finished := new(finishedMsg) - finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret) - hs.finishedHash.Write(finished.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { - return err - } - - c.cipherSuite = hs.suite.id - copy(out, finished.verifyData) - - return nil -} - -// processCertsFromClient takes a chain of client certificates either from a -// Certificates message or from a sessionState and verifies them. It returns -// the public key of the leaf certificate. -func (c *Conn) processCertsFromClient(certificate Certificate) error { - certificates := certificate.Certificate - certs := make([]*x509.Certificate, len(certificates)) - var err error - for i, asn1Data := range certificates { - if certs[i], err = x509.ParseCertificate(asn1Data); err != nil { - c.sendAlert(alertBadCertificate) - return errors.New("tls: failed to parse client certificate: " + err.Error()) - } - } - - if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) { - c.sendAlert(alertBadCertificate) - return errors.New("tls: client didn't provide a certificate") - } - - if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 { - opts := x509.VerifyOptions{ - Roots: c.config.ClientCAs, - CurrentTime: c.config.time(), - Intermediates: x509.NewCertPool(), - KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, - } - - for _, cert := range certs[1:] { - opts.Intermediates.AddCert(cert) - } - - chains, err := certs[0].Verify(opts) - if err != nil { - c.sendAlert(alertBadCertificate) - return errors.New("tls: failed to verify client's certificate: " + err.Error()) - } - - c.verifiedChains = chains - } - - if c.config.VerifyPeerCertificate != nil { - if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil { - c.sendAlert(alertBadCertificate) - return err - } - } - - if len(certs) == 0 { - return nil - } - - switch certs[0].PublicKey.(type) { - case *ecdsa.PublicKey, *rsa.PublicKey: - default: - c.sendAlert(alertUnsupportedCertificate) - return fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey) - } - - c.peerCertificates = certs - c.ocspResponse = certificate.OCSPStaple - c.scts = certificate.SignedCertificateTimestamps - return nil -} - -// setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState -// suite if that cipher suite is acceptable to use. -// It returns a bool indicating if the suite was set. -func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool { - for _, supported := range supportedCipherSuites { - if id == supported { - candidate := cipherSuiteByID(id) - if candidate == nil { - continue - } - // Don't select a ciphersuite which we can't - // support for this client. - if candidate.flags&suiteECDHE != 0 { - if !hs.ellipticOk { - continue - } - if candidate.flags&suiteECDSA != 0 { - if !hs.ecdsaOk { - continue - } - } else if !hs.rsaSignOk { - continue - } - } else if !hs.rsaDecryptOk { - continue - } - if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 { - continue - } - hs.suite = candidate - return true - } - } - return false -} - -func clientHelloInfo(c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo { - supportedVersions := clientHello.supportedVersions - if len(clientHello.supportedVersions) == 0 { - supportedVersions = supportedVersionsFromMax(clientHello.vers) - } - - return &ClientHelloInfo{ - CipherSuites: clientHello.cipherSuites, - ServerName: clientHello.serverName, - SupportedCurves: clientHello.supportedCurves, - SupportedPoints: clientHello.supportedPoints, - SignatureSchemes: clientHello.supportedSignatureAlgorithms, - SupportedProtos: clientHello.alpnProtocols, - SupportedVersions: supportedVersions, - Conn: c.conn, - } -} diff --git a/vendor/github.com/marten-seemann/qtls/handshake_server_tls13.go b/vendor/github.com/marten-seemann/qtls/handshake_server_tls13.go deleted file mode 100644 index 97f15091fe..0000000000 --- a/vendor/github.com/marten-seemann/qtls/handshake_server_tls13.go +++ /dev/null @@ -1,872 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "bytes" - "crypto" - "crypto/hmac" - "crypto/rsa" - "errors" - "hash" - "io" - "sync/atomic" - "time" -) - -// maxClientPSKIdentities is the number of client PSK identities the server will -// attempt to validate. It will ignore the rest not to let cheap ClientHello -// messages cause too much work in session ticket decryption attempts. -const maxClientPSKIdentities = 5 - -type serverHandshakeStateTLS13 struct { - c *Conn - clientHello *clientHelloMsg - hello *serverHelloMsg - sentDummyCCS bool - usingPSK bool - suite *cipherSuiteTLS13 - cert *Certificate - sigAlg SignatureScheme - earlySecret []byte - sharedKey []byte - handshakeSecret []byte - masterSecret []byte - trafficSecret []byte // client_application_traffic_secret_0 - transcript hash.Hash - clientFinished []byte -} - -func (hs *serverHandshakeStateTLS13) handshake() error { - c := hs.c - - // For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2. - if err := hs.processClientHello(); err != nil { - return err - } - if err := hs.checkForResumption(); err != nil { - return err - } - if err := hs.pickCertificate(); err != nil { - return err - } - c.buffering = true - if err := hs.sendServerParameters(); err != nil { - return err - } - if err := hs.sendServerCertificate(); err != nil { - return err - } - if err := hs.sendServerFinished(); err != nil { - return err - } - // Note that at this point we could start sending application data without - // waiting for the client's second flight, but the application might not - // expect the lack of replay protection of the ClientHello parameters. - if _, err := c.flush(); err != nil { - return err - } - if err := hs.readClientCertificate(); err != nil { - return err - } - if err := hs.readClientFinished(); err != nil { - return err - } - - atomic.StoreUint32(&c.handshakeStatus, 1) - - return nil -} - -func (hs *serverHandshakeStateTLS13) processClientHello() error { - c := hs.c - - hs.hello = new(serverHelloMsg) - - // TLS 1.3 froze the ServerHello.legacy_version field, and uses - // supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1. - hs.hello.vers = VersionTLS12 - hs.hello.supportedVersion = c.vers - - if len(hs.clientHello.supportedVersions) == 0 { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: client used the legacy version field to negotiate TLS 1.3") - } - - // Abort if the client is doing a fallback and landing lower than what we - // support. See RFC 7507, which however does not specify the interaction - // with supported_versions. The only difference is that with - // supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4] - // handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case, - // it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to - // TLS 1.2, because a TLS 1.3 server would abort here. The situation before - // supported_versions was not better because there was just no way to do a - // TLS 1.4 handshake without risking the server selecting TLS 1.3. - for _, id := range hs.clientHello.cipherSuites { - if id == TLS_FALLBACK_SCSV { - // Use c.vers instead of max(supported_versions) because an attacker - // could defeat this by adding an arbitrary high version otherwise. - if c.vers < c.config.maxSupportedVersion(false) { - c.sendAlert(alertInappropriateFallback) - return errors.New("tls: client using inappropriate protocol fallback") - } - break - } - } - - if len(hs.clientHello.compressionMethods) != 1 || - hs.clientHello.compressionMethods[0] != compressionNone { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: TLS 1.3 client supports illegal compression methods") - } - - hs.hello.random = make([]byte, 32) - if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil { - c.sendAlert(alertInternalError) - return err - } - - if len(hs.clientHello.secureRenegotiation) != 0 { - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: initial handshake had non-empty renegotiation extension") - } - - if hs.clientHello.earlyData { - // See RFC 8446, Section 4.2.10 for the complicated behavior required - // here. The scenario is that a different server at our address offered - // to accept early data in the past, which we can't handle. For now, all - // 0-RTT enabled session tickets need to expire before a Go server can - // replace a server or join a pool. That's the same requirement that - // applies to mixing or replacing with any TLS 1.2 server. - c.sendAlert(alertUnsupportedExtension) - return errors.New("tls: client sent unexpected early data") - } - - hs.hello.sessionId = hs.clientHello.sessionId - hs.hello.compressionMethod = compressionNone - - var preferenceList, supportedList []uint16 - if c.config.PreferServerCipherSuites { - preferenceList = defaultCipherSuitesTLS13() - supportedList = hs.clientHello.cipherSuites - } else { - preferenceList = hs.clientHello.cipherSuites - supportedList = defaultCipherSuitesTLS13() - } - for _, suiteID := range preferenceList { - hs.suite = mutualCipherSuiteTLS13(supportedList, suiteID) - if hs.suite != nil { - break - } - } - if hs.suite == nil { - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: no cipher suite supported by both client and server") - } - c.cipherSuite = hs.suite.id - hs.hello.cipherSuite = hs.suite.id - hs.transcript = hs.suite.hash.New() - - // Pick the ECDHE group in server preference order, but give priority to - // groups with a key share, to avoid a HelloRetryRequest round-trip. - var selectedGroup CurveID - var clientKeyShare *keyShare -GroupSelection: - for _, preferredGroup := range c.config.curvePreferences() { - for _, ks := range hs.clientHello.keyShares { - if ks.group == preferredGroup { - selectedGroup = ks.group - clientKeyShare = &ks - break GroupSelection - } - } - if selectedGroup != 0 { - continue - } - for _, group := range hs.clientHello.supportedCurves { - if group == preferredGroup { - selectedGroup = group - break - } - } - } - if selectedGroup == 0 { - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: no ECDHE curve supported by both client and server") - } - if clientKeyShare == nil { - if err := hs.doHelloRetryRequest(selectedGroup); err != nil { - return err - } - clientKeyShare = &hs.clientHello.keyShares[0] - } - - if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok { - c.sendAlert(alertInternalError) - return errors.New("tls: CurvePreferences includes unsupported curve") - } - params, err := generateECDHEParameters(c.config.rand(), selectedGroup) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()} - hs.sharedKey = params.SharedKey(clientKeyShare.data) - if hs.sharedKey == nil { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: invalid client key share") - } - - c.serverName = hs.clientHello.serverName - - if c.config.ReceivedExtensions != nil { - c.config.ReceivedExtensions(typeClientHello, hs.clientHello.additionalExtensions) - } - - return nil -} - -func (hs *serverHandshakeStateTLS13) checkForResumption() error { - c := hs.c - - if c.config.SessionTicketsDisabled { - return nil - } - - modeOK := false - for _, mode := range hs.clientHello.pskModes { - if mode == pskModeDHE { - modeOK = true - break - } - } - if !modeOK { - return nil - } - - if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: invalid or missing PSK binders") - } - if len(hs.clientHello.pskIdentities) == 0 { - return nil - } - - for i, identity := range hs.clientHello.pskIdentities { - if i >= maxClientPSKIdentities { - break - } - - plaintext, _ := c.decryptTicket(identity.label) - if plaintext == nil { - continue - } - sessionState := new(sessionStateTLS13) - if ok := sessionState.unmarshal(plaintext); !ok { - continue - } - - createdAt := time.Unix(int64(sessionState.createdAt), 0) - if c.config.time().Sub(createdAt) > maxSessionTicketLifetime { - continue - } - - // We don't check the obfuscated ticket age because it's affected by - // clock skew and it's only a freshness signal useful for shrinking the - // window for replay attacks, which don't affect us as we don't do 0-RTT. - - pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite) - if pskSuite == nil || pskSuite.hash != hs.suite.hash { - continue - } - - // PSK connections don't re-establish client certificates, but carry - // them over in the session ticket. Ensure the presence of client certs - // in the ticket is consistent with the configured requirements. - sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0 - needClientCerts := requiresClientCert(c.config.ClientAuth) - if needClientCerts && !sessionHasClientCerts { - continue - } - if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { - continue - } - - psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption", - nil, hs.suite.hash.Size()) - hs.earlySecret = hs.suite.extract(psk, nil) - binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil) - // Clone the transcript in case a HelloRetryRequest was recorded. - transcript := cloneHash(hs.transcript, hs.suite.hash) - if transcript == nil { - c.sendAlert(alertInternalError) - return errors.New("tls: internal error: failed to clone hash") - } - transcript.Write(hs.clientHello.marshalWithoutBinders()) - pskBinder := hs.suite.finishedHash(binderKey, transcript) - if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) { - c.sendAlert(alertDecryptError) - return errors.New("tls: invalid PSK binder") - } - - if err := c.processCertsFromClient(sessionState.certificate); err != nil { - return err - } - - hs.hello.selectedIdentityPresent = true - hs.hello.selectedIdentity = uint16(i) - hs.usingPSK = true - c.didResume = true - return nil - } - - return nil -} - -// cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler -// interfaces implemented by standard library hashes to clone the state of in -// to a new instance of h. It returns nil if the operation fails. -func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash { - // Recreate the interface to avoid importing encoding. - type binaryMarshaler interface { - MarshalBinary() (data []byte, err error) - UnmarshalBinary(data []byte) error - } - marshaler, ok := in.(binaryMarshaler) - if !ok { - return nil - } - state, err := marshaler.MarshalBinary() - if err != nil { - return nil - } - out := h.New() - unmarshaler, ok := out.(binaryMarshaler) - if !ok { - return nil - } - if err := unmarshaler.UnmarshalBinary(state); err != nil { - return nil - } - return out -} - -func (hs *serverHandshakeStateTLS13) pickCertificate() error { - c := hs.c - - // Only one of PSK and certificates are used at a time. - if hs.usingPSK { - return nil - } - - // This implements a very simplistic certificate selection strategy for now: - // getCertificate delegates to the application Config.GetCertificate, or - // selects based on the server_name only. If the selected certificate's - // public key does not match the client signature_algorithms, the handshake - // is aborted. No attention is given to signature_algorithms_cert, and it is - // not passed to the application Config.GetCertificate. This will need to - // improve according to RFC 8446, sections 4.4.2.2 and 4.2.3. - certificate, err := c.config.getCertificate(clientHelloInfo(c, hs.clientHello)) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - supportedAlgs := signatureSchemesForCertificate(c.vers, certificate) - if supportedAlgs == nil { - c.sendAlert(alertInternalError) - return unsupportedCertificateError(certificate) - } - // Pick signature scheme in client preference order, as the server - // preference order is not configurable. - for _, preferredAlg := range hs.clientHello.supportedSignatureAlgorithms { - if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) { - hs.sigAlg = preferredAlg - break - } - } - if hs.sigAlg == 0 { - // getCertificate returned a certificate incompatible with the - // ClientHello supported signature algorithms. - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: client doesn't support selected certificate") - } - hs.cert = certificate - - return nil -} - -// sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility -// with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. -func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error { - if hs.sentDummyCCS { - return nil - } - hs.sentDummyCCS = true - - _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) - return err -} - -func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error { - c := hs.c - - // The first ClientHello gets double-hashed into the transcript upon a - // HelloRetryRequest. See RFC 8446, Section 4.4.1. - hs.transcript.Write(hs.clientHello.marshal()) - chHash := hs.transcript.Sum(nil) - hs.transcript.Reset() - hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) - hs.transcript.Write(chHash) - - helloRetryRequest := &serverHelloMsg{ - vers: hs.hello.vers, - random: helloRetryRequestRandom, - sessionId: hs.hello.sessionId, - cipherSuite: hs.hello.cipherSuite, - compressionMethod: hs.hello.compressionMethod, - supportedVersion: hs.hello.supportedVersion, - selectedGroup: selectedGroup, - } - - hs.transcript.Write(helloRetryRequest.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil { - return err - } - - if err := hs.sendDummyChangeCipherSpec(); err != nil { - return err - } - - msg, err := c.readHandshake() - if err != nil { - return err - } - - clientHello, ok := msg.(*clientHelloMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(clientHello, msg) - } - - if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: client sent invalid key share in second ClientHello") - } - - if clientHello.earlyData { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: client indicated early data in second ClientHello") - } - - if illegalClientHelloChange(clientHello, hs.clientHello) { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: client illegally modified second ClientHello") - } - - hs.clientHello = clientHello - return nil -} - -// illegalClientHelloChange reports whether the two ClientHello messages are -// different, with the exception of the changes allowed before and after a -// HelloRetryRequest. See RFC 8446, Section 4.1.2. -func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool { - if len(ch.supportedVersions) != len(ch1.supportedVersions) || - len(ch.cipherSuites) != len(ch1.cipherSuites) || - len(ch.supportedCurves) != len(ch1.supportedCurves) || - len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) || - len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) || - len(ch.alpnProtocols) != len(ch1.alpnProtocols) { - return true - } - for i := range ch.supportedVersions { - if ch.supportedVersions[i] != ch1.supportedVersions[i] { - return true - } - } - for i := range ch.cipherSuites { - if ch.cipherSuites[i] != ch1.cipherSuites[i] { - return true - } - } - for i := range ch.supportedCurves { - if ch.supportedCurves[i] != ch1.supportedCurves[i] { - return true - } - } - for i := range ch.supportedSignatureAlgorithms { - if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] { - return true - } - } - for i := range ch.supportedSignatureAlgorithmsCert { - if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] { - return true - } - } - for i := range ch.alpnProtocols { - if ch.alpnProtocols[i] != ch1.alpnProtocols[i] { - return true - } - } - return ch.vers != ch1.vers || - !bytes.Equal(ch.random, ch1.random) || - !bytes.Equal(ch.sessionId, ch1.sessionId) || - !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) || - ch.nextProtoNeg != ch1.nextProtoNeg || - ch.serverName != ch1.serverName || - ch.ocspStapling != ch1.ocspStapling || - !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) || - ch.ticketSupported != ch1.ticketSupported || - !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) || - ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported || - !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) || - ch.scts != ch1.scts || - !bytes.Equal(ch.cookie, ch1.cookie) || - !bytes.Equal(ch.pskModes, ch1.pskModes) -} - -func (hs *serverHandshakeStateTLS13) sendServerParameters() error { - c := hs.c - - hs.transcript.Write(hs.clientHello.marshal()) - hs.transcript.Write(hs.hello.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { - return err - } - - if err := hs.sendDummyChangeCipherSpec(); err != nil { - return err - } - - earlySecret := hs.earlySecret - if earlySecret == nil { - earlySecret = hs.suite.extract(nil, nil) - } - hs.handshakeSecret = hs.suite.extract(hs.sharedKey, - hs.suite.deriveSecret(earlySecret, "derived", nil)) - - clientSecret := hs.suite.deriveSecret(hs.handshakeSecret, - clientHandshakeTrafficLabel, hs.transcript) - c.in.exportKey(hs.suite, clientSecret) - c.in.setTrafficSecret(hs.suite, clientSecret) - serverSecret := hs.suite.deriveSecret(hs.handshakeSecret, - serverHandshakeTrafficLabel, hs.transcript) - c.out.exportKey(hs.suite, serverSecret) - c.out.setTrafficSecret(hs.suite, serverSecret) - - err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - - encryptedExtensions := new(encryptedExtensionsMsg) - - if len(hs.clientHello.alpnProtocols) > 0 { - if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback { - encryptedExtensions.alpnProtocol = selectedProto - c.clientProtocol = selectedProto - } - } - if hs.c.config.GetExtensions != nil { - encryptedExtensions.additionalExtensions = hs.c.config.GetExtensions(typeEncryptedExtensions) - } - - hs.transcript.Write(encryptedExtensions.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil { - return err - } - - return nil -} - -func (hs *serverHandshakeStateTLS13) requestClientCert() bool { - return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK -} - -func (hs *serverHandshakeStateTLS13) sendServerCertificate() error { - c := hs.c - - // Only one of PSK and certificates are used at a time. - if hs.usingPSK { - return nil - } - - if hs.requestClientCert() { - // Request a client certificate - certReq := new(certificateRequestMsgTLS13) - certReq.ocspStapling = true - certReq.scts = true - certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms - if c.config.ClientCAs != nil { - certReq.certificateAuthorities = c.config.ClientCAs.Subjects() - } - - hs.transcript.Write(certReq.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil { - return err - } - } - - certMsg := new(certificateMsgTLS13) - - certMsg.certificate = *hs.cert - certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0 - certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 - - hs.transcript.Write(certMsg.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { - return err - } - - certVerifyMsg := new(certificateVerifyMsg) - certVerifyMsg.hasSignatureAlgorithm = true - certVerifyMsg.signatureAlgorithm = hs.sigAlg - - sigType := signatureFromSignatureScheme(hs.sigAlg) - sigHash, err := hashFromSignatureScheme(hs.sigAlg) - if sigType == 0 || err != nil { - return c.sendAlert(alertInternalError) - } - h := sigHash.New() - writeSignedMessage(h, serverSignatureContext, hs.transcript) - - signOpts := crypto.SignerOpts(sigHash) - if sigType == signatureRSAPSS { - signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} - } - sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), h.Sum(nil), signOpts) - if err != nil { - public := hs.cert.PrivateKey.(crypto.Signer).Public() - if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS && - rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS - c.sendAlert(alertHandshakeFailure) - } else { - c.sendAlert(alertInternalError) - } - return errors.New("tls: failed to sign handshake: " + err.Error()) - } - certVerifyMsg.signature = sig - - hs.transcript.Write(certVerifyMsg.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil { - return err - } - - return nil -} - -func (hs *serverHandshakeStateTLS13) sendServerFinished() error { - c := hs.c - - finished := &finishedMsg{ - verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), - } - - hs.transcript.Write(finished.marshal()) - if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { - return err - } - - // Derive secrets that take context through the server Finished. - - hs.masterSecret = hs.suite.extract(nil, - hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil)) - - hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, - clientApplicationTrafficLabel, hs.transcript) - serverSecret := hs.suite.deriveSecret(hs.masterSecret, - serverApplicationTrafficLabel, hs.transcript) - c.out.exportKey(hs.suite, serverSecret) - c.out.setTrafficSecret(hs.suite, serverSecret) - - err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - - c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) - - // If we did not request client certificates, at this point we can - // precompute the client finished and roll the transcript forward to send - // session tickets in our first flight. - if !hs.requestClientCert() { - if err := hs.sendSessionTickets(); err != nil { - return err - } - } - - return nil -} - -func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool { - if hs.c.config.SessionTicketsDisabled { - return false - } - - // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9. - for _, pskMode := range hs.clientHello.pskModes { - if pskMode == pskModeDHE { - return true - } - } - return false -} - -func (hs *serverHandshakeStateTLS13) sendSessionTickets() error { - c := hs.c - - hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) - finishedMsg := &finishedMsg{ - verifyData: hs.clientFinished, - } - hs.transcript.Write(finishedMsg.marshal()) - - if !hs.shouldSendSessionTickets() { - return nil - } - - resumptionSecret := hs.suite.deriveSecret(hs.masterSecret, - resumptionLabel, hs.transcript) - - m := new(newSessionTicketMsgTLS13) - - var certsFromClient [][]byte - for _, cert := range c.peerCertificates { - certsFromClient = append(certsFromClient, cert.Raw) - } - state := sessionStateTLS13{ - cipherSuite: hs.suite.id, - createdAt: uint64(c.config.time().Unix()), - resumptionSecret: resumptionSecret, - certificate: Certificate{ - Certificate: certsFromClient, - OCSPStaple: c.ocspResponse, - SignedCertificateTimestamps: c.scts, - }, - } - var err error - m.label, err = c.encryptTicket(state.marshal()) - if err != nil { - return err - } - m.lifetime = uint32(maxSessionTicketLifetime / time.Second) - - if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil { - return err - } - - return nil -} - -func (hs *serverHandshakeStateTLS13) readClientCertificate() error { - c := hs.c - - if !hs.requestClientCert() { - return nil - } - - // If we requested a client certificate, then the client must send a - // certificate message. If it's empty, no CertificateVerify is sent. - - msg, err := c.readHandshake() - if err != nil { - return err - } - - certMsg, ok := msg.(*certificateMsgTLS13) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(certMsg, msg) - } - hs.transcript.Write(certMsg.marshal()) - - if err := c.processCertsFromClient(certMsg.certificate); err != nil { - return err - } - - if len(certMsg.certificate.Certificate) != 0 { - msg, err = c.readHandshake() - if err != nil { - return err - } - - certVerify, ok := msg.(*certificateVerifyMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(certVerify, msg) - } - - // See RFC 8446, Section 4.4.3. - if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: invalid certificate signature algorithm") - } - sigType := signatureFromSignatureScheme(certVerify.signatureAlgorithm) - sigHash, err := hashFromSignatureScheme(certVerify.signatureAlgorithm) - if sigType == 0 || err != nil { - c.sendAlert(alertInternalError) - return err - } - if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { - c.sendAlert(alertIllegalParameter) - return errors.New("tls: invalid certificate signature algorithm") - } - h := sigHash.New() - writeSignedMessage(h, clientSignatureContext, hs.transcript) - if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, - sigHash, h.Sum(nil), certVerify.signature); err != nil { - c.sendAlert(alertDecryptError) - return errors.New("tls: invalid certificate signature") - } - - hs.transcript.Write(certVerify.marshal()) - } - - // If we waited until the client certificates to send session tickets, we - // are ready to do it now. - if err := hs.sendSessionTickets(); err != nil { - return err - } - - return nil -} - -func (hs *serverHandshakeStateTLS13) readClientFinished() error { - c := hs.c - - msg, err := c.readHandshake() - if err != nil { - return err - } - - finished, ok := msg.(*finishedMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(finished, msg) - } - - if !hmac.Equal(hs.clientFinished, finished.verifyData) { - c.sendAlert(alertDecryptError) - return errors.New("tls: invalid client finished hash") - } - - c.in.exportKey(hs.suite, hs.trafficSecret) - c.in.setTrafficSecret(hs.suite, hs.trafficSecret) - - return nil -} diff --git a/vendor/github.com/marten-seemann/qtls/key_agreement.go b/vendor/github.com/marten-seemann/qtls/key_agreement.go deleted file mode 100644 index 477aae4a40..0000000000 --- a/vendor/github.com/marten-seemann/qtls/key_agreement.go +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "crypto" - "crypto/md5" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "errors" - "io" -) - -var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message") -var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message") - -// rsaKeyAgreement implements the standard TLS key agreement where the client -// encrypts the pre-master secret to the server's public key. -type rsaKeyAgreement struct{} - -func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) { - return nil, nil -} - -func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) { - if len(ckx.ciphertext) < 2 { - return nil, errClientKeyExchange - } - - ciphertext := ckx.ciphertext - if version != VersionSSL30 { - ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1]) - if ciphertextLen != len(ckx.ciphertext)-2 { - return nil, errClientKeyExchange - } - ciphertext = ckx.ciphertext[2:] - } - priv, ok := cert.PrivateKey.(crypto.Decrypter) - if !ok { - return nil, errors.New("tls: certificate private key does not implement crypto.Decrypter") - } - // Perform constant time RSA PKCS#1 v1.5 decryption - preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48}) - if err != nil { - return nil, err - } - // We don't check the version number in the premaster secret. For one, - // by checking it, we would leak information about the validity of the - // encrypted pre-master secret. Secondly, it provides only a small - // benefit against a downgrade attack and some implementations send the - // wrong version anyway. See the discussion at the end of section - // 7.4.7.1 of RFC 4346. - return preMasterSecret, nil -} - -func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { - return errors.New("tls: unexpected ServerKeyExchange") -} - -func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { - preMasterSecret := make([]byte, 48) - preMasterSecret[0] = byte(clientHello.vers >> 8) - preMasterSecret[1] = byte(clientHello.vers) - _, err := io.ReadFull(config.rand(), preMasterSecret[2:]) - if err != nil { - return nil, nil, err - } - - encrypted, err := rsa.EncryptPKCS1v15(config.rand(), cert.PublicKey.(*rsa.PublicKey), preMasterSecret) - if err != nil { - return nil, nil, err - } - ckx := new(clientKeyExchangeMsg) - ckx.ciphertext = make([]byte, len(encrypted)+2) - ckx.ciphertext[0] = byte(len(encrypted) >> 8) - ckx.ciphertext[1] = byte(len(encrypted)) - copy(ckx.ciphertext[2:], encrypted) - return preMasterSecret, ckx, nil -} - -// sha1Hash calculates a SHA1 hash over the given byte slices. -func sha1Hash(slices [][]byte) []byte { - hsha1 := sha1.New() - for _, slice := range slices { - hsha1.Write(slice) - } - return hsha1.Sum(nil) -} - -// md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the -// concatenation of an MD5 and SHA1 hash. -func md5SHA1Hash(slices [][]byte) []byte { - md5sha1 := make([]byte, md5.Size+sha1.Size) - hmd5 := md5.New() - for _, slice := range slices { - hmd5.Write(slice) - } - copy(md5sha1, hmd5.Sum(nil)) - copy(md5sha1[md5.Size:], sha1Hash(slices)) - return md5sha1 -} - -// hashForServerKeyExchange hashes the given slices and returns their digest -// using the given hash function (for >= TLS 1.2) or using a default based on -// the sigType (for earlier TLS versions). -func hashForServerKeyExchange(sigType uint8, hashFunc crypto.Hash, version uint16, slices ...[]byte) ([]byte, error) { - if version >= VersionTLS12 { - h := hashFunc.New() - for _, slice := range slices { - h.Write(slice) - } - digest := h.Sum(nil) - return digest, nil - } - if sigType == signatureECDSA { - return sha1Hash(slices), nil - } - return md5SHA1Hash(slices), nil -} - -// ecdheKeyAgreement implements a TLS key agreement where the server -// generates an ephemeral EC public/private key pair and signs it. The -// pre-master secret is then calculated using ECDH. The signature may -// either be ECDSA or RSA. -type ecdheKeyAgreement struct { - version uint16 - isRSA bool - params ecdheParameters - - // ckx and preMasterSecret are generated in processServerKeyExchange - // and returned in generateClientKeyExchange. - ckx *clientKeyExchangeMsg - preMasterSecret []byte -} - -func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) { - preferredCurves := config.curvePreferences() - - var curveID CurveID -NextCandidate: - for _, candidate := range preferredCurves { - for _, c := range clientHello.supportedCurves { - if candidate == c { - curveID = c - break NextCandidate - } - } - } - - if curveID == 0 { - return nil, errors.New("tls: no supported elliptic curves offered") - } - if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { - return nil, errors.New("tls: CurvePreferences includes unsupported curve") - } - - params, err := generateECDHEParameters(config.rand(), curveID) - if err != nil { - return nil, err - } - ka.params = params - - // See RFC 4492, Section 5.4. - ecdhePublic := params.PublicKey() - serverECDHParams := make([]byte, 1+2+1+len(ecdhePublic)) - serverECDHParams[0] = 3 // named curve - serverECDHParams[1] = byte(curveID >> 8) - serverECDHParams[2] = byte(curveID) - serverECDHParams[3] = byte(len(ecdhePublic)) - copy(serverECDHParams[4:], ecdhePublic) - - priv, ok := cert.PrivateKey.(crypto.Signer) - if !ok { - return nil, errors.New("tls: certificate private key does not implement crypto.Signer") - } - - signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(priv.Public(), clientHello.supportedSignatureAlgorithms, supportedSignatureAlgorithmsTLS12, ka.version) - if err != nil { - return nil, err - } - if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA { - return nil, errors.New("tls: certificate cannot be used with the selected cipher suite") - } - - digest, err := hashForServerKeyExchange(sigType, hashFunc, ka.version, clientHello.random, hello.random, serverECDHParams) - if err != nil { - return nil, err - } - - signOpts := crypto.SignerOpts(hashFunc) - if sigType == signatureRSAPSS { - signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc} - } - sig, err := priv.Sign(config.rand(), digest, signOpts) - if err != nil { - return nil, errors.New("tls: failed to sign ECDHE parameters: " + err.Error()) - } - - skx := new(serverKeyExchangeMsg) - sigAndHashLen := 0 - if ka.version >= VersionTLS12 { - sigAndHashLen = 2 - } - skx.key = make([]byte, len(serverECDHParams)+sigAndHashLen+2+len(sig)) - copy(skx.key, serverECDHParams) - k := skx.key[len(serverECDHParams):] - if ka.version >= VersionTLS12 { - k[0] = byte(signatureAlgorithm >> 8) - k[1] = byte(signatureAlgorithm) - k = k[2:] - } - k[0] = byte(len(sig) >> 8) - k[1] = byte(len(sig)) - copy(k[2:], sig) - - return skx, nil -} - -func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) { - if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 { - return nil, errClientKeyExchange - } - - preMasterSecret := ka.params.SharedKey(ckx.ciphertext[1:]) - if preMasterSecret == nil { - return nil, errClientKeyExchange - } - - return preMasterSecret, nil -} - -func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { - if len(skx.key) < 4 { - return errServerKeyExchange - } - if skx.key[0] != 3 { // named curve - return errors.New("tls: server selected unsupported curve") - } - curveID := CurveID(skx.key[1])<<8 | CurveID(skx.key[2]) - - publicLen := int(skx.key[3]) - if publicLen+4 > len(skx.key) { - return errServerKeyExchange - } - serverECDHParams := skx.key[:4+publicLen] - publicKey := serverECDHParams[4:] - - sig := skx.key[4+publicLen:] - if len(sig) < 2 { - return errServerKeyExchange - } - - if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { - return errors.New("tls: server selected unsupported curve") - } - - params, err := generateECDHEParameters(config.rand(), curveID) - if err != nil { - return err - } - ka.params = params - - ka.preMasterSecret = params.SharedKey(publicKey) - if ka.preMasterSecret == nil { - return errServerKeyExchange - } - - ourPublicKey := params.PublicKey() - ka.ckx = new(clientKeyExchangeMsg) - ka.ckx.ciphertext = make([]byte, 1+len(ourPublicKey)) - ka.ckx.ciphertext[0] = byte(len(ourPublicKey)) - copy(ka.ckx.ciphertext[1:], ourPublicKey) - - var signatureAlgorithm SignatureScheme - if ka.version >= VersionTLS12 { - // handle SignatureAndHashAlgorithm - signatureAlgorithm = SignatureScheme(sig[0])<<8 | SignatureScheme(sig[1]) - sig = sig[2:] - if len(sig) < 2 { - return errServerKeyExchange - } - } - _, sigType, hashFunc, err := pickSignatureAlgorithm(cert.PublicKey, []SignatureScheme{signatureAlgorithm}, clientHello.supportedSignatureAlgorithms, ka.version) - if err != nil { - return err - } - if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA { - return errServerKeyExchange - } - - sigLen := int(sig[0])<<8 | int(sig[1]) - if sigLen+2 != len(sig) { - return errServerKeyExchange - } - sig = sig[2:] - - digest, err := hashForServerKeyExchange(sigType, hashFunc, ka.version, clientHello.random, serverHello.random, serverECDHParams) - if err != nil { - return err - } - return verifyHandshakeSignature(sigType, cert.PublicKey, hashFunc, digest, sig) -} - -func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { - if ka.ckx == nil { - return nil, nil, errors.New("tls: missing ServerKeyExchange message") - } - - return ka.preMasterSecret, ka.ckx, nil -} diff --git a/vendor/github.com/marten-seemann/qtls/key_schedule.go b/vendor/github.com/marten-seemann/qtls/key_schedule.go deleted file mode 100644 index 24bae2e68e..0000000000 --- a/vendor/github.com/marten-seemann/qtls/key_schedule.go +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "crypto" - "crypto/elliptic" - "crypto/hmac" - "errors" - "hash" - "io" - "math/big" - - "golang.org/x/crypto/cryptobyte" - "golang.org/x/crypto/curve25519" - "golang.org/x/crypto/hkdf" -) - -// This file contains the functions necessary to compute the TLS 1.3 key -// schedule. See RFC 8446, Section 7. - -const ( - resumptionBinderLabel = "res binder" - clientHandshakeTrafficLabel = "c hs traffic" - serverHandshakeTrafficLabel = "s hs traffic" - clientApplicationTrafficLabel = "c ap traffic" - serverApplicationTrafficLabel = "s ap traffic" - exporterLabel = "exp master" - resumptionLabel = "res master" - trafficUpdateLabel = "traffic upd" -) - -// HkdfExtract generates a pseudorandom key for use with Expand from an input secret and an optional independent salt. -func HkdfExtract(hash crypto.Hash, newSecret, currentSecret []byte) []byte { - if newSecret == nil { - newSecret = make([]byte, hash.Size()) - } - return hkdf.Extract(hash.New, newSecret, currentSecret) -} - -// HkdfExpandLabel HKDF expands a label -func HkdfExpandLabel(hash crypto.Hash, secret, hashValue []byte, label string, L int) []byte { - return hkdfExpandLabel(hash, secret, hashValue, label, L) -} - -func hkdfExpandLabel(hash crypto.Hash, secret, context []byte, label string, length int) []byte { - var hkdfLabel cryptobyte.Builder - hkdfLabel.AddUint16(uint16(length)) - hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes([]byte("tls13 ")) - b.AddBytes([]byte(label)) - }) - hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(context) - }) - out := make([]byte, length) - n, err := hkdf.Expand(hash.New, secret, hkdfLabel.BytesOrPanic()).Read(out) - if err != nil || n != length { - panic("tls: HKDF-Expand-Label invocation failed unexpectedly") - } - return out -} - -// expandLabel implements HKDF-Expand-Label from RFC 8446, Section 7.1. -func (c *cipherSuiteTLS13) expandLabel(secret []byte, label string, context []byte, length int) []byte { - return hkdfExpandLabel(c.hash, secret, context, label, length) -} - -// deriveSecret implements Derive-Secret from RFC 8446, Section 7.1. -func (c *cipherSuiteTLS13) deriveSecret(secret []byte, label string, transcript hash.Hash) []byte { - if transcript == nil { - transcript = c.hash.New() - } - return c.expandLabel(secret, label, transcript.Sum(nil), c.hash.Size()) -} - -// extract implements HKDF-Extract with the cipher suite hash. -func (c *cipherSuiteTLS13) extract(newSecret, currentSecret []byte) []byte { - return HkdfExtract(c.hash, newSecret, currentSecret) -} - -// nextTrafficSecret generates the next traffic secret, given the current one, -// according to RFC 8446, Section 7.2. -func (c *cipherSuiteTLS13) nextTrafficSecret(trafficSecret []byte) []byte { - return c.expandLabel(trafficSecret, trafficUpdateLabel, nil, c.hash.Size()) -} - -// trafficKey generates traffic keys according to RFC 8446, Section 7.3. -func (c *cipherSuiteTLS13) trafficKey(trafficSecret []byte) (key, iv []byte) { - key = c.expandLabel(trafficSecret, "key", nil, c.keyLen) - iv = c.expandLabel(trafficSecret, "iv", nil, aeadNonceLength) - return -} - -// finishedHash generates the Finished verify_data or PskBinderEntry according -// to RFC 8446, Section 4.4.4. See sections 4.4 and 4.2.11.2 for the baseKey -// selection. -func (c *cipherSuiteTLS13) finishedHash(baseKey []byte, transcript hash.Hash) []byte { - finishedKey := c.expandLabel(baseKey, "finished", nil, c.hash.Size()) - verifyData := hmac.New(c.hash.New, finishedKey) - verifyData.Write(transcript.Sum(nil)) - return verifyData.Sum(nil) -} - -// exportKeyingMaterial implements RFC5705 exporters for TLS 1.3 according to -// RFC 8446, Section 7.5. -func (c *cipherSuiteTLS13) exportKeyingMaterial(masterSecret []byte, transcript hash.Hash) func(string, []byte, int) ([]byte, error) { - expMasterSecret := c.deriveSecret(masterSecret, exporterLabel, transcript) - return func(label string, context []byte, length int) ([]byte, error) { - secret := c.deriveSecret(expMasterSecret, label, nil) - h := c.hash.New() - h.Write(context) - return c.expandLabel(secret, "exporter", h.Sum(nil), length), nil - } -} - -// ecdheParameters implements Diffie-Hellman with either NIST curves or X25519, -// according to RFC 8446, Section 4.2.8.2. -type ecdheParameters interface { - CurveID() CurveID - PublicKey() []byte - SharedKey(peerPublicKey []byte) []byte -} - -func generateECDHEParameters(rand io.Reader, curveID CurveID) (ecdheParameters, error) { - if curveID == X25519 { - p := &x25519Parameters{} - if _, err := io.ReadFull(rand, p.privateKey[:]); err != nil { - return nil, err - } - curve25519.ScalarBaseMult(&p.publicKey, &p.privateKey) - return p, nil - } - - curve, ok := curveForCurveID(curveID) - if !ok { - return nil, errors.New("tls: internal error: unsupported curve") - } - - p := &nistParameters{curveID: curveID} - var err error - p.privateKey, p.x, p.y, err = elliptic.GenerateKey(curve, rand) - if err != nil { - return nil, err - } - return p, nil -} - -func curveForCurveID(id CurveID) (elliptic.Curve, bool) { - switch id { - case CurveP256: - return elliptic.P256(), true - case CurveP384: - return elliptic.P384(), true - case CurveP521: - return elliptic.P521(), true - default: - return nil, false - } -} - -type nistParameters struct { - privateKey []byte - x, y *big.Int // public key - curveID CurveID -} - -func (p *nistParameters) CurveID() CurveID { - return p.curveID -} - -func (p *nistParameters) PublicKey() []byte { - curve, _ := curveForCurveID(p.curveID) - return elliptic.Marshal(curve, p.x, p.y) -} - -func (p *nistParameters) SharedKey(peerPublicKey []byte) []byte { - curve, _ := curveForCurveID(p.curveID) - // Unmarshal also checks whether the given point is on the curve. - x, y := elliptic.Unmarshal(curve, peerPublicKey) - if x == nil { - return nil - } - - xShared, _ := curve.ScalarMult(x, y, p.privateKey) - sharedKey := make([]byte, (curve.Params().BitSize+7)>>3) - xBytes := xShared.Bytes() - copy(sharedKey[len(sharedKey)-len(xBytes):], xBytes) - - return sharedKey -} - -type x25519Parameters struct { - privateKey [32]byte - publicKey [32]byte -} - -func (p *x25519Parameters) CurveID() CurveID { - return X25519 -} - -func (p *x25519Parameters) PublicKey() []byte { - return p.publicKey[:] -} - -func (p *x25519Parameters) SharedKey(peerPublicKey []byte) []byte { - if len(peerPublicKey) != 32 { - return nil - } - var theirPublicKey, sharedKey [32]byte - copy(theirPublicKey[:], peerPublicKey) - curve25519.ScalarMult(&sharedKey, &p.privateKey, &theirPublicKey) - return sharedKey[:] -} diff --git a/vendor/github.com/marten-seemann/qtls/prf.go b/vendor/github.com/marten-seemann/qtls/prf.go deleted file mode 100644 index a973d6ad4d..0000000000 --- a/vendor/github.com/marten-seemann/qtls/prf.go +++ /dev/null @@ -1,385 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "crypto" - "crypto/hmac" - "crypto/md5" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "errors" - "fmt" - "hash" -) - -// Split a premaster secret in two as specified in RFC 4346, Section 5. -func splitPreMasterSecret(secret []byte) (s1, s2 []byte) { - s1 = secret[0 : (len(secret)+1)/2] - s2 = secret[len(secret)/2:] - return -} - -// pHash implements the P_hash function, as defined in RFC 4346, Section 5. -func pHash(result, secret, seed []byte, hash func() hash.Hash) { - h := hmac.New(hash, secret) - h.Write(seed) - a := h.Sum(nil) - - j := 0 - for j < len(result) { - h.Reset() - h.Write(a) - h.Write(seed) - b := h.Sum(nil) - copy(result[j:], b) - j += len(b) - - h.Reset() - h.Write(a) - a = h.Sum(nil) - } -} - -// prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246, Section 5. -func prf10(result, secret, label, seed []byte) { - hashSHA1 := sha1.New - hashMD5 := md5.New - - labelAndSeed := make([]byte, len(label)+len(seed)) - copy(labelAndSeed, label) - copy(labelAndSeed[len(label):], seed) - - s1, s2 := splitPreMasterSecret(secret) - pHash(result, s1, labelAndSeed, hashMD5) - result2 := make([]byte, len(result)) - pHash(result2, s2, labelAndSeed, hashSHA1) - - for i, b := range result2 { - result[i] ^= b - } -} - -// prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246, Section 5. -func prf12(hashFunc func() hash.Hash) func(result, secret, label, seed []byte) { - return func(result, secret, label, seed []byte) { - labelAndSeed := make([]byte, len(label)+len(seed)) - copy(labelAndSeed, label) - copy(labelAndSeed[len(label):], seed) - - pHash(result, secret, labelAndSeed, hashFunc) - } -} - -// prf30 implements the SSL 3.0 pseudo-random function, as defined in -// www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt section 6. -func prf30(result, secret, label, seed []byte) { - hashSHA1 := sha1.New() - hashMD5 := md5.New() - - done := 0 - i := 0 - // RFC 5246 section 6.3 says that the largest PRF output needed is 128 - // bytes. Since no more ciphersuites will be added to SSLv3, this will - // remain true. Each iteration gives us 16 bytes so 10 iterations will - // be sufficient. - var b [11]byte - for done < len(result) { - for j := 0; j <= i; j++ { - b[j] = 'A' + byte(i) - } - - hashSHA1.Reset() - hashSHA1.Write(b[:i+1]) - hashSHA1.Write(secret) - hashSHA1.Write(seed) - digest := hashSHA1.Sum(nil) - - hashMD5.Reset() - hashMD5.Write(secret) - hashMD5.Write(digest) - - done += copy(result[done:], hashMD5.Sum(nil)) - i++ - } -} - -const ( - masterSecretLength = 48 // Length of a master secret in TLS 1.1. - finishedVerifyLength = 12 // Length of verify_data in a Finished message. -) - -var masterSecretLabel = []byte("master secret") -var keyExpansionLabel = []byte("key expansion") -var clientFinishedLabel = []byte("client finished") -var serverFinishedLabel = []byte("server finished") - -func prfAndHashForVersion(version uint16, suite *cipherSuite) (func(result, secret, label, seed []byte), crypto.Hash) { - switch version { - case VersionSSL30: - return prf30, crypto.Hash(0) - case VersionTLS10, VersionTLS11: - return prf10, crypto.Hash(0) - case VersionTLS12: - if suite.flags&suiteSHA384 != 0 { - return prf12(sha512.New384), crypto.SHA384 - } - return prf12(sha256.New), crypto.SHA256 - default: - panic("unknown version") - } -} - -func prfForVersion(version uint16, suite *cipherSuite) func(result, secret, label, seed []byte) { - prf, _ := prfAndHashForVersion(version, suite) - return prf -} - -// masterFromPreMasterSecret generates the master secret from the pre-master -// secret. See RFC 5246, Section 8.1. -func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, clientRandom, serverRandom []byte) []byte { - seed := make([]byte, 0, len(clientRandom)+len(serverRandom)) - seed = append(seed, clientRandom...) - seed = append(seed, serverRandom...) - - masterSecret := make([]byte, masterSecretLength) - prfForVersion(version, suite)(masterSecret, preMasterSecret, masterSecretLabel, seed) - return masterSecret -} - -// keysFromMasterSecret generates the connection keys from the master -// secret, given the lengths of the MAC key, cipher key and IV, as defined in -// RFC 2246, Section 6.3. -func keysFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte, macLen, keyLen, ivLen int) (clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV []byte) { - seed := make([]byte, 0, len(serverRandom)+len(clientRandom)) - seed = append(seed, serverRandom...) - seed = append(seed, clientRandom...) - - n := 2*macLen + 2*keyLen + 2*ivLen - keyMaterial := make([]byte, n) - prfForVersion(version, suite)(keyMaterial, masterSecret, keyExpansionLabel, seed) - clientMAC = keyMaterial[:macLen] - keyMaterial = keyMaterial[macLen:] - serverMAC = keyMaterial[:macLen] - keyMaterial = keyMaterial[macLen:] - clientKey = keyMaterial[:keyLen] - keyMaterial = keyMaterial[keyLen:] - serverKey = keyMaterial[:keyLen] - keyMaterial = keyMaterial[keyLen:] - clientIV = keyMaterial[:ivLen] - keyMaterial = keyMaterial[ivLen:] - serverIV = keyMaterial[:ivLen] - return -} - -// hashFromSignatureScheme returns the corresponding crypto.Hash for a given -// hash from a TLS SignatureScheme. -func hashFromSignatureScheme(signatureAlgorithm SignatureScheme) (crypto.Hash, error) { - switch signatureAlgorithm { - case PKCS1WithSHA1, ECDSAWithSHA1: - return crypto.SHA1, nil - case PKCS1WithSHA256, PSSWithSHA256, ECDSAWithP256AndSHA256: - return crypto.SHA256, nil - case PKCS1WithSHA384, PSSWithSHA384, ECDSAWithP384AndSHA384: - return crypto.SHA384, nil - case PKCS1WithSHA512, PSSWithSHA512, ECDSAWithP521AndSHA512: - return crypto.SHA512, nil - default: - return 0, fmt.Errorf("tls: unsupported signature algorithm: %#04x", signatureAlgorithm) - } -} - -func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash { - var buffer []byte - if version == VersionSSL30 || version >= VersionTLS12 { - buffer = []byte{} - } - - prf, hash := prfAndHashForVersion(version, cipherSuite) - if hash != 0 { - return finishedHash{hash.New(), hash.New(), nil, nil, buffer, version, prf} - } - - return finishedHash{sha1.New(), sha1.New(), md5.New(), md5.New(), buffer, version, prf} -} - -// A finishedHash calculates the hash of a set of handshake messages suitable -// for including in a Finished message. -type finishedHash struct { - client hash.Hash - server hash.Hash - - // Prior to TLS 1.2, an additional MD5 hash is required. - clientMD5 hash.Hash - serverMD5 hash.Hash - - // In TLS 1.2, a full buffer is sadly required. - buffer []byte - - version uint16 - prf func(result, secret, label, seed []byte) -} - -func (h *finishedHash) Write(msg []byte) (n int, err error) { - h.client.Write(msg) - h.server.Write(msg) - - if h.version < VersionTLS12 { - h.clientMD5.Write(msg) - h.serverMD5.Write(msg) - } - - if h.buffer != nil { - h.buffer = append(h.buffer, msg...) - } - - return len(msg), nil -} - -func (h finishedHash) Sum() []byte { - if h.version >= VersionTLS12 { - return h.client.Sum(nil) - } - - out := make([]byte, 0, md5.Size+sha1.Size) - out = h.clientMD5.Sum(out) - return h.client.Sum(out) -} - -// finishedSum30 calculates the contents of the verify_data member of a SSLv3 -// Finished message given the MD5 and SHA1 hashes of a set of handshake -// messages. -func finishedSum30(md5, sha1 hash.Hash, masterSecret []byte, magic []byte) []byte { - md5.Write(magic) - md5.Write(masterSecret) - md5.Write(ssl30Pad1[:]) - md5Digest := md5.Sum(nil) - - md5.Reset() - md5.Write(masterSecret) - md5.Write(ssl30Pad2[:]) - md5.Write(md5Digest) - md5Digest = md5.Sum(nil) - - sha1.Write(magic) - sha1.Write(masterSecret) - sha1.Write(ssl30Pad1[:40]) - sha1Digest := sha1.Sum(nil) - - sha1.Reset() - sha1.Write(masterSecret) - sha1.Write(ssl30Pad2[:40]) - sha1.Write(sha1Digest) - sha1Digest = sha1.Sum(nil) - - ret := make([]byte, len(md5Digest)+len(sha1Digest)) - copy(ret, md5Digest) - copy(ret[len(md5Digest):], sha1Digest) - return ret -} - -var ssl3ClientFinishedMagic = [4]byte{0x43, 0x4c, 0x4e, 0x54} -var ssl3ServerFinishedMagic = [4]byte{0x53, 0x52, 0x56, 0x52} - -// clientSum returns the contents of the verify_data member of a client's -// Finished message. -func (h finishedHash) clientSum(masterSecret []byte) []byte { - if h.version == VersionSSL30 { - return finishedSum30(h.clientMD5, h.client, masterSecret, ssl3ClientFinishedMagic[:]) - } - - out := make([]byte, finishedVerifyLength) - h.prf(out, masterSecret, clientFinishedLabel, h.Sum()) - return out -} - -// serverSum returns the contents of the verify_data member of a server's -// Finished message. -func (h finishedHash) serverSum(masterSecret []byte) []byte { - if h.version == VersionSSL30 { - return finishedSum30(h.serverMD5, h.server, masterSecret, ssl3ServerFinishedMagic[:]) - } - - out := make([]byte, finishedVerifyLength) - h.prf(out, masterSecret, serverFinishedLabel, h.Sum()) - return out -} - -// hashForClientCertificate returns a digest over the handshake messages so far, -// suitable for signing by a TLS client certificate. -func (h finishedHash) hashForClientCertificate(sigType uint8, hashAlg crypto.Hash, masterSecret []byte) ([]byte, error) { - if (h.version == VersionSSL30 || h.version >= VersionTLS12) && h.buffer == nil { - panic("a handshake hash for a client-certificate was requested after discarding the handshake buffer") - } - - if h.version == VersionSSL30 { - if sigType != signaturePKCS1v15 { - return nil, errors.New("tls: unsupported signature type for client certificate") - } - - md5Hash := md5.New() - md5Hash.Write(h.buffer) - sha1Hash := sha1.New() - sha1Hash.Write(h.buffer) - return finishedSum30(md5Hash, sha1Hash, masterSecret, nil), nil - } - if h.version >= VersionTLS12 { - hash := hashAlg.New() - hash.Write(h.buffer) - return hash.Sum(nil), nil - } - - if sigType == signatureECDSA { - return h.server.Sum(nil), nil - } - - return h.Sum(), nil -} - -// discardHandshakeBuffer is called when there is no more need to -// buffer the entirety of the handshake messages. -func (h *finishedHash) discardHandshakeBuffer() { - h.buffer = nil -} - -// noExportedKeyingMaterial is used as a value of -// ConnectionState.ekm when renegotation is enabled and thus -// we wish to fail all key-material export requests. -func noExportedKeyingMaterial(label string, context []byte, length int) ([]byte, error) { - return nil, errors.New("crypto/tls: ExportKeyingMaterial is unavailable when renegotiation is enabled") -} - -// ekmFromMasterSecret generates exported keying material as defined in RFC 5705. -func ekmFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte) func(string, []byte, int) ([]byte, error) { - return func(label string, context []byte, length int) ([]byte, error) { - switch label { - case "client finished", "server finished", "master secret", "key expansion": - // These values are reserved and may not be used. - return nil, fmt.Errorf("crypto/tls: reserved ExportKeyingMaterial label: %s", label) - } - - seedLen := len(serverRandom) + len(clientRandom) - if context != nil { - seedLen += 2 + len(context) - } - seed := make([]byte, 0, seedLen) - - seed = append(seed, clientRandom...) - seed = append(seed, serverRandom...) - - if context != nil { - if len(context) >= 1<<16 { - return nil, fmt.Errorf("crypto/tls: ExportKeyingMaterial context too long") - } - seed = append(seed, byte(len(context)>>8), byte(len(context))) - seed = append(seed, context...) - } - - keyMaterial := make([]byte, length) - prfForVersion(version, suite)(keyMaterial, masterSecret, []byte(label), seed) - return keyMaterial, nil - } -} diff --git a/vendor/github.com/marten-seemann/qtls/ticket.go b/vendor/github.com/marten-seemann/qtls/ticket.go deleted file mode 100644 index 989c9787de..0000000000 --- a/vendor/github.com/marten-seemann/qtls/ticket.go +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/hmac" - "crypto/sha256" - "crypto/subtle" - "errors" - "io" - - "golang.org/x/crypto/cryptobyte" -) - -// sessionState contains the information that is serialized into a session -// ticket in order to later resume a connection. -type sessionState struct { - vers uint16 - cipherSuite uint16 - masterSecret []byte - certificates [][]byte - // usedOldKey is true if the ticket from which this session came from - // was encrypted with an older key and thus should be refreshed. - usedOldKey bool -} - -func (s *sessionState) marshal() []byte { - length := 2 + 2 + 2 + len(s.masterSecret) + 2 - for _, cert := range s.certificates { - length += 4 + len(cert) - } - - ret := make([]byte, length) - x := ret - x[0] = byte(s.vers >> 8) - x[1] = byte(s.vers) - x[2] = byte(s.cipherSuite >> 8) - x[3] = byte(s.cipherSuite) - x[4] = byte(len(s.masterSecret) >> 8) - x[5] = byte(len(s.masterSecret)) - x = x[6:] - copy(x, s.masterSecret) - x = x[len(s.masterSecret):] - - x[0] = byte(len(s.certificates) >> 8) - x[1] = byte(len(s.certificates)) - x = x[2:] - - for _, cert := range s.certificates { - x[0] = byte(len(cert) >> 24) - x[1] = byte(len(cert) >> 16) - x[2] = byte(len(cert) >> 8) - x[3] = byte(len(cert)) - copy(x[4:], cert) - x = x[4+len(cert):] - } - - return ret -} - -func (s *sessionState) unmarshal(data []byte) bool { - if len(data) < 8 { - return false - } - - s.vers = uint16(data[0])<<8 | uint16(data[1]) - s.cipherSuite = uint16(data[2])<<8 | uint16(data[3]) - masterSecretLen := int(data[4])<<8 | int(data[5]) - data = data[6:] - if len(data) < masterSecretLen { - return false - } - - s.masterSecret = data[:masterSecretLen] - data = data[masterSecretLen:] - - if len(data) < 2 { - return false - } - - numCerts := int(data[0])<<8 | int(data[1]) - data = data[2:] - - s.certificates = make([][]byte, numCerts) - for i := range s.certificates { - if len(data) < 4 { - return false - } - certLen := int(data[0])<<24 | int(data[1])<<16 | int(data[2])<<8 | int(data[3]) - data = data[4:] - if certLen < 0 { - return false - } - if len(data) < certLen { - return false - } - s.certificates[i] = data[:certLen] - data = data[certLen:] - } - - return len(data) == 0 -} - -// sessionStateTLS13 is the content of a TLS 1.3 session ticket. Its first -// version (revision = 0) doesn't carry any of the information needed for 0-RTT -// validation and the nonce is always empty. -type sessionStateTLS13 struct { - // uint8 version = 0x0304; - // uint8 revision = 0; - cipherSuite uint16 - createdAt uint64 - resumptionSecret []byte // opaque resumption_master_secret<1..2^8-1>; - certificate Certificate // CertificateEntry certificate_list<0..2^24-1>; -} - -func (m *sessionStateTLS13) marshal() []byte { - var b cryptobyte.Builder - b.AddUint16(VersionTLS13) - b.AddUint8(0) // revision - b.AddUint16(m.cipherSuite) - addUint64(&b, m.createdAt) - b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.resumptionSecret) - }) - marshalCertificate(&b, m.certificate) - return b.BytesOrPanic() -} - -func (m *sessionStateTLS13) unmarshal(data []byte) bool { - *m = sessionStateTLS13{} - s := cryptobyte.String(data) - var version uint16 - var revision uint8 - return s.ReadUint16(&version) && - version == VersionTLS13 && - s.ReadUint8(&revision) && - revision == 0 && - s.ReadUint16(&m.cipherSuite) && - readUint64(&s, &m.createdAt) && - readUint8LengthPrefixed(&s, &m.resumptionSecret) && - len(m.resumptionSecret) != 0 && - unmarshalCertificate(&s, &m.certificate) && - s.Empty() -} - -func (c *Conn) encryptTicket(state []byte) ([]byte, error) { - encrypted := make([]byte, ticketKeyNameLen+aes.BlockSize+len(state)+sha256.Size) - keyName := encrypted[:ticketKeyNameLen] - iv := encrypted[ticketKeyNameLen : ticketKeyNameLen+aes.BlockSize] - macBytes := encrypted[len(encrypted)-sha256.Size:] - - if _, err := io.ReadFull(c.config.rand(), iv); err != nil { - return nil, err - } - key := c.config.ticketKeys()[0] - copy(keyName, key.keyName[:]) - block, err := aes.NewCipher(key.aesKey[:]) - if err != nil { - return nil, errors.New("tls: failed to create cipher while encrypting ticket: " + err.Error()) - } - cipher.NewCTR(block, iv).XORKeyStream(encrypted[ticketKeyNameLen+aes.BlockSize:], state) - - mac := hmac.New(sha256.New, key.hmacKey[:]) - mac.Write(encrypted[:len(encrypted)-sha256.Size]) - mac.Sum(macBytes[:0]) - - return encrypted, nil -} - -func (c *Conn) decryptTicket(encrypted []byte) (plaintext []byte, usedOldKey bool) { - if len(encrypted) < ticketKeyNameLen+aes.BlockSize+sha256.Size { - return nil, false - } - - keyName := encrypted[:ticketKeyNameLen] - iv := encrypted[ticketKeyNameLen : ticketKeyNameLen+aes.BlockSize] - macBytes := encrypted[len(encrypted)-sha256.Size:] - ciphertext := encrypted[ticketKeyNameLen+aes.BlockSize : len(encrypted)-sha256.Size] - - keys := c.config.ticketKeys() - keyIndex := -1 - for i, candidateKey := range keys { - if bytes.Equal(keyName, candidateKey.keyName[:]) { - keyIndex = i - break - } - } - - if keyIndex == -1 { - return nil, false - } - key := &keys[keyIndex] - - mac := hmac.New(sha256.New, key.hmacKey[:]) - mac.Write(encrypted[:len(encrypted)-sha256.Size]) - expected := mac.Sum(nil) - - if subtle.ConstantTimeCompare(macBytes, expected) != 1 { - return nil, false - } - - block, err := aes.NewCipher(key.aesKey[:]) - if err != nil { - return nil, false - } - plaintext = make([]byte, len(ciphertext)) - cipher.NewCTR(block, iv).XORKeyStream(plaintext, ciphertext) - - return plaintext, keyIndex > 0 -} diff --git a/vendor/github.com/marten-seemann/qtls/tls.go b/vendor/github.com/marten-seemann/qtls/tls.go deleted file mode 100644 index 818997d3ed..0000000000 --- a/vendor/github.com/marten-seemann/qtls/tls.go +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// package qtls partially implements TLS 1.2, as specified in RFC 5246, -// and TLS 1.3, as specified in RFC 8446. -// -// TLS 1.3 is available only on an opt-in basis in Go 1.12. To enable -// it, set the GODEBUG environment variable (comma-separated key=value -// options) such that it includes "tls13=1". To enable it from within -// the process, set the environment variable before any use of TLS: -// -// func init() { -// os.Setenv("GODEBUG", os.Getenv("GODEBUG")+",tls13=1") -// } -package qtls - -// BUG(agl): The crypto/tls package only implements some countermeasures -// against Lucky13 attacks on CBC-mode encryption, and only on SHA1 -// variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and -// https://www.imperialviolet.org/2013/02/04/luckythirteen.html. - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "io/ioutil" - "net" - "strings" - "time" -) - -// Server returns a new TLS server side connection -// using conn as the underlying transport. -// The configuration config must be non-nil and must include -// at least one certificate or else set GetCertificate. -func Server(conn net.Conn, config *Config) *Conn { - return &Conn{conn: conn, config: config} -} - -// Client returns a new TLS client side connection -// using conn as the underlying transport. -// The config cannot be nil: users must set either ServerName or -// InsecureSkipVerify in the config. -func Client(conn net.Conn, config *Config) *Conn { - return &Conn{conn: conn, config: config, isClient: true} -} - -// A listener implements a network listener (net.Listener) for TLS connections. -type listener struct { - net.Listener - config *Config -} - -// Accept waits for and returns the next incoming TLS connection. -// The returned connection is of type *Conn. -func (l *listener) Accept() (net.Conn, error) { - c, err := l.Listener.Accept() - if err != nil { - return nil, err - } - return Server(c, l.config), nil -} - -// NewListener creates a Listener which accepts connections from an inner -// Listener and wraps each connection with Server. -// The configuration config must be non-nil and must include -// at least one certificate or else set GetCertificate. -func NewListener(inner net.Listener, config *Config) net.Listener { - l := new(listener) - l.Listener = inner - l.config = config - return l -} - -// Listen creates a TLS listener accepting connections on the -// given network address using net.Listen. -// The configuration config must be non-nil and must include -// at least one certificate or else set GetCertificate. -func Listen(network, laddr string, config *Config) (net.Listener, error) { - if config == nil || (len(config.Certificates) == 0 && config.GetCertificate == nil) { - return nil, errors.New("tls: neither Certificates nor GetCertificate set in Config") - } - l, err := net.Listen(network, laddr) - if err != nil { - return nil, err - } - return NewListener(l, config), nil -} - -type timeoutError struct{} - -func (timeoutError) Error() string { return "tls: DialWithDialer timed out" } -func (timeoutError) Timeout() bool { return true } -func (timeoutError) Temporary() bool { return true } - -// DialWithDialer connects to the given network address using dialer.Dial and -// then initiates a TLS handshake, returning the resulting TLS connection. Any -// timeout or deadline given in the dialer apply to connection and TLS -// handshake as a whole. -// -// DialWithDialer interprets a nil configuration as equivalent to the zero -// configuration; see the documentation of Config for the defaults. -func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) { - // We want the Timeout and Deadline values from dialer to cover the - // whole process: TCP connection and TLS handshake. This means that we - // also need to start our own timers now. - timeout := dialer.Timeout - - if !dialer.Deadline.IsZero() { - deadlineTimeout := time.Until(dialer.Deadline) - if timeout == 0 || deadlineTimeout < timeout { - timeout = deadlineTimeout - } - } - - var errChannel chan error - - if timeout != 0 { - errChannel = make(chan error, 2) - time.AfterFunc(timeout, func() { - errChannel <- timeoutError{} - }) - } - - rawConn, err := dialer.Dial(network, addr) - if err != nil { - return nil, err - } - - colonPos := strings.LastIndex(addr, ":") - if colonPos == -1 { - colonPos = len(addr) - } - hostname := addr[:colonPos] - - if config == nil { - config = defaultConfig() - } - // If no ServerName is set, infer the ServerName - // from the hostname we're connecting to. - if config.ServerName == "" { - // Make a copy to avoid polluting argument or default. - c := config.Clone() - c.ServerName = hostname - config = c - } - - conn := Client(rawConn, config) - - if timeout == 0 { - err = conn.Handshake() - } else { - go func() { - errChannel <- conn.Handshake() - }() - - err = <-errChannel - } - - if err != nil { - rawConn.Close() - return nil, err - } - - return conn, nil -} - -// Dial connects to the given network address using net.Dial -// and then initiates a TLS handshake, returning the resulting -// TLS connection. -// Dial interprets a nil configuration as equivalent to -// the zero configuration; see the documentation of Config -// for the defaults. -func Dial(network, addr string, config *Config) (*Conn, error) { - return DialWithDialer(new(net.Dialer), network, addr, config) -} - -// LoadX509KeyPair reads and parses a public/private key pair from a pair -// of files. The files must contain PEM encoded data. The certificate file -// may contain intermediate certificates following the leaf certificate to -// form a certificate chain. On successful return, Certificate.Leaf will -// be nil because the parsed form of the certificate is not retained. -func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) { - certPEMBlock, err := ioutil.ReadFile(certFile) - if err != nil { - return Certificate{}, err - } - keyPEMBlock, err := ioutil.ReadFile(keyFile) - if err != nil { - return Certificate{}, err - } - return X509KeyPair(certPEMBlock, keyPEMBlock) -} - -// X509KeyPair parses a public/private key pair from a pair of -// PEM encoded data. On successful return, Certificate.Leaf will be nil because -// the parsed form of the certificate is not retained. -func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) { - fail := func(err error) (Certificate, error) { return Certificate{}, err } - - var cert Certificate - var skippedBlockTypes []string - for { - var certDERBlock *pem.Block - certDERBlock, certPEMBlock = pem.Decode(certPEMBlock) - if certDERBlock == nil { - break - } - if certDERBlock.Type == "CERTIFICATE" { - cert.Certificate = append(cert.Certificate, certDERBlock.Bytes) - } else { - skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type) - } - } - - if len(cert.Certificate) == 0 { - if len(skippedBlockTypes) == 0 { - return fail(errors.New("tls: failed to find any PEM data in certificate input")) - } - if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") { - return fail(errors.New("tls: failed to find certificate PEM data in certificate input, but did find a private key; PEM inputs may have been switched")) - } - return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes)) - } - - skippedBlockTypes = skippedBlockTypes[:0] - var keyDERBlock *pem.Block - for { - keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock) - if keyDERBlock == nil { - if len(skippedBlockTypes) == 0 { - return fail(errors.New("tls: failed to find any PEM data in key input")) - } - if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" { - return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key")) - } - return fail(fmt.Errorf("tls: failed to find PEM block with type ending in \"PRIVATE KEY\" in key input after skipping PEM blocks of the following types: %v", skippedBlockTypes)) - } - if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") { - break - } - skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type) - } - - // We don't need to parse the public key for TLS, but we so do anyway - // to check that it looks sane and matches the private key. - x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) - if err != nil { - return fail(err) - } - - cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes) - if err != nil { - return fail(err) - } - - switch pub := x509Cert.PublicKey.(type) { - case *rsa.PublicKey: - priv, ok := cert.PrivateKey.(*rsa.PrivateKey) - if !ok { - return fail(errors.New("tls: private key type does not match public key type")) - } - if pub.N.Cmp(priv.N) != 0 { - return fail(errors.New("tls: private key does not match public key")) - } - case *ecdsa.PublicKey: - priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey) - if !ok { - return fail(errors.New("tls: private key type does not match public key type")) - } - if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 { - return fail(errors.New("tls: private key does not match public key")) - } - default: - return fail(errors.New("tls: unknown public key algorithm")) - } - - return cert, nil -} - -// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates -// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys. -// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. -func parsePrivateKey(der []byte) (crypto.PrivateKey, error) { - if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { - return key, nil - } - if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { - switch key := key.(type) { - case *rsa.PrivateKey, *ecdsa.PrivateKey: - return key, nil - default: - return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping") - } - } - if key, err := x509.ParseECPrivateKey(der); err == nil { - return key, nil - } - - return nil, errors.New("tls: failed to parse private key") -} diff --git a/vendor/github.com/prometheus/procfs/internal/fs/fs.go b/vendor/github.com/prometheus/procfs/internal/fs/fs.go deleted file mode 100644 index c66a1cf80e..0000000000 --- a/vendor/github.com/prometheus/procfs/internal/fs/fs.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2019 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fs - -import ( - "fmt" - "os" - "path/filepath" -) - -const ( - // DefaultProcMountPoint is the common mount point of the proc filesystem. - DefaultProcMountPoint = "/proc" - - // DefaultSysMountPoint is the common mount point of the sys filesystem. - DefaultSysMountPoint = "/sys" -) - -// FS represents a pseudo-filesystem, normally /proc or /sys, which provides an -// interface to kernel data structures. -type FS string - -// NewFS returns a new FS mounted under the given mountPoint. It will error -// if the mount point can't be read. -func NewFS(mountPoint string) (FS, error) { - info, err := os.Stat(mountPoint) - if err != nil { - return "", fmt.Errorf("could not read %s: %s", mountPoint, err) - } - if !info.IsDir() { - return "", fmt.Errorf("mount point %s is not a directory", mountPoint) - } - - return FS(mountPoint), nil -} - -// Path appends the given path elements to the filesystem path, adding separators -// as necessary. -func (fs FS) Path(p ...string) string { - return filepath.Join(append([]string{string(fs)}, p...)...) -} diff --git a/vendor/github.com/webx-top/com/caller.go b/vendor/github.com/webx-top/com/caller.go index 76d97dacac..ecd0e41699 100644 --- a/vendor/github.com/webx-top/com/caller.go +++ b/vendor/github.com/webx-top/com/caller.go @@ -15,6 +15,7 @@ limitations under the License. */ + package com import ( diff --git a/vendor/github.com/webx-top/com/cmd.go b/vendor/github.com/webx-top/com/cmd.go index 788635d939..4b9a4e6d11 100644 --- a/vendor/github.com/webx-top/com/cmd.go +++ b/vendor/github.com/webx-top/com/cmd.go @@ -172,12 +172,18 @@ func (this CmdResultCapturer) WriteString(p string) (n int, err error) { return } -func NewCmdChanReader() *CmdChanReader { - return &CmdChanReader{ch: make(chan io.Reader)} +func NewCmdChanReader(timeouts ...time.Duration) *CmdChanReader { + timeout := time.Second + if len(timeouts) > 0 { + timeout = timeouts[0] + } + return &CmdChanReader{ch: make(chan io.Reader), timeout: timeout} } type CmdChanReader struct { - ch chan io.Reader + ch chan io.Reader + timeout time.Duration + debug bool } func (c *CmdChanReader) Read(p []byte) (n int, err error) { @@ -191,18 +197,48 @@ func (c *CmdChanReader) Read(p []byte) (n int, err error) { return r.Read(p) } +func (c *CmdChanReader) Debug(on bool) *CmdChanReader { + c.debug = on + return c +} + func (c *CmdChanReader) Close() { + if c.ch == nil { + return + } close(c.ch) c.ch = nil } func (c *CmdChanReader) Send(b []byte) *CmdChanReader { - c.ch <- bytes.NewReader(b) + c.sendWithTimeout(bytes.NewReader(b)) return c } +func (c *CmdChanReader) sendWithTimeout(r io.Reader) { + go func() { + t := time.NewTicker(c.timeout) + defer t.Stop() + for { + select { + case c.ch <- r: + if c.debug { + println(`CmdChanReader Chan has been sent`) + } + return + case <-t.C: + if c.debug { + println(`CmdChanReader Chan has timed out`) + } + c.Close() + return + } + } + }() +} + func (c *CmdChanReader) SendString(s string) *CmdChanReader { - c.ch <- strings.NewReader(s) + c.sendWithTimeout(strings.NewReader(s)) return c } diff --git a/vendor/github.com/webx-top/com/string.go b/vendor/github.com/webx-top/com/string.go index 6761b7903d..9aa09220e1 100644 --- a/vendor/github.com/webx-top/com/string.go +++ b/vendor/github.com/webx-top/com/string.go @@ -510,7 +510,7 @@ func LeftPadZero(input string, padLength int) string { var ( reSpaceLine = regexp.MustCompile("([\\t\\s\r]*\n){2,}") BreakLine = []byte("\n") - BreakLineString = "\n" + BreakLineString = StrLF ) func CleanSpaceLine(b []byte) []byte { diff --git a/vendor/github.com/webx-top/com/time.go b/vendor/github.com/webx-top/com/time.go index ecd56e6ff7..066a6e7cfd 100644 --- a/vendor/github.com/webx-top/com/time.go +++ b/vendor/github.com/webx-top/com/time.go @@ -432,3 +432,8 @@ func (d *Durafmt) String() string { duration = strings.TrimSpace(duration) return duration } + +// NowStr 当前时间字符串 +func NowStr() string { + return time.Now().Format(`2006-01-02 15:04:05`) +} diff --git a/vendor/github.com/webx-top/com/vars.go b/vendor/github.com/webx-top/com/vars.go new file mode 100644 index 0000000000..3dbf85d483 --- /dev/null +++ b/vendor/github.com/webx-top/com/vars.go @@ -0,0 +1,11 @@ +package com + +const ( + TB byte = '\t' + LF byte = '\n' + CR byte = '\r' + StrLF = "\n" + StrR = "\r" + StrCRLF = "\r\n" + StrTB = "\t" +) diff --git a/vendor/golang.org/x/crypto/cryptobyte/asn1.go b/vendor/golang.org/x/crypto/cryptobyte/asn1.go deleted file mode 100644 index 528b9bff67..0000000000 --- a/vendor/golang.org/x/crypto/cryptobyte/asn1.go +++ /dev/null @@ -1,751 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cryptobyte - -import ( - encoding_asn1 "encoding/asn1" - "fmt" - "math/big" - "reflect" - "time" - - "golang.org/x/crypto/cryptobyte/asn1" -) - -// This file contains ASN.1-related methods for String and Builder. - -// Builder - -// AddASN1Int64 appends a DER-encoded ASN.1 INTEGER. -func (b *Builder) AddASN1Int64(v int64) { - b.addASN1Signed(asn1.INTEGER, v) -} - -// AddASN1Int64WithTag appends a DER-encoded ASN.1 INTEGER with the -// given tag. -func (b *Builder) AddASN1Int64WithTag(v int64, tag asn1.Tag) { - b.addASN1Signed(tag, v) -} - -// AddASN1Enum appends a DER-encoded ASN.1 ENUMERATION. -func (b *Builder) AddASN1Enum(v int64) { - b.addASN1Signed(asn1.ENUM, v) -} - -func (b *Builder) addASN1Signed(tag asn1.Tag, v int64) { - b.AddASN1(tag, func(c *Builder) { - length := 1 - for i := v; i >= 0x80 || i < -0x80; i >>= 8 { - length++ - } - - for ; length > 0; length-- { - i := v >> uint((length-1)*8) & 0xff - c.AddUint8(uint8(i)) - } - }) -} - -// AddASN1Uint64 appends a DER-encoded ASN.1 INTEGER. -func (b *Builder) AddASN1Uint64(v uint64) { - b.AddASN1(asn1.INTEGER, func(c *Builder) { - length := 1 - for i := v; i >= 0x80; i >>= 8 { - length++ - } - - for ; length > 0; length-- { - i := v >> uint((length-1)*8) & 0xff - c.AddUint8(uint8(i)) - } - }) -} - -// AddASN1BigInt appends a DER-encoded ASN.1 INTEGER. -func (b *Builder) AddASN1BigInt(n *big.Int) { - if b.err != nil { - return - } - - b.AddASN1(asn1.INTEGER, func(c *Builder) { - if n.Sign() < 0 { - // A negative number has to be converted to two's-complement form. So we - // invert and subtract 1. If the most-significant-bit isn't set then - // we'll need to pad the beginning with 0xff in order to keep the number - // negative. - nMinus1 := new(big.Int).Neg(n) - nMinus1.Sub(nMinus1, bigOne) - bytes := nMinus1.Bytes() - for i := range bytes { - bytes[i] ^= 0xff - } - if bytes[0]&0x80 == 0 { - c.add(0xff) - } - c.add(bytes...) - } else if n.Sign() == 0 { - c.add(0) - } else { - bytes := n.Bytes() - if bytes[0]&0x80 != 0 { - c.add(0) - } - c.add(bytes...) - } - }) -} - -// AddASN1OctetString appends a DER-encoded ASN.1 OCTET STRING. -func (b *Builder) AddASN1OctetString(bytes []byte) { - b.AddASN1(asn1.OCTET_STRING, func(c *Builder) { - c.AddBytes(bytes) - }) -} - -const generalizedTimeFormatStr = "20060102150405Z0700" - -// AddASN1GeneralizedTime appends a DER-encoded ASN.1 GENERALIZEDTIME. -func (b *Builder) AddASN1GeneralizedTime(t time.Time) { - if t.Year() < 0 || t.Year() > 9999 { - b.err = fmt.Errorf("cryptobyte: cannot represent %v as a GeneralizedTime", t) - return - } - b.AddASN1(asn1.GeneralizedTime, func(c *Builder) { - c.AddBytes([]byte(t.Format(generalizedTimeFormatStr))) - }) -} - -// AddASN1BitString appends a DER-encoded ASN.1 BIT STRING. This does not -// support BIT STRINGs that are not a whole number of bytes. -func (b *Builder) AddASN1BitString(data []byte) { - b.AddASN1(asn1.BIT_STRING, func(b *Builder) { - b.AddUint8(0) - b.AddBytes(data) - }) -} - -func (b *Builder) addBase128Int(n int64) { - var length int - if n == 0 { - length = 1 - } else { - for i := n; i > 0; i >>= 7 { - length++ - } - } - - for i := length - 1; i >= 0; i-- { - o := byte(n >> uint(i*7)) - o &= 0x7f - if i != 0 { - o |= 0x80 - } - - b.add(o) - } -} - -func isValidOID(oid encoding_asn1.ObjectIdentifier) bool { - if len(oid) < 2 { - return false - } - - if oid[0] > 2 || (oid[0] <= 1 && oid[1] >= 40) { - return false - } - - for _, v := range oid { - if v < 0 { - return false - } - } - - return true -} - -func (b *Builder) AddASN1ObjectIdentifier(oid encoding_asn1.ObjectIdentifier) { - b.AddASN1(asn1.OBJECT_IDENTIFIER, func(b *Builder) { - if !isValidOID(oid) { - b.err = fmt.Errorf("cryptobyte: invalid OID: %v", oid) - return - } - - b.addBase128Int(int64(oid[0])*40 + int64(oid[1])) - for _, v := range oid[2:] { - b.addBase128Int(int64(v)) - } - }) -} - -func (b *Builder) AddASN1Boolean(v bool) { - b.AddASN1(asn1.BOOLEAN, func(b *Builder) { - if v { - b.AddUint8(0xff) - } else { - b.AddUint8(0) - } - }) -} - -func (b *Builder) AddASN1NULL() { - b.add(uint8(asn1.NULL), 0) -} - -// MarshalASN1 calls encoding_asn1.Marshal on its input and appends the result if -// successful or records an error if one occurred. -func (b *Builder) MarshalASN1(v interface{}) { - // NOTE(martinkr): This is somewhat of a hack to allow propagation of - // encoding_asn1.Marshal errors into Builder.err. N.B. if you call MarshalASN1 with a - // value embedded into a struct, its tag information is lost. - if b.err != nil { - return - } - bytes, err := encoding_asn1.Marshal(v) - if err != nil { - b.err = err - return - } - b.AddBytes(bytes) -} - -// AddASN1 appends an ASN.1 object. The object is prefixed with the given tag. -// Tags greater than 30 are not supported and result in an error (i.e. -// low-tag-number form only). The child builder passed to the -// BuilderContinuation can be used to build the content of the ASN.1 object. -func (b *Builder) AddASN1(tag asn1.Tag, f BuilderContinuation) { - if b.err != nil { - return - } - // Identifiers with the low five bits set indicate high-tag-number format - // (two or more octets), which we don't support. - if tag&0x1f == 0x1f { - b.err = fmt.Errorf("cryptobyte: high-tag number identifier octects not supported: 0x%x", tag) - return - } - b.AddUint8(uint8(tag)) - b.addLengthPrefixed(1, true, f) -} - -// String - -// ReadASN1Boolean decodes an ASN.1 INTEGER and converts it to a boolean -// representation into out and advances. It reports whether the read -// was successful. -func (s *String) ReadASN1Boolean(out *bool) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.INTEGER) || len(bytes) != 1 { - return false - } - - switch bytes[0] { - case 0: - *out = false - case 0xff: - *out = true - default: - return false - } - - return true -} - -var bigIntType = reflect.TypeOf((*big.Int)(nil)).Elem() - -// ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does -// not point to an integer or to a big.Int, it panics. It reports whether the -// read was successful. -func (s *String) ReadASN1Integer(out interface{}) bool { - if reflect.TypeOf(out).Kind() != reflect.Ptr { - panic("out is not a pointer") - } - switch reflect.ValueOf(out).Elem().Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - var i int64 - if !s.readASN1Int64(&i) || reflect.ValueOf(out).Elem().OverflowInt(i) { - return false - } - reflect.ValueOf(out).Elem().SetInt(i) - return true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - var u uint64 - if !s.readASN1Uint64(&u) || reflect.ValueOf(out).Elem().OverflowUint(u) { - return false - } - reflect.ValueOf(out).Elem().SetUint(u) - return true - case reflect.Struct: - if reflect.TypeOf(out).Elem() == bigIntType { - return s.readASN1BigInt(out.(*big.Int)) - } - } - panic("out does not point to an integer type") -} - -func checkASN1Integer(bytes []byte) bool { - if len(bytes) == 0 { - // An INTEGER is encoded with at least one octet. - return false - } - if len(bytes) == 1 { - return true - } - if bytes[0] == 0 && bytes[1]&0x80 == 0 || bytes[0] == 0xff && bytes[1]&0x80 == 0x80 { - // Value is not minimally encoded. - return false - } - return true -} - -var bigOne = big.NewInt(1) - -func (s *String) readASN1BigInt(out *big.Int) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) { - return false - } - if bytes[0]&0x80 == 0x80 { - // Negative number. - neg := make([]byte, len(bytes)) - for i, b := range bytes { - neg[i] = ^b - } - out.SetBytes(neg) - out.Add(out, bigOne) - out.Neg(out) - } else { - out.SetBytes(bytes) - } - return true -} - -func (s *String) readASN1Int64(out *int64) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Signed(out, bytes) { - return false - } - return true -} - -func asn1Signed(out *int64, n []byte) bool { - length := len(n) - if length > 8 { - return false - } - for i := 0; i < length; i++ { - *out <<= 8 - *out |= int64(n[i]) - } - // Shift up and down in order to sign extend the result. - *out <<= 64 - uint8(length)*8 - *out >>= 64 - uint8(length)*8 - return true -} - -func (s *String) readASN1Uint64(out *uint64) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Unsigned(out, bytes) { - return false - } - return true -} - -func asn1Unsigned(out *uint64, n []byte) bool { - length := len(n) - if length > 9 || length == 9 && n[0] != 0 { - // Too large for uint64. - return false - } - if n[0]&0x80 != 0 { - // Negative number. - return false - } - for i := 0; i < length; i++ { - *out <<= 8 - *out |= uint64(n[i]) - } - return true -} - -// ReadASN1Int64WithTag decodes an ASN.1 INTEGER with the given tag into out -// and advances. It reports whether the read was successful and resulted in a -// value that can be represented in an int64. -func (s *String) ReadASN1Int64WithTag(out *int64, tag asn1.Tag) bool { - var bytes String - return s.ReadASN1(&bytes, tag) && checkASN1Integer(bytes) && asn1Signed(out, bytes) -} - -// ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It reports -// whether the read was successful. -func (s *String) ReadASN1Enum(out *int) bool { - var bytes String - var i int64 - if !s.ReadASN1(&bytes, asn1.ENUM) || !checkASN1Integer(bytes) || !asn1Signed(&i, bytes) { - return false - } - if int64(int(i)) != i { - return false - } - *out = int(i) - return true -} - -func (s *String) readBase128Int(out *int) bool { - ret := 0 - for i := 0; len(*s) > 0; i++ { - if i == 4 { - return false - } - ret <<= 7 - b := s.read(1)[0] - ret |= int(b & 0x7f) - if b&0x80 == 0 { - *out = ret - return true - } - } - return false // truncated -} - -// ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and -// advances. It reports whether the read was successful. -func (s *String) ReadASN1ObjectIdentifier(out *encoding_asn1.ObjectIdentifier) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.OBJECT_IDENTIFIER) || len(bytes) == 0 { - return false - } - - // In the worst case, we get two elements from the first byte (which is - // encoded differently) and then every varint is a single byte long. - components := make([]int, len(bytes)+1) - - // The first varint is 40*value1 + value2: - // According to this packing, value1 can take the values 0, 1 and 2 only. - // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2, - // then there are no restrictions on value2. - var v int - if !bytes.readBase128Int(&v) { - return false - } - if v < 80 { - components[0] = v / 40 - components[1] = v % 40 - } else { - components[0] = 2 - components[1] = v - 80 - } - - i := 2 - for ; len(bytes) > 0; i++ { - if !bytes.readBase128Int(&v) { - return false - } - components[i] = v - } - *out = components[:i] - return true -} - -// ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and -// advances. It reports whether the read was successful. -func (s *String) ReadASN1GeneralizedTime(out *time.Time) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.GeneralizedTime) { - return false - } - t := string(bytes) - res, err := time.Parse(generalizedTimeFormatStr, t) - if err != nil { - return false - } - if serialized := res.Format(generalizedTimeFormatStr); serialized != t { - return false - } - *out = res - return true -} - -// ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. -// It reports whether the read was successful. -func (s *String) ReadASN1BitString(out *encoding_asn1.BitString) bool { - var bytes String - if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 { - return false - } - - paddingBits := uint8(bytes[0]) - bytes = bytes[1:] - if paddingBits > 7 || - len(bytes) == 0 && paddingBits != 0 || - len(bytes) > 0 && bytes[len(bytes)-1]&(1< 4 || len(*s) < int(2+lenLen) { - return false - } - - lenBytes := String((*s)[2 : 2+lenLen]) - if !lenBytes.readUnsigned(&len32, int(lenLen)) { - return false - } - - // ITU-T X.690 section 10.1 (DER length forms) requires encoding the length - // with the minimum number of octets. - if len32 < 128 { - // Length should have used short-form encoding. - return false - } - if len32>>((lenLen-1)*8) == 0 { - // Leading octet is 0. Length should have been at least one byte shorter. - return false - } - - headerLen = 2 + uint32(lenLen) - if headerLen+len32 < len32 { - // Overflow. - return false - } - length = headerLen + len32 - } - - if uint32(int(length)) != length || !s.ReadBytes((*[]byte)(out), int(length)) { - return false - } - if skipHeader && !out.Skip(int(headerLen)) { - panic("cryptobyte: internal error") - } - - return true -} diff --git a/vendor/golang.org/x/crypto/cryptobyte/asn1/asn1.go b/vendor/golang.org/x/crypto/cryptobyte/asn1/asn1.go deleted file mode 100644 index cda8e3edfd..0000000000 --- a/vendor/golang.org/x/crypto/cryptobyte/asn1/asn1.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package asn1 contains supporting types for parsing and building ASN.1 -// messages with the cryptobyte package. -package asn1 // import "golang.org/x/crypto/cryptobyte/asn1" - -// Tag represents an ASN.1 identifier octet, consisting of a tag number -// (indicating a type) and class (such as context-specific or constructed). -// -// Methods in the cryptobyte package only support the low-tag-number form, i.e. -// a single identifier octet with bits 7-8 encoding the class and bits 1-6 -// encoding the tag number. -type Tag uint8 - -const ( - classConstructed = 0x20 - classContextSpecific = 0x80 -) - -// Constructed returns t with the constructed class bit set. -func (t Tag) Constructed() Tag { return t | classConstructed } - -// ContextSpecific returns t with the context-specific class bit set. -func (t Tag) ContextSpecific() Tag { return t | classContextSpecific } - -// The following is a list of standard tag and class combinations. -const ( - BOOLEAN = Tag(1) - INTEGER = Tag(2) - BIT_STRING = Tag(3) - OCTET_STRING = Tag(4) - NULL = Tag(5) - OBJECT_IDENTIFIER = Tag(6) - ENUM = Tag(10) - UTF8String = Tag(12) - SEQUENCE = Tag(16 | classConstructed) - SET = Tag(17 | classConstructed) - PrintableString = Tag(19) - T61String = Tag(20) - IA5String = Tag(22) - UTCTime = Tag(23) - GeneralizedTime = Tag(24) - GeneralString = Tag(27) -) diff --git a/vendor/golang.org/x/crypto/cryptobyte/builder.go b/vendor/golang.org/x/crypto/cryptobyte/builder.go deleted file mode 100644 index ca7b1db5ce..0000000000 --- a/vendor/golang.org/x/crypto/cryptobyte/builder.go +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cryptobyte - -import ( - "errors" - "fmt" -) - -// A Builder builds byte strings from fixed-length and length-prefixed values. -// Builders either allocate space as needed, or are ‘fixed’, which means that -// they write into a given buffer and produce an error if it's exhausted. -// -// The zero value is a usable Builder that allocates space as needed. -// -// Simple values are marshaled and appended to a Builder using methods on the -// Builder. Length-prefixed values are marshaled by providing a -// BuilderContinuation, which is a function that writes the inner contents of -// the value to a given Builder. See the documentation for BuilderContinuation -// for details. -type Builder struct { - err error - result []byte - fixedSize bool - child *Builder - offset int - pendingLenLen int - pendingIsASN1 bool - inContinuation *bool -} - -// NewBuilder creates a Builder that appends its output to the given buffer. -// Like append(), the slice will be reallocated if its capacity is exceeded. -// Use Bytes to get the final buffer. -func NewBuilder(buffer []byte) *Builder { - return &Builder{ - result: buffer, - } -} - -// NewFixedBuilder creates a Builder that appends its output into the given -// buffer. This builder does not reallocate the output buffer. Writes that -// would exceed the buffer's capacity are treated as an error. -func NewFixedBuilder(buffer []byte) *Builder { - return &Builder{ - result: buffer, - fixedSize: true, - } -} - -// SetError sets the value to be returned as the error from Bytes. Writes -// performed after calling SetError are ignored. -func (b *Builder) SetError(err error) { - b.err = err -} - -// Bytes returns the bytes written by the builder or an error if one has -// occurred during building. -func (b *Builder) Bytes() ([]byte, error) { - if b.err != nil { - return nil, b.err - } - return b.result[b.offset:], nil -} - -// BytesOrPanic returns the bytes written by the builder or panics if an error -// has occurred during building. -func (b *Builder) BytesOrPanic() []byte { - if b.err != nil { - panic(b.err) - } - return b.result[b.offset:] -} - -// AddUint8 appends an 8-bit value to the byte string. -func (b *Builder) AddUint8(v uint8) { - b.add(byte(v)) -} - -// AddUint16 appends a big-endian, 16-bit value to the byte string. -func (b *Builder) AddUint16(v uint16) { - b.add(byte(v>>8), byte(v)) -} - -// AddUint24 appends a big-endian, 24-bit value to the byte string. The highest -// byte of the 32-bit input value is silently truncated. -func (b *Builder) AddUint24(v uint32) { - b.add(byte(v>>16), byte(v>>8), byte(v)) -} - -// AddUint32 appends a big-endian, 32-bit value to the byte string. -func (b *Builder) AddUint32(v uint32) { - b.add(byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) -} - -// AddBytes appends a sequence of bytes to the byte string. -func (b *Builder) AddBytes(v []byte) { - b.add(v...) -} - -// BuilderContinuation is a continuation-passing interface for building -// length-prefixed byte sequences. Builder methods for length-prefixed -// sequences (AddUint8LengthPrefixed etc) will invoke the BuilderContinuation -// supplied to them. The child builder passed to the continuation can be used -// to build the content of the length-prefixed sequence. For example: -// -// parent := cryptobyte.NewBuilder() -// parent.AddUint8LengthPrefixed(func (child *Builder) { -// child.AddUint8(42) -// child.AddUint8LengthPrefixed(func (grandchild *Builder) { -// grandchild.AddUint8(5) -// }) -// }) -// -// It is an error to write more bytes to the child than allowed by the reserved -// length prefix. After the continuation returns, the child must be considered -// invalid, i.e. users must not store any copies or references of the child -// that outlive the continuation. -// -// If the continuation panics with a value of type BuildError then the inner -// error will be returned as the error from Bytes. If the child panics -// otherwise then Bytes will repanic with the same value. -type BuilderContinuation func(child *Builder) - -// BuildError wraps an error. If a BuilderContinuation panics with this value, -// the panic will be recovered and the inner error will be returned from -// Builder.Bytes. -type BuildError struct { - Err error -} - -// AddUint8LengthPrefixed adds a 8-bit length-prefixed byte sequence. -func (b *Builder) AddUint8LengthPrefixed(f BuilderContinuation) { - b.addLengthPrefixed(1, false, f) -} - -// AddUint16LengthPrefixed adds a big-endian, 16-bit length-prefixed byte sequence. -func (b *Builder) AddUint16LengthPrefixed(f BuilderContinuation) { - b.addLengthPrefixed(2, false, f) -} - -// AddUint24LengthPrefixed adds a big-endian, 24-bit length-prefixed byte sequence. -func (b *Builder) AddUint24LengthPrefixed(f BuilderContinuation) { - b.addLengthPrefixed(3, false, f) -} - -// AddUint32LengthPrefixed adds a big-endian, 32-bit length-prefixed byte sequence. -func (b *Builder) AddUint32LengthPrefixed(f BuilderContinuation) { - b.addLengthPrefixed(4, false, f) -} - -func (b *Builder) callContinuation(f BuilderContinuation, arg *Builder) { - if !*b.inContinuation { - *b.inContinuation = true - - defer func() { - *b.inContinuation = false - - r := recover() - if r == nil { - return - } - - if buildError, ok := r.(BuildError); ok { - b.err = buildError.Err - } else { - panic(r) - } - }() - } - - f(arg) -} - -func (b *Builder) addLengthPrefixed(lenLen int, isASN1 bool, f BuilderContinuation) { - // Subsequent writes can be ignored if the builder has encountered an error. - if b.err != nil { - return - } - - offset := len(b.result) - b.add(make([]byte, lenLen)...) - - if b.inContinuation == nil { - b.inContinuation = new(bool) - } - - b.child = &Builder{ - result: b.result, - fixedSize: b.fixedSize, - offset: offset, - pendingLenLen: lenLen, - pendingIsASN1: isASN1, - inContinuation: b.inContinuation, - } - - b.callContinuation(f, b.child) - b.flushChild() - if b.child != nil { - panic("cryptobyte: internal error") - } -} - -func (b *Builder) flushChild() { - if b.child == nil { - return - } - b.child.flushChild() - child := b.child - b.child = nil - - if child.err != nil { - b.err = child.err - return - } - - length := len(child.result) - child.pendingLenLen - child.offset - - if length < 0 { - panic("cryptobyte: internal error") // result unexpectedly shrunk - } - - if child.pendingIsASN1 { - // For ASN.1, we reserved a single byte for the length. If that turned out - // to be incorrect, we have to move the contents along in order to make - // space. - if child.pendingLenLen != 1 { - panic("cryptobyte: internal error") - } - var lenLen, lenByte uint8 - if int64(length) > 0xfffffffe { - b.err = errors.New("pending ASN.1 child too long") - return - } else if length > 0xffffff { - lenLen = 5 - lenByte = 0x80 | 4 - } else if length > 0xffff { - lenLen = 4 - lenByte = 0x80 | 3 - } else if length > 0xff { - lenLen = 3 - lenByte = 0x80 | 2 - } else if length > 0x7f { - lenLen = 2 - lenByte = 0x80 | 1 - } else { - lenLen = 1 - lenByte = uint8(length) - length = 0 - } - - // Insert the initial length byte, make space for successive length bytes, - // and adjust the offset. - child.result[child.offset] = lenByte - extraBytes := int(lenLen - 1) - if extraBytes != 0 { - child.add(make([]byte, extraBytes)...) - childStart := child.offset + child.pendingLenLen - copy(child.result[childStart+extraBytes:], child.result[childStart:]) - } - child.offset++ - child.pendingLenLen = extraBytes - } - - l := length - for i := child.pendingLenLen - 1; i >= 0; i-- { - child.result[child.offset+i] = uint8(l) - l >>= 8 - } - if l != 0 { - b.err = fmt.Errorf("cryptobyte: pending child length %d exceeds %d-byte length prefix", length, child.pendingLenLen) - return - } - - if b.fixedSize && &b.result[0] != &child.result[0] { - panic("cryptobyte: BuilderContinuation reallocated a fixed-size buffer") - } - - b.result = child.result -} - -func (b *Builder) add(bytes ...byte) { - if b.err != nil { - return - } - if b.child != nil { - panic("cryptobyte: attempted write while child is pending") - } - if len(b.result)+len(bytes) < len(bytes) { - b.err = errors.New("cryptobyte: length overflow") - } - if b.fixedSize && len(b.result)+len(bytes) > cap(b.result) { - b.err = errors.New("cryptobyte: Builder is exceeding its fixed-size buffer") - return - } - b.result = append(b.result, bytes...) -} - -// Unwrite rolls back n bytes written directly to the Builder. An attempt by a -// child builder passed to a continuation to unwrite bytes from its parent will -// panic. -func (b *Builder) Unwrite(n int) { - if b.err != nil { - return - } - if b.child != nil { - panic("cryptobyte: attempted unwrite while child is pending") - } - length := len(b.result) - b.pendingLenLen - b.offset - if length < 0 { - panic("cryptobyte: internal error") - } - if n > length { - panic("cryptobyte: attempted to unwrite more than was written") - } - b.result = b.result[:len(b.result)-n] -} - -// A MarshalingValue marshals itself into a Builder. -type MarshalingValue interface { - // Marshal is called by Builder.AddValue. It receives a pointer to a builder - // to marshal itself into. It may return an error that occurred during - // marshaling, such as unset or invalid values. - Marshal(b *Builder) error -} - -// AddValue calls Marshal on v, passing a pointer to the builder to append to. -// If Marshal returns an error, it is set on the Builder so that subsequent -// appends don't have an effect. -func (b *Builder) AddValue(v MarshalingValue) { - err := v.Marshal(b) - if err != nil { - b.err = err - } -} diff --git a/vendor/golang.org/x/crypto/cryptobyte/string.go b/vendor/golang.org/x/crypto/cryptobyte/string.go deleted file mode 100644 index 39bf98aeea..0000000000 --- a/vendor/golang.org/x/crypto/cryptobyte/string.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package cryptobyte contains types that help with parsing and constructing -// length-prefixed, binary messages, including ASN.1 DER. (The asn1 subpackage -// contains useful ASN.1 constants.) -// -// The String type is for parsing. It wraps a []byte slice and provides helper -// functions for consuming structures, value by value. -// -// The Builder type is for constructing messages. It providers helper functions -// for appending values and also for appending length-prefixed submessages – -// without having to worry about calculating the length prefix ahead of time. -// -// See the documentation and examples for the Builder and String types to get -// started. -package cryptobyte // import "golang.org/x/crypto/cryptobyte" - -// String represents a string of bytes. It provides methods for parsing -// fixed-length and length-prefixed values from it. -type String []byte - -// read advances a String by n bytes and returns them. If less than n bytes -// remain, it returns nil. -func (s *String) read(n int) []byte { - if len(*s) < n { - return nil - } - v := (*s)[:n] - *s = (*s)[n:] - return v -} - -// Skip advances the String by n byte and reports whether it was successful. -func (s *String) Skip(n int) bool { - return s.read(n) != nil -} - -// ReadUint8 decodes an 8-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint8(out *uint8) bool { - v := s.read(1) - if v == nil { - return false - } - *out = uint8(v[0]) - return true -} - -// ReadUint16 decodes a big-endian, 16-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint16(out *uint16) bool { - v := s.read(2) - if v == nil { - return false - } - *out = uint16(v[0])<<8 | uint16(v[1]) - return true -} - -// ReadUint24 decodes a big-endian, 24-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint24(out *uint32) bool { - v := s.read(3) - if v == nil { - return false - } - *out = uint32(v[0])<<16 | uint32(v[1])<<8 | uint32(v[2]) - return true -} - -// ReadUint32 decodes a big-endian, 32-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint32(out *uint32) bool { - v := s.read(4) - if v == nil { - return false - } - *out = uint32(v[0])<<24 | uint32(v[1])<<16 | uint32(v[2])<<8 | uint32(v[3]) - return true -} - -func (s *String) readUnsigned(out *uint32, length int) bool { - v := s.read(length) - if v == nil { - return false - } - var result uint32 - for i := 0; i < length; i++ { - result <<= 8 - result |= uint32(v[i]) - } - *out = result - return true -} - -func (s *String) readLengthPrefixed(lenLen int, outChild *String) bool { - lenBytes := s.read(lenLen) - if lenBytes == nil { - return false - } - var length uint32 - for _, b := range lenBytes { - length = length << 8 - length = length | uint32(b) - } - if int(length) < 0 { - // This currently cannot overflow because we read uint24 at most, but check - // anyway in case that changes in the future. - return false - } - v := s.read(int(length)) - if v == nil { - return false - } - *outChild = v - return true -} - -// ReadUint8LengthPrefixed reads the content of an 8-bit length-prefixed value -// into out and advances over it. It reports whether the read was successful. -func (s *String) ReadUint8LengthPrefixed(out *String) bool { - return s.readLengthPrefixed(1, out) -} - -// ReadUint16LengthPrefixed reads the content of a big-endian, 16-bit -// length-prefixed value into out and advances over it. It reports whether the -// read was successful. -func (s *String) ReadUint16LengthPrefixed(out *String) bool { - return s.readLengthPrefixed(2, out) -} - -// ReadUint24LengthPrefixed reads the content of a big-endian, 24-bit -// length-prefixed value into out and advances over it. It reports whether -// the read was successful. -func (s *String) ReadUint24LengthPrefixed(out *String) bool { - return s.readLengthPrefixed(3, out) -} - -// ReadBytes reads n bytes into out and advances over them. It reports -// whether the read was successful. -func (s *String) ReadBytes(out *[]byte, n int) bool { - v := s.read(n) - if v == nil { - return false - } - *out = v - return true -} - -// CopyBytes copies len(out) bytes into out and advances over them. It reports -// whether the copy operation was successful -func (s *String) CopyBytes(out []byte) bool { - n := len(out) - v := s.read(n) - if v == nil { - return false - } - return copy(out, v) == n -} - -// Empty reports whether the string does not contain any bytes. -func (s String) Empty() bool { - return len(s) == 0 -} diff --git a/vendor/golang.org/x/net/http/httpguts/guts.go b/vendor/golang.org/x/net/http/httpguts/guts.go deleted file mode 100644 index e6cd0ced39..0000000000 --- a/vendor/golang.org/x/net/http/httpguts/guts.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package httpguts provides functions implementing various details -// of the HTTP specification. -// -// This package is shared by the standard library (which vendors it) -// and x/net/http2. It comes with no API stability promise. -package httpguts - -import ( - "net/textproto" - "strings" -) - -// ValidTrailerHeader reports whether name is a valid header field name to appear -// in trailers. -// See RFC 7230, Section 4.1.2 -func ValidTrailerHeader(name string) bool { - name = textproto.CanonicalMIMEHeaderKey(name) - if strings.HasPrefix(name, "If-") || badTrailer[name] { - return false - } - return true -} - -var badTrailer = map[string]bool{ - "Authorization": true, - "Cache-Control": true, - "Connection": true, - "Content-Encoding": true, - "Content-Length": true, - "Content-Range": true, - "Content-Type": true, - "Expect": true, - "Host": true, - "Keep-Alive": true, - "Max-Forwards": true, - "Pragma": true, - "Proxy-Authenticate": true, - "Proxy-Authorization": true, - "Proxy-Connection": true, - "Range": true, - "Realm": true, - "Te": true, - "Trailer": true, - "Transfer-Encoding": true, - "Www-Authenticate": true, -} diff --git a/vendor/golang.org/x/net/http/httpguts/httplex.go b/vendor/golang.org/x/net/http/httpguts/httplex.go deleted file mode 100644 index e7de24ee64..0000000000 --- a/vendor/golang.org/x/net/http/httpguts/httplex.go +++ /dev/null @@ -1,346 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package httpguts - -import ( - "net" - "strings" - "unicode/utf8" - - "golang.org/x/net/idna" -) - -var isTokenTable = [127]bool{ - '!': true, - '#': true, - '$': true, - '%': true, - '&': true, - '\'': true, - '*': true, - '+': true, - '-': true, - '.': true, - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - 'A': true, - 'B': true, - 'C': true, - 'D': true, - 'E': true, - 'F': true, - 'G': true, - 'H': true, - 'I': true, - 'J': true, - 'K': true, - 'L': true, - 'M': true, - 'N': true, - 'O': true, - 'P': true, - 'Q': true, - 'R': true, - 'S': true, - 'T': true, - 'U': true, - 'W': true, - 'V': true, - 'X': true, - 'Y': true, - 'Z': true, - '^': true, - '_': true, - '`': true, - 'a': true, - 'b': true, - 'c': true, - 'd': true, - 'e': true, - 'f': true, - 'g': true, - 'h': true, - 'i': true, - 'j': true, - 'k': true, - 'l': true, - 'm': true, - 'n': true, - 'o': true, - 'p': true, - 'q': true, - 'r': true, - 's': true, - 't': true, - 'u': true, - 'v': true, - 'w': true, - 'x': true, - 'y': true, - 'z': true, - '|': true, - '~': true, -} - -func IsTokenRune(r rune) bool { - i := int(r) - return i < len(isTokenTable) && isTokenTable[i] -} - -func isNotToken(r rune) bool { - return !IsTokenRune(r) -} - -// HeaderValuesContainsToken reports whether any string in values -// contains the provided token, ASCII case-insensitively. -func HeaderValuesContainsToken(values []string, token string) bool { - for _, v := range values { - if headerValueContainsToken(v, token) { - return true - } - } - return false -} - -// isOWS reports whether b is an optional whitespace byte, as defined -// by RFC 7230 section 3.2.3. -func isOWS(b byte) bool { return b == ' ' || b == '\t' } - -// trimOWS returns x with all optional whitespace removes from the -// beginning and end. -func trimOWS(x string) string { - // TODO: consider using strings.Trim(x, " \t") instead, - // if and when it's fast enough. See issue 10292. - // But this ASCII-only code will probably always beat UTF-8 - // aware code. - for len(x) > 0 && isOWS(x[0]) { - x = x[1:] - } - for len(x) > 0 && isOWS(x[len(x)-1]) { - x = x[:len(x)-1] - } - return x -} - -// headerValueContainsToken reports whether v (assumed to be a -// 0#element, in the ABNF extension described in RFC 7230 section 7) -// contains token amongst its comma-separated tokens, ASCII -// case-insensitively. -func headerValueContainsToken(v string, token string) bool { - v = trimOWS(v) - if comma := strings.IndexByte(v, ','); comma != -1 { - return tokenEqual(trimOWS(v[:comma]), token) || headerValueContainsToken(v[comma+1:], token) - } - return tokenEqual(v, token) -} - -// lowerASCII returns the ASCII lowercase version of b. -func lowerASCII(b byte) byte { - if 'A' <= b && b <= 'Z' { - return b + ('a' - 'A') - } - return b -} - -// tokenEqual reports whether t1 and t2 are equal, ASCII case-insensitively. -func tokenEqual(t1, t2 string) bool { - if len(t1) != len(t2) { - return false - } - for i, b := range t1 { - if b >= utf8.RuneSelf { - // No UTF-8 or non-ASCII allowed in tokens. - return false - } - if lowerASCII(byte(b)) != lowerASCII(t2[i]) { - return false - } - } - return true -} - -// isLWS reports whether b is linear white space, according -// to http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 -// LWS = [CRLF] 1*( SP | HT ) -func isLWS(b byte) bool { return b == ' ' || b == '\t' } - -// isCTL reports whether b is a control byte, according -// to http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 -// CTL = -func isCTL(b byte) bool { - const del = 0x7f // a CTL - return b < ' ' || b == del -} - -// ValidHeaderFieldName reports whether v is a valid HTTP/1.x header name. -// HTTP/2 imposes the additional restriction that uppercase ASCII -// letters are not allowed. -// -// RFC 7230 says: -// header-field = field-name ":" OWS field-value OWS -// field-name = token -// token = 1*tchar -// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / -// "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA -func ValidHeaderFieldName(v string) bool { - if len(v) == 0 { - return false - } - for _, r := range v { - if !IsTokenRune(r) { - return false - } - } - return true -} - -// ValidHostHeader reports whether h is a valid host header. -func ValidHostHeader(h string) bool { - // The latest spec is actually this: - // - // http://tools.ietf.org/html/rfc7230#section-5.4 - // Host = uri-host [ ":" port ] - // - // Where uri-host is: - // http://tools.ietf.org/html/rfc3986#section-3.2.2 - // - // But we're going to be much more lenient for now and just - // search for any byte that's not a valid byte in any of those - // expressions. - for i := 0; i < len(h); i++ { - if !validHostByte[h[i]] { - return false - } - } - return true -} - -// See the validHostHeader comment. -var validHostByte = [256]bool{ - '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, - '8': true, '9': true, - - 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, - 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, - 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, - 'y': true, 'z': true, - - 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, - 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, - 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true, - 'Y': true, 'Z': true, - - '!': true, // sub-delims - '$': true, // sub-delims - '%': true, // pct-encoded (and used in IPv6 zones) - '&': true, // sub-delims - '(': true, // sub-delims - ')': true, // sub-delims - '*': true, // sub-delims - '+': true, // sub-delims - ',': true, // sub-delims - '-': true, // unreserved - '.': true, // unreserved - ':': true, // IPv6address + Host expression's optional port - ';': true, // sub-delims - '=': true, // sub-delims - '[': true, - '\'': true, // sub-delims - ']': true, - '_': true, // unreserved - '~': true, // unreserved -} - -// ValidHeaderFieldValue reports whether v is a valid "field-value" according to -// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 : -// -// message-header = field-name ":" [ field-value ] -// field-value = *( field-content | LWS ) -// field-content = -// -// http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 : -// -// TEXT = -// LWS = [CRLF] 1*( SP | HT ) -// CTL = -// -// RFC 7230 says: -// field-value = *( field-content / obs-fold ) -// obj-fold = N/A to http2, and deprecated -// field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] -// field-vchar = VCHAR / obs-text -// obs-text = %x80-FF -// VCHAR = "any visible [USASCII] character" -// -// http2 further says: "Similarly, HTTP/2 allows header field values -// that are not valid. While most of the values that can be encoded -// will not alter header field parsing, carriage return (CR, ASCII -// 0xd), line feed (LF, ASCII 0xa), and the zero character (NUL, ASCII -// 0x0) might be exploited by an attacker if they are translated -// verbatim. Any request or response that contains a character not -// permitted in a header field value MUST be treated as malformed -// (Section 8.1.2.6). Valid characters are defined by the -// field-content ABNF rule in Section 3.2 of [RFC7230]." -// -// This function does not (yet?) properly handle the rejection of -// strings that begin or end with SP or HTAB. -func ValidHeaderFieldValue(v string) bool { - for i := 0; i < len(v); i++ { - b := v[i] - if isCTL(b) && !isLWS(b) { - return false - } - } - return true -} - -func isASCII(s string) bool { - for i := 0; i < len(s); i++ { - if s[i] >= utf8.RuneSelf { - return false - } - } - return true -} - -// PunycodeHostPort returns the IDNA Punycode version -// of the provided "host" or "host:port" string. -func PunycodeHostPort(v string) (string, error) { - if isASCII(v) { - return v, nil - } - - host, port, err := net.SplitHostPort(v) - if err != nil { - // The input 'v' argument was just a "host" argument, - // without a port. This error should not be returned - // to the caller. - host = v - port = "" - } - host, err = idna.ToASCII(host) - if err != nil { - // Non-UTF-8? Not representable in Punycode, in any - // case. - return "", err - } - if port == "" { - return host, nil - } - return net.JoinHostPort(host, port), nil -} diff --git a/vendor/golang.org/x/net/ipv6/batch.go b/vendor/golang.org/x/net/ipv6/batch.go deleted file mode 100644 index 10d6492451..0000000000 --- a/vendor/golang.org/x/net/ipv6/batch.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 - -package ipv6 - -import ( - "net" - "runtime" - - "golang.org/x/net/internal/socket" -) - -// BUG(mikio): On Windows, the ReadBatch and WriteBatch methods of -// PacketConn are not implemented. - -// A Message represents an IO message. -// -// type Message struct { -// Buffers [][]byte -// OOB []byte -// Addr net.Addr -// N int -// NN int -// Flags int -// } -// -// The Buffers fields represents a list of contiguous buffers, which -// can be used for vectored IO, for example, putting a header and a -// payload in each slice. -// When writing, the Buffers field must contain at least one byte to -// write. -// When reading, the Buffers field will always contain a byte to read. -// -// The OOB field contains protocol-specific control or miscellaneous -// ancillary data known as out-of-band data. -// It can be nil when not required. -// -// The Addr field specifies a destination address when writing. -// It can be nil when the underlying protocol of the endpoint uses -// connection-oriented communication. -// After a successful read, it may contain the source address on the -// received packet. -// -// The N field indicates the number of bytes read or written from/to -// Buffers. -// -// The NN field indicates the number of bytes read or written from/to -// OOB. -// -// The Flags field contains protocol-specific information on the -// received message. -type Message = socket.Message - -// ReadBatch reads a batch of messages. -// -// The provided flags is a set of platform-dependent flags, such as -// syscall.MSG_PEEK. -// -// On a successful read it returns the number of messages received, up -// to len(ms). -// -// On Linux, a batch read will be optimized. -// On other platforms, this method will read only a single message. -func (c *payloadHandler) ReadBatch(ms []Message, flags int) (int, error) { - if !c.ok() { - return 0, errInvalidConn - } - switch runtime.GOOS { - case "linux": - n, err := c.RecvMsgs([]socket.Message(ms), flags) - if err != nil { - err = &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} - } - return n, err - default: - n := 1 - err := c.RecvMsg(&ms[0], flags) - if err != nil { - n = 0 - err = &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} - } - return n, err - } -} - -// WriteBatch writes a batch of messages. -// -// The provided flags is a set of platform-dependent flags, such as -// syscall.MSG_DONTROUTE. -// -// It returns the number of messages written on a successful write. -// -// On Linux, a batch write will be optimized. -// On other platforms, this method will write only a single message. -func (c *payloadHandler) WriteBatch(ms []Message, flags int) (int, error) { - if !c.ok() { - return 0, errInvalidConn - } - switch runtime.GOOS { - case "linux": - n, err := c.SendMsgs([]socket.Message(ms), flags) - if err != nil { - err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} - } - return n, err - default: - n := 1 - err := c.SendMsg(&ms[0], flags) - if err != nil { - n = 0 - err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} - } - return n, err - } -} diff --git a/vendor/golang.org/x/net/ipv6/control.go b/vendor/golang.org/x/net/ipv6/control.go deleted file mode 100644 index 2da644413b..0000000000 --- a/vendor/golang.org/x/net/ipv6/control.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "fmt" - "net" - "sync" - - "golang.org/x/net/internal/iana" - "golang.org/x/net/internal/socket" -) - -// Note that RFC 3542 obsoletes RFC 2292 but OS X Snow Leopard and the -// former still support RFC 2292 only. Please be aware that almost -// all protocol implementations prohibit using a combination of RFC -// 2292 and RFC 3542 for some practical reasons. - -type rawOpt struct { - sync.RWMutex - cflags ControlFlags -} - -func (c *rawOpt) set(f ControlFlags) { c.cflags |= f } -func (c *rawOpt) clear(f ControlFlags) { c.cflags &^= f } -func (c *rawOpt) isset(f ControlFlags) bool { return c.cflags&f != 0 } - -// A ControlFlags represents per packet basis IP-level socket option -// control flags. -type ControlFlags uint - -const ( - FlagTrafficClass ControlFlags = 1 << iota // pass the traffic class on the received packet - FlagHopLimit // pass the hop limit on the received packet - FlagSrc // pass the source address on the received packet - FlagDst // pass the destination address on the received packet - FlagInterface // pass the interface index on the received packet - FlagPathMTU // pass the path MTU on the received packet path -) - -const flagPacketInfo = FlagDst | FlagInterface - -// A ControlMessage represents per packet basis IP-level socket -// options. -type ControlMessage struct { - // Receiving socket options: SetControlMessage allows to - // receive the options from the protocol stack using ReadFrom - // method of PacketConn. - // - // Specifying socket options: ControlMessage for WriteTo - // method of PacketConn allows to send the options to the - // protocol stack. - // - TrafficClass int // traffic class, must be 1 <= value <= 255 when specifying - HopLimit int // hop limit, must be 1 <= value <= 255 when specifying - Src net.IP // source address, specifying only - Dst net.IP // destination address, receiving only - IfIndex int // interface index, must be 1 <= value when specifying - NextHop net.IP // next hop address, specifying only - MTU int // path MTU, receiving only -} - -func (cm *ControlMessage) String() string { - if cm == nil { - return "" - } - return fmt.Sprintf("tclass=%#x hoplim=%d src=%v dst=%v ifindex=%d nexthop=%v mtu=%d", cm.TrafficClass, cm.HopLimit, cm.Src, cm.Dst, cm.IfIndex, cm.NextHop, cm.MTU) -} - -// Marshal returns the binary encoding of cm. -func (cm *ControlMessage) Marshal() []byte { - if cm == nil { - return nil - } - var l int - tclass := false - if ctlOpts[ctlTrafficClass].name > 0 && cm.TrafficClass > 0 { - tclass = true - l += socket.ControlMessageSpace(ctlOpts[ctlTrafficClass].length) - } - hoplimit := false - if ctlOpts[ctlHopLimit].name > 0 && cm.HopLimit > 0 { - hoplimit = true - l += socket.ControlMessageSpace(ctlOpts[ctlHopLimit].length) - } - pktinfo := false - if ctlOpts[ctlPacketInfo].name > 0 && (cm.Src.To16() != nil && cm.Src.To4() == nil || cm.IfIndex > 0) { - pktinfo = true - l += socket.ControlMessageSpace(ctlOpts[ctlPacketInfo].length) - } - nexthop := false - if ctlOpts[ctlNextHop].name > 0 && cm.NextHop.To16() != nil && cm.NextHop.To4() == nil { - nexthop = true - l += socket.ControlMessageSpace(ctlOpts[ctlNextHop].length) - } - var b []byte - if l > 0 { - b = make([]byte, l) - bb := b - if tclass { - bb = ctlOpts[ctlTrafficClass].marshal(bb, cm) - } - if hoplimit { - bb = ctlOpts[ctlHopLimit].marshal(bb, cm) - } - if pktinfo { - bb = ctlOpts[ctlPacketInfo].marshal(bb, cm) - } - if nexthop { - bb = ctlOpts[ctlNextHop].marshal(bb, cm) - } - } - return b -} - -// Parse parses b as a control message and stores the result in cm. -func (cm *ControlMessage) Parse(b []byte) error { - ms, err := socket.ControlMessage(b).Parse() - if err != nil { - return err - } - for _, m := range ms { - lvl, typ, l, err := m.ParseHeader() - if err != nil { - return err - } - if lvl != iana.ProtocolIPv6 { - continue - } - switch { - case typ == ctlOpts[ctlTrafficClass].name && l >= ctlOpts[ctlTrafficClass].length: - ctlOpts[ctlTrafficClass].parse(cm, m.Data(l)) - case typ == ctlOpts[ctlHopLimit].name && l >= ctlOpts[ctlHopLimit].length: - ctlOpts[ctlHopLimit].parse(cm, m.Data(l)) - case typ == ctlOpts[ctlPacketInfo].name && l >= ctlOpts[ctlPacketInfo].length: - ctlOpts[ctlPacketInfo].parse(cm, m.Data(l)) - case typ == ctlOpts[ctlPathMTU].name && l >= ctlOpts[ctlPathMTU].length: - ctlOpts[ctlPathMTU].parse(cm, m.Data(l)) - } - } - return nil -} - -// NewControlMessage returns a new control message. -// -// The returned message is large enough for options specified by cf. -func NewControlMessage(cf ControlFlags) []byte { - opt := rawOpt{cflags: cf} - var l int - if opt.isset(FlagTrafficClass) && ctlOpts[ctlTrafficClass].name > 0 { - l += socket.ControlMessageSpace(ctlOpts[ctlTrafficClass].length) - } - if opt.isset(FlagHopLimit) && ctlOpts[ctlHopLimit].name > 0 { - l += socket.ControlMessageSpace(ctlOpts[ctlHopLimit].length) - } - if opt.isset(flagPacketInfo) && ctlOpts[ctlPacketInfo].name > 0 { - l += socket.ControlMessageSpace(ctlOpts[ctlPacketInfo].length) - } - if opt.isset(FlagPathMTU) && ctlOpts[ctlPathMTU].name > 0 { - l += socket.ControlMessageSpace(ctlOpts[ctlPathMTU].length) - } - var b []byte - if l > 0 { - b = make([]byte, l) - } - return b -} - -// Ancillary data socket options -const ( - ctlTrafficClass = iota // header field - ctlHopLimit // header field - ctlPacketInfo // inbound or outbound packet path - ctlNextHop // nexthop - ctlPathMTU // path mtu - ctlMax -) - -// A ctlOpt represents a binding for ancillary data socket option. -type ctlOpt struct { - name int // option name, must be equal or greater than 1 - length int // option length - marshal func([]byte, *ControlMessage) []byte - parse func(*ControlMessage, []byte) -} diff --git a/vendor/golang.org/x/net/ipv6/control_rfc2292_unix.go b/vendor/golang.org/x/net/ipv6/control_rfc2292_unix.go deleted file mode 100644 index 9fd9eb15e3..0000000000 --- a/vendor/golang.org/x/net/ipv6/control_rfc2292_unix.go +++ /dev/null @@ -1,48 +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 darwin - -package ipv6 - -import ( - "unsafe" - - "golang.org/x/net/internal/iana" - "golang.org/x/net/internal/socket" -) - -func marshal2292HopLimit(b []byte, cm *ControlMessage) []byte { - m := socket.ControlMessage(b) - m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_2292HOPLIMIT, 4) - if cm != nil { - socket.NativeEndian.PutUint32(m.Data(4), uint32(cm.HopLimit)) - } - return m.Next(4) -} - -func marshal2292PacketInfo(b []byte, cm *ControlMessage) []byte { - m := socket.ControlMessage(b) - m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_2292PKTINFO, sizeofInet6Pktinfo) - if cm != nil { - pi := (*inet6Pktinfo)(unsafe.Pointer(&m.Data(sizeofInet6Pktinfo)[0])) - if ip := cm.Src.To16(); ip != nil && ip.To4() == nil { - copy(pi.Addr[:], ip) - } - if cm.IfIndex > 0 { - pi.setIfindex(cm.IfIndex) - } - } - return m.Next(sizeofInet6Pktinfo) -} - -func marshal2292NextHop(b []byte, cm *ControlMessage) []byte { - m := socket.ControlMessage(b) - m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_2292NEXTHOP, sizeofSockaddrInet6) - if cm != nil { - sa := (*sockaddrInet6)(unsafe.Pointer(&m.Data(sizeofSockaddrInet6)[0])) - sa.setSockaddr(cm.NextHop, cm.IfIndex) - } - return m.Next(sizeofSockaddrInet6) -} diff --git a/vendor/golang.org/x/net/ipv6/control_rfc3542_unix.go b/vendor/golang.org/x/net/ipv6/control_rfc3542_unix.go deleted file mode 100644 index eec529c205..0000000000 --- a/vendor/golang.org/x/net/ipv6/control_rfc3542_unix.go +++ /dev/null @@ -1,94 +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 darwin dragonfly freebsd linux netbsd openbsd solaris - -package ipv6 - -import ( - "net" - "unsafe" - - "golang.org/x/net/internal/iana" - "golang.org/x/net/internal/socket" -) - -func marshalTrafficClass(b []byte, cm *ControlMessage) []byte { - m := socket.ControlMessage(b) - m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_TCLASS, 4) - if cm != nil { - socket.NativeEndian.PutUint32(m.Data(4), uint32(cm.TrafficClass)) - } - return m.Next(4) -} - -func parseTrafficClass(cm *ControlMessage, b []byte) { - cm.TrafficClass = int(socket.NativeEndian.Uint32(b[:4])) -} - -func marshalHopLimit(b []byte, cm *ControlMessage) []byte { - m := socket.ControlMessage(b) - m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_HOPLIMIT, 4) - if cm != nil { - socket.NativeEndian.PutUint32(m.Data(4), uint32(cm.HopLimit)) - } - return m.Next(4) -} - -func parseHopLimit(cm *ControlMessage, b []byte) { - cm.HopLimit = int(socket.NativeEndian.Uint32(b[:4])) -} - -func marshalPacketInfo(b []byte, cm *ControlMessage) []byte { - m := socket.ControlMessage(b) - m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_PKTINFO, sizeofInet6Pktinfo) - if cm != nil { - pi := (*inet6Pktinfo)(unsafe.Pointer(&m.Data(sizeofInet6Pktinfo)[0])) - if ip := cm.Src.To16(); ip != nil && ip.To4() == nil { - copy(pi.Addr[:], ip) - } - if cm.IfIndex > 0 { - pi.setIfindex(cm.IfIndex) - } - } - return m.Next(sizeofInet6Pktinfo) -} - -func parsePacketInfo(cm *ControlMessage, b []byte) { - pi := (*inet6Pktinfo)(unsafe.Pointer(&b[0])) - if len(cm.Dst) < net.IPv6len { - cm.Dst = make(net.IP, net.IPv6len) - } - copy(cm.Dst, pi.Addr[:]) - cm.IfIndex = int(pi.Ifindex) -} - -func marshalNextHop(b []byte, cm *ControlMessage) []byte { - m := socket.ControlMessage(b) - m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_NEXTHOP, sizeofSockaddrInet6) - if cm != nil { - sa := (*sockaddrInet6)(unsafe.Pointer(&m.Data(sizeofSockaddrInet6)[0])) - sa.setSockaddr(cm.NextHop, cm.IfIndex) - } - return m.Next(sizeofSockaddrInet6) -} - -func parseNextHop(cm *ControlMessage, b []byte) { -} - -func marshalPathMTU(b []byte, cm *ControlMessage) []byte { - m := socket.ControlMessage(b) - m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_PATHMTU, sizeofIPv6Mtuinfo) - return m.Next(sizeofIPv6Mtuinfo) -} - -func parsePathMTU(cm *ControlMessage, b []byte) { - mi := (*ipv6Mtuinfo)(unsafe.Pointer(&b[0])) - if len(cm.Dst) < net.IPv6len { - cm.Dst = make(net.IP, net.IPv6len) - } - copy(cm.Dst, mi.Addr.Addr[:]) - cm.IfIndex = int(mi.Addr.Scope_id) - cm.MTU = int(mi.Mtu) -} diff --git a/vendor/golang.org/x/net/ipv6/control_stub.go b/vendor/golang.org/x/net/ipv6/control_stub.go deleted file mode 100644 index a045f28f74..0000000000 --- a/vendor/golang.org/x/net/ipv6/control_stub.go +++ /dev/null @@ -1,13 +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 !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows - -package ipv6 - -import "golang.org/x/net/internal/socket" - -func setControlMessage(c *socket.Conn, opt *rawOpt, cf ControlFlags, on bool) error { - return errOpNoSupport -} diff --git a/vendor/golang.org/x/net/ipv6/control_unix.go b/vendor/golang.org/x/net/ipv6/control_unix.go deleted file mode 100644 index 66515060a8..0000000000 --- a/vendor/golang.org/x/net/ipv6/control_unix.go +++ /dev/null @@ -1,55 +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 darwin dragonfly freebsd linux netbsd openbsd solaris - -package ipv6 - -import "golang.org/x/net/internal/socket" - -func setControlMessage(c *socket.Conn, opt *rawOpt, cf ControlFlags, on bool) error { - opt.Lock() - defer opt.Unlock() - if so, ok := sockOpts[ssoReceiveTrafficClass]; ok && cf&FlagTrafficClass != 0 { - if err := so.SetInt(c, boolint(on)); err != nil { - return err - } - if on { - opt.set(FlagTrafficClass) - } else { - opt.clear(FlagTrafficClass) - } - } - if so, ok := sockOpts[ssoReceiveHopLimit]; ok && cf&FlagHopLimit != 0 { - if err := so.SetInt(c, boolint(on)); err != nil { - return err - } - if on { - opt.set(FlagHopLimit) - } else { - opt.clear(FlagHopLimit) - } - } - if so, ok := sockOpts[ssoReceivePacketInfo]; ok && cf&flagPacketInfo != 0 { - if err := so.SetInt(c, boolint(on)); err != nil { - return err - } - if on { - opt.set(cf & flagPacketInfo) - } else { - opt.clear(cf & flagPacketInfo) - } - } - if so, ok := sockOpts[ssoReceivePathMTU]; ok && cf&FlagPathMTU != 0 { - if err := so.SetInt(c, boolint(on)); err != nil { - return err - } - if on { - opt.set(FlagPathMTU) - } else { - opt.clear(FlagPathMTU) - } - } - return nil -} diff --git a/vendor/golang.org/x/net/ipv6/control_windows.go b/vendor/golang.org/x/net/ipv6/control_windows.go deleted file mode 100644 index ef2563b3fc..0000000000 --- a/vendor/golang.org/x/net/ipv6/control_windows.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "syscall" - - "golang.org/x/net/internal/socket" -) - -func setControlMessage(c *socket.Conn, opt *rawOpt, cf ControlFlags, on bool) error { - // TODO(mikio): implement this - return syscall.EWINDOWS -} diff --git a/vendor/golang.org/x/net/ipv6/dgramopt.go b/vendor/golang.org/x/net/ipv6/dgramopt.go deleted file mode 100644 index eea4fde256..0000000000 --- a/vendor/golang.org/x/net/ipv6/dgramopt.go +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "net" - - "golang.org/x/net/bpf" -) - -// MulticastHopLimit returns the hop limit field value for outgoing -// multicast packets. -func (c *dgramOpt) MulticastHopLimit() (int, error) { - if !c.ok() { - return 0, errInvalidConn - } - so, ok := sockOpts[ssoMulticastHopLimit] - if !ok { - return 0, errOpNoSupport - } - return so.GetInt(c.Conn) -} - -// SetMulticastHopLimit sets the hop limit field value for future -// outgoing multicast packets. -func (c *dgramOpt) SetMulticastHopLimit(hoplim int) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoMulticastHopLimit] - if !ok { - return errOpNoSupport - } - return so.SetInt(c.Conn, hoplim) -} - -// MulticastInterface returns the default interface for multicast -// packet transmissions. -func (c *dgramOpt) MulticastInterface() (*net.Interface, error) { - if !c.ok() { - return nil, errInvalidConn - } - so, ok := sockOpts[ssoMulticastInterface] - if !ok { - return nil, errOpNoSupport - } - return so.getMulticastInterface(c.Conn) -} - -// SetMulticastInterface sets the default interface for future -// multicast packet transmissions. -func (c *dgramOpt) SetMulticastInterface(ifi *net.Interface) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoMulticastInterface] - if !ok { - return errOpNoSupport - } - return so.setMulticastInterface(c.Conn, ifi) -} - -// MulticastLoopback reports whether transmitted multicast packets -// should be copied and send back to the originator. -func (c *dgramOpt) MulticastLoopback() (bool, error) { - if !c.ok() { - return false, errInvalidConn - } - so, ok := sockOpts[ssoMulticastLoopback] - if !ok { - return false, errOpNoSupport - } - on, err := so.GetInt(c.Conn) - if err != nil { - return false, err - } - return on == 1, nil -} - -// SetMulticastLoopback sets whether transmitted multicast packets -// should be copied and send back to the originator. -func (c *dgramOpt) SetMulticastLoopback(on bool) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoMulticastLoopback] - if !ok { - return errOpNoSupport - } - return so.SetInt(c.Conn, boolint(on)) -} - -// JoinGroup joins the group address group on the interface ifi. -// By default all sources that can cast data to group are accepted. -// It's possible to mute and unmute data transmission from a specific -// source by using ExcludeSourceSpecificGroup and -// IncludeSourceSpecificGroup. -// JoinGroup uses the system assigned multicast interface when ifi is -// nil, although this is not recommended because the assignment -// depends on platforms and sometimes it might require routing -// configuration. -func (c *dgramOpt) JoinGroup(ifi *net.Interface, group net.Addr) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoJoinGroup] - if !ok { - return errOpNoSupport - } - grp := netAddrToIP16(group) - if grp == nil { - return errMissingAddress - } - return so.setGroup(c.Conn, ifi, grp) -} - -// LeaveGroup leaves the group address group on the interface ifi -// regardless of whether the group is any-source group or -// source-specific group. -func (c *dgramOpt) LeaveGroup(ifi *net.Interface, group net.Addr) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoLeaveGroup] - if !ok { - return errOpNoSupport - } - grp := netAddrToIP16(group) - if grp == nil { - return errMissingAddress - } - return so.setGroup(c.Conn, ifi, grp) -} - -// JoinSourceSpecificGroup joins the source-specific group comprising -// group and source on the interface ifi. -// JoinSourceSpecificGroup uses the system assigned multicast -// interface when ifi is nil, although this is not recommended because -// the assignment depends on platforms and sometimes it might require -// routing configuration. -func (c *dgramOpt) JoinSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoJoinSourceGroup] - if !ok { - return errOpNoSupport - } - grp := netAddrToIP16(group) - if grp == nil { - return errMissingAddress - } - src := netAddrToIP16(source) - if src == nil { - return errMissingAddress - } - return so.setSourceGroup(c.Conn, ifi, grp, src) -} - -// LeaveSourceSpecificGroup leaves the source-specific group on the -// interface ifi. -func (c *dgramOpt) LeaveSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoLeaveSourceGroup] - if !ok { - return errOpNoSupport - } - grp := netAddrToIP16(group) - if grp == nil { - return errMissingAddress - } - src := netAddrToIP16(source) - if src == nil { - return errMissingAddress - } - return so.setSourceGroup(c.Conn, ifi, grp, src) -} - -// ExcludeSourceSpecificGroup excludes the source-specific group from -// the already joined any-source groups by JoinGroup on the interface -// ifi. -func (c *dgramOpt) ExcludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoBlockSourceGroup] - if !ok { - return errOpNoSupport - } - grp := netAddrToIP16(group) - if grp == nil { - return errMissingAddress - } - src := netAddrToIP16(source) - if src == nil { - return errMissingAddress - } - return so.setSourceGroup(c.Conn, ifi, grp, src) -} - -// IncludeSourceSpecificGroup includes the excluded source-specific -// group by ExcludeSourceSpecificGroup again on the interface ifi. -func (c *dgramOpt) IncludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoUnblockSourceGroup] - if !ok { - return errOpNoSupport - } - grp := netAddrToIP16(group) - if grp == nil { - return errMissingAddress - } - src := netAddrToIP16(source) - if src == nil { - return errMissingAddress - } - return so.setSourceGroup(c.Conn, ifi, grp, src) -} - -// Checksum reports whether the kernel will compute, store or verify a -// checksum for both incoming and outgoing packets. If on is true, it -// returns an offset in bytes into the data of where the checksum -// field is located. -func (c *dgramOpt) Checksum() (on bool, offset int, err error) { - if !c.ok() { - return false, 0, errInvalidConn - } - so, ok := sockOpts[ssoChecksum] - if !ok { - return false, 0, errOpNoSupport - } - offset, err = so.GetInt(c.Conn) - if err != nil { - return false, 0, err - } - if offset < 0 { - return false, 0, nil - } - return true, offset, nil -} - -// SetChecksum enables the kernel checksum processing. If on is ture, -// the offset should be an offset in bytes into the data of where the -// checksum field is located. -func (c *dgramOpt) SetChecksum(on bool, offset int) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoChecksum] - if !ok { - return errOpNoSupport - } - if !on { - offset = -1 - } - return so.SetInt(c.Conn, offset) -} - -// ICMPFilter returns an ICMP filter. -func (c *dgramOpt) ICMPFilter() (*ICMPFilter, error) { - if !c.ok() { - return nil, errInvalidConn - } - so, ok := sockOpts[ssoICMPFilter] - if !ok { - return nil, errOpNoSupport - } - return so.getICMPFilter(c.Conn) -} - -// SetICMPFilter deploys the ICMP filter. -func (c *dgramOpt) SetICMPFilter(f *ICMPFilter) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoICMPFilter] - if !ok { - return errOpNoSupport - } - return so.setICMPFilter(c.Conn, f) -} - -// SetBPF attaches a BPF program to the connection. -// -// Only supported on Linux. -func (c *dgramOpt) SetBPF(filter []bpf.RawInstruction) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoAttachFilter] - if !ok { - return errOpNoSupport - } - return so.setBPF(c.Conn, filter) -} diff --git a/vendor/golang.org/x/net/ipv6/doc.go b/vendor/golang.org/x/net/ipv6/doc.go deleted file mode 100644 index e0be9d50d7..0000000000 --- a/vendor/golang.org/x/net/ipv6/doc.go +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ipv6 implements IP-level socket options for the Internet -// Protocol version 6. -// -// The package provides IP-level socket options that allow -// manipulation of IPv6 facilities. -// -// The IPv6 protocol is defined in RFC 8200. -// Socket interface extensions are defined in RFC 3493, RFC 3542 and -// RFC 3678. -// MLDv1 and MLDv2 are defined in RFC 2710 and RFC 3810. -// Source-specific multicast is defined in RFC 4607. -// -// On Darwin, this package requires OS X Mavericks version 10.9 or -// above, or equivalent. -// -// -// Unicasting -// -// The options for unicasting are available for net.TCPConn, -// net.UDPConn and net.IPConn which are created as network connections -// that use the IPv6 transport. When a single TCP connection carrying -// a data flow of multiple packets needs to indicate the flow is -// important, Conn is used to set the traffic class field on the IPv6 -// header for each packet. -// -// ln, err := net.Listen("tcp6", "[::]:1024") -// if err != nil { -// // error handling -// } -// defer ln.Close() -// for { -// c, err := ln.Accept() -// if err != nil { -// // error handling -// } -// go func(c net.Conn) { -// defer c.Close() -// -// The outgoing packets will be labeled DiffServ assured forwarding -// class 1 low drop precedence, known as AF11 packets. -// -// if err := ipv6.NewConn(c).SetTrafficClass(0x28); err != nil { -// // error handling -// } -// if _, err := c.Write(data); err != nil { -// // error handling -// } -// }(c) -// } -// -// -// Multicasting -// -// The options for multicasting are available for net.UDPConn and -// net.IPConn which are created as network connections that use the -// IPv6 transport. A few network facilities must be prepared before -// you begin multicasting, at a minimum joining network interfaces and -// multicast groups. -// -// en0, err := net.InterfaceByName("en0") -// if err != nil { -// // error handling -// } -// en1, err := net.InterfaceByIndex(911) -// if err != nil { -// // error handling -// } -// group := net.ParseIP("ff02::114") -// -// First, an application listens to an appropriate address with an -// appropriate service port. -// -// c, err := net.ListenPacket("udp6", "[::]:1024") -// if err != nil { -// // error handling -// } -// defer c.Close() -// -// Second, the application joins multicast groups, starts listening to -// the groups on the specified network interfaces. Note that the -// service port for transport layer protocol does not matter with this -// operation as joining groups affects only network and link layer -// protocols, such as IPv6 and Ethernet. -// -// p := ipv6.NewPacketConn(c) -// if err := p.JoinGroup(en0, &net.UDPAddr{IP: group}); err != nil { -// // error handling -// } -// if err := p.JoinGroup(en1, &net.UDPAddr{IP: group}); err != nil { -// // error handling -// } -// -// The application might set per packet control message transmissions -// between the protocol stack within the kernel. When the application -// needs a destination address on an incoming packet, -// SetControlMessage of PacketConn is used to enable control message -// transmissions. -// -// if err := p.SetControlMessage(ipv6.FlagDst, true); err != nil { -// // error handling -// } -// -// The application could identify whether the received packets are -// of interest by using the control message that contains the -// destination address of the received packet. -// -// b := make([]byte, 1500) -// for { -// n, rcm, src, err := p.ReadFrom(b) -// if err != nil { -// // error handling -// } -// if rcm.Dst.IsMulticast() { -// if rcm.Dst.Equal(group) { -// // joined group, do something -// } else { -// // unknown group, discard -// continue -// } -// } -// -// The application can also send both unicast and multicast packets. -// -// p.SetTrafficClass(0x0) -// p.SetHopLimit(16) -// if _, err := p.WriteTo(data[:n], nil, src); err != nil { -// // error handling -// } -// dst := &net.UDPAddr{IP: group, Port: 1024} -// wcm := ipv6.ControlMessage{TrafficClass: 0xe0, HopLimit: 1} -// for _, ifi := range []*net.Interface{en0, en1} { -// wcm.IfIndex = ifi.Index -// if _, err := p.WriteTo(data[:n], &wcm, dst); err != nil { -// // error handling -// } -// } -// } -// -// -// More multicasting -// -// An application that uses PacketConn may join multiple multicast -// groups. For example, a UDP listener with port 1024 might join two -// different groups across over two different network interfaces by -// using: -// -// c, err := net.ListenPacket("udp6", "[::]:1024") -// if err != nil { -// // error handling -// } -// defer c.Close() -// p := ipv6.NewPacketConn(c) -// if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::1:114")}); err != nil { -// // error handling -// } -// if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::2:114")}); err != nil { -// // error handling -// } -// if err := p.JoinGroup(en1, &net.UDPAddr{IP: net.ParseIP("ff02::2:114")}); err != nil { -// // error handling -// } -// -// It is possible for multiple UDP listeners that listen on the same -// UDP port to join the same multicast group. The net package will -// provide a socket that listens to a wildcard address with reusable -// UDP port when an appropriate multicast address prefix is passed to -// the net.ListenPacket or net.ListenUDP. -// -// c1, err := net.ListenPacket("udp6", "[ff02::]:1024") -// if err != nil { -// // error handling -// } -// defer c1.Close() -// c2, err := net.ListenPacket("udp6", "[ff02::]:1024") -// if err != nil { -// // error handling -// } -// defer c2.Close() -// p1 := ipv6.NewPacketConn(c1) -// if err := p1.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil { -// // error handling -// } -// p2 := ipv6.NewPacketConn(c2) -// if err := p2.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil { -// // error handling -// } -// -// Also it is possible for the application to leave or rejoin a -// multicast group on the network interface. -// -// if err := p.LeaveGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil { -// // error handling -// } -// if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff01::114")}); err != nil { -// // error handling -// } -// -// -// Source-specific multicasting -// -// An application that uses PacketConn on MLDv2 supported platform is -// able to join source-specific multicast groups. -// The application may use JoinSourceSpecificGroup and -// LeaveSourceSpecificGroup for the operation known as "include" mode, -// -// ssmgroup := net.UDPAddr{IP: net.ParseIP("ff32::8000:9")} -// ssmsource := net.UDPAddr{IP: net.ParseIP("fe80::cafe")} -// if err := p.JoinSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil { -// // error handling -// } -// if err := p.LeaveSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil { -// // error handling -// } -// -// or JoinGroup, ExcludeSourceSpecificGroup, -// IncludeSourceSpecificGroup and LeaveGroup for the operation known -// as "exclude" mode. -// -// exclsource := net.UDPAddr{IP: net.ParseIP("fe80::dead")} -// if err := p.JoinGroup(en0, &ssmgroup); err != nil { -// // error handling -// } -// if err := p.ExcludeSourceSpecificGroup(en0, &ssmgroup, &exclsource); err != nil { -// // error handling -// } -// if err := p.LeaveGroup(en0, &ssmgroup); err != nil { -// // error handling -// } -// -// Note that it depends on each platform implementation what happens -// when an application which runs on MLDv2 unsupported platform uses -// JoinSourceSpecificGroup and LeaveSourceSpecificGroup. -// In general the platform tries to fall back to conversations using -// MLDv1 and starts to listen to multicast traffic. -// In the fallback case, ExcludeSourceSpecificGroup and -// IncludeSourceSpecificGroup may return an error. -package ipv6 // import "golang.org/x/net/ipv6" - -// BUG(mikio): This package is not implemented on JS, NaCl and Plan 9. diff --git a/vendor/golang.org/x/net/ipv6/endpoint.go b/vendor/golang.org/x/net/ipv6/endpoint.go deleted file mode 100644 index 9325756396..0000000000 --- a/vendor/golang.org/x/net/ipv6/endpoint.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "net" - "time" - - "golang.org/x/net/internal/socket" -) - -// BUG(mikio): On Windows, the JoinSourceSpecificGroup, -// LeaveSourceSpecificGroup, ExcludeSourceSpecificGroup and -// IncludeSourceSpecificGroup methods of PacketConn are not -// implemented. - -// A Conn represents a network endpoint that uses IPv6 transport. -// It allows to set basic IP-level socket options such as traffic -// class and hop limit. -type Conn struct { - genericOpt -} - -type genericOpt struct { - *socket.Conn -} - -func (c *genericOpt) ok() bool { return c != nil && c.Conn != nil } - -// PathMTU returns a path MTU value for the destination associated -// with the endpoint. -func (c *Conn) PathMTU() (int, error) { - if !c.ok() { - return 0, errInvalidConn - } - so, ok := sockOpts[ssoPathMTU] - if !ok { - return 0, errOpNoSupport - } - _, mtu, err := so.getMTUInfo(c.Conn) - if err != nil { - return 0, err - } - return mtu, nil -} - -// NewConn returns a new Conn. -func NewConn(c net.Conn) *Conn { - cc, _ := socket.NewConn(c) - return &Conn{ - genericOpt: genericOpt{Conn: cc}, - } -} - -// A PacketConn represents a packet network endpoint that uses IPv6 -// transport. It is used to control several IP-level socket options -// including IPv6 header manipulation. It also provides datagram -// based network I/O methods specific to the IPv6 and higher layer -// protocols such as OSPF, GRE, and UDP. -type PacketConn struct { - genericOpt - dgramOpt - payloadHandler -} - -type dgramOpt struct { - *socket.Conn -} - -func (c *dgramOpt) ok() bool { return c != nil && c.Conn != nil } - -// SetControlMessage allows to receive the per packet basis IP-level -// socket options. -func (c *PacketConn) SetControlMessage(cf ControlFlags, on bool) error { - if !c.payloadHandler.ok() { - return errInvalidConn - } - return setControlMessage(c.dgramOpt.Conn, &c.payloadHandler.rawOpt, cf, on) -} - -// SetDeadline sets the read and write deadlines associated with the -// endpoint. -func (c *PacketConn) SetDeadline(t time.Time) error { - if !c.payloadHandler.ok() { - return errInvalidConn - } - return c.payloadHandler.SetDeadline(t) -} - -// SetReadDeadline sets the read deadline associated with the -// endpoint. -func (c *PacketConn) SetReadDeadline(t time.Time) error { - if !c.payloadHandler.ok() { - return errInvalidConn - } - return c.payloadHandler.SetReadDeadline(t) -} - -// SetWriteDeadline sets the write deadline associated with the -// endpoint. -func (c *PacketConn) SetWriteDeadline(t time.Time) error { - if !c.payloadHandler.ok() { - return errInvalidConn - } - return c.payloadHandler.SetWriteDeadline(t) -} - -// Close closes the endpoint. -func (c *PacketConn) Close() error { - if !c.payloadHandler.ok() { - return errInvalidConn - } - return c.payloadHandler.Close() -} - -// NewPacketConn returns a new PacketConn using c as its underlying -// transport. -func NewPacketConn(c net.PacketConn) *PacketConn { - cc, _ := socket.NewConn(c.(net.Conn)) - return &PacketConn{ - genericOpt: genericOpt{Conn: cc}, - dgramOpt: dgramOpt{Conn: cc}, - payloadHandler: payloadHandler{PacketConn: c, Conn: cc}, - } -} diff --git a/vendor/golang.org/x/net/ipv6/genericopt.go b/vendor/golang.org/x/net/ipv6/genericopt.go deleted file mode 100644 index 1a18f7549a..0000000000 --- a/vendor/golang.org/x/net/ipv6/genericopt.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -// TrafficClass returns the traffic class field value for outgoing -// packets. -func (c *genericOpt) TrafficClass() (int, error) { - if !c.ok() { - return 0, errInvalidConn - } - so, ok := sockOpts[ssoTrafficClass] - if !ok { - return 0, errOpNoSupport - } - return so.GetInt(c.Conn) -} - -// SetTrafficClass sets the traffic class field value for future -// outgoing packets. -func (c *genericOpt) SetTrafficClass(tclass int) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoTrafficClass] - if !ok { - return errOpNoSupport - } - return so.SetInt(c.Conn, tclass) -} - -// HopLimit returns the hop limit field value for outgoing packets. -func (c *genericOpt) HopLimit() (int, error) { - if !c.ok() { - return 0, errInvalidConn - } - so, ok := sockOpts[ssoHopLimit] - if !ok { - return 0, errOpNoSupport - } - return so.GetInt(c.Conn) -} - -// SetHopLimit sets the hop limit field value for future outgoing -// packets. -func (c *genericOpt) SetHopLimit(hoplim int) error { - if !c.ok() { - return errInvalidConn - } - so, ok := sockOpts[ssoHopLimit] - if !ok { - return errOpNoSupport - } - return so.SetInt(c.Conn, hoplim) -} diff --git a/vendor/golang.org/x/net/ipv6/header.go b/vendor/golang.org/x/net/ipv6/header.go deleted file mode 100644 index e05cb08b21..0000000000 --- a/vendor/golang.org/x/net/ipv6/header.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "encoding/binary" - "fmt" - "net" -) - -const ( - Version = 6 // protocol version - HeaderLen = 40 // header length -) - -// A Header represents an IPv6 base header. -type Header struct { - Version int // protocol version - TrafficClass int // traffic class - FlowLabel int // flow label - PayloadLen int // payload length - NextHeader int // next header - HopLimit int // hop limit - Src net.IP // source address - Dst net.IP // destination address -} - -func (h *Header) String() string { - if h == nil { - return "" - } - return fmt.Sprintf("ver=%d tclass=%#x flowlbl=%#x payloadlen=%d nxthdr=%d hoplim=%d src=%v dst=%v", h.Version, h.TrafficClass, h.FlowLabel, h.PayloadLen, h.NextHeader, h.HopLimit, h.Src, h.Dst) -} - -// ParseHeader parses b as an IPv6 base header. -func ParseHeader(b []byte) (*Header, error) { - if len(b) < HeaderLen { - return nil, errHeaderTooShort - } - h := &Header{ - Version: int(b[0]) >> 4, - TrafficClass: int(b[0]&0x0f)<<4 | int(b[1])>>4, - FlowLabel: int(b[1]&0x0f)<<16 | int(b[2])<<8 | int(b[3]), - PayloadLen: int(binary.BigEndian.Uint16(b[4:6])), - NextHeader: int(b[6]), - HopLimit: int(b[7]), - } - h.Src = make(net.IP, net.IPv6len) - copy(h.Src, b[8:24]) - h.Dst = make(net.IP, net.IPv6len) - copy(h.Dst, b[24:40]) - return h, nil -} diff --git a/vendor/golang.org/x/net/ipv6/helper.go b/vendor/golang.org/x/net/ipv6/helper.go deleted file mode 100644 index 7ac5352294..0000000000 --- a/vendor/golang.org/x/net/ipv6/helper.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "errors" - "net" -) - -var ( - errInvalidConn = errors.New("invalid connection") - errMissingAddress = errors.New("missing address") - errHeaderTooShort = errors.New("header too short") - errInvalidConnType = errors.New("invalid conn type") - errOpNoSupport = errors.New("operation not supported") - errNoSuchInterface = errors.New("no such interface") -) - -func boolint(b bool) int { - if b { - return 1 - } - return 0 -} - -func netAddrToIP16(a net.Addr) net.IP { - switch v := a.(type) { - case *net.UDPAddr: - if ip := v.IP.To16(); ip != nil && ip.To4() == nil { - return ip - } - case *net.IPAddr: - if ip := v.IP.To16(); ip != nil && ip.To4() == nil { - return ip - } - } - return nil -} - -func opAddr(a net.Addr) net.Addr { - switch a.(type) { - case *net.TCPAddr: - if a == nil { - return nil - } - case *net.UDPAddr: - if a == nil { - return nil - } - case *net.IPAddr: - if a == nil { - return nil - } - } - return a -} diff --git a/vendor/golang.org/x/net/ipv6/iana.go b/vendor/golang.org/x/net/ipv6/iana.go deleted file mode 100644 index 32db1aa949..0000000000 --- a/vendor/golang.org/x/net/ipv6/iana.go +++ /dev/null @@ -1,86 +0,0 @@ -// go generate gen.go -// Code generated by the command above; DO NOT EDIT. - -package ipv6 - -// Internet Control Message Protocol version 6 (ICMPv6) Parameters, Updated: 2018-03-09 -const ( - ICMPTypeDestinationUnreachable ICMPType = 1 // Destination Unreachable - ICMPTypePacketTooBig ICMPType = 2 // Packet Too Big - ICMPTypeTimeExceeded ICMPType = 3 // Time Exceeded - ICMPTypeParameterProblem ICMPType = 4 // Parameter Problem - ICMPTypeEchoRequest ICMPType = 128 // Echo Request - ICMPTypeEchoReply ICMPType = 129 // Echo Reply - ICMPTypeMulticastListenerQuery ICMPType = 130 // Multicast Listener Query - ICMPTypeMulticastListenerReport ICMPType = 131 // Multicast Listener Report - ICMPTypeMulticastListenerDone ICMPType = 132 // Multicast Listener Done - ICMPTypeRouterSolicitation ICMPType = 133 // Router Solicitation - ICMPTypeRouterAdvertisement ICMPType = 134 // Router Advertisement - ICMPTypeNeighborSolicitation ICMPType = 135 // Neighbor Solicitation - ICMPTypeNeighborAdvertisement ICMPType = 136 // Neighbor Advertisement - ICMPTypeRedirect ICMPType = 137 // Redirect Message - ICMPTypeRouterRenumbering ICMPType = 138 // Router Renumbering - ICMPTypeNodeInformationQuery ICMPType = 139 // ICMP Node Information Query - ICMPTypeNodeInformationResponse ICMPType = 140 // ICMP Node Information Response - ICMPTypeInverseNeighborDiscoverySolicitation ICMPType = 141 // Inverse Neighbor Discovery Solicitation Message - ICMPTypeInverseNeighborDiscoveryAdvertisement ICMPType = 142 // Inverse Neighbor Discovery Advertisement Message - ICMPTypeVersion2MulticastListenerReport ICMPType = 143 // Version 2 Multicast Listener Report - ICMPTypeHomeAgentAddressDiscoveryRequest ICMPType = 144 // Home Agent Address Discovery Request Message - ICMPTypeHomeAgentAddressDiscoveryReply ICMPType = 145 // Home Agent Address Discovery Reply Message - ICMPTypeMobilePrefixSolicitation ICMPType = 146 // Mobile Prefix Solicitation - ICMPTypeMobilePrefixAdvertisement ICMPType = 147 // Mobile Prefix Advertisement - ICMPTypeCertificationPathSolicitation ICMPType = 148 // Certification Path Solicitation Message - ICMPTypeCertificationPathAdvertisement ICMPType = 149 // Certification Path Advertisement Message - ICMPTypeMulticastRouterAdvertisement ICMPType = 151 // Multicast Router Advertisement - ICMPTypeMulticastRouterSolicitation ICMPType = 152 // Multicast Router Solicitation - ICMPTypeMulticastRouterTermination ICMPType = 153 // Multicast Router Termination - ICMPTypeFMIPv6 ICMPType = 154 // FMIPv6 Messages - ICMPTypeRPLControl ICMPType = 155 // RPL Control Message - ICMPTypeILNPv6LocatorUpdate ICMPType = 156 // ILNPv6 Locator Update Message - ICMPTypeDuplicateAddressRequest ICMPType = 157 // Duplicate Address Request - ICMPTypeDuplicateAddressConfirmation ICMPType = 158 // Duplicate Address Confirmation - ICMPTypeMPLControl ICMPType = 159 // MPL Control Message - ICMPTypeExtendedEchoRequest ICMPType = 160 // Extended Echo Request - ICMPTypeExtendedEchoReply ICMPType = 161 // Extended Echo Reply -) - -// Internet Control Message Protocol version 6 (ICMPv6) Parameters, Updated: 2018-03-09 -var icmpTypes = map[ICMPType]string{ - 1: "destination unreachable", - 2: "packet too big", - 3: "time exceeded", - 4: "parameter problem", - 128: "echo request", - 129: "echo reply", - 130: "multicast listener query", - 131: "multicast listener report", - 132: "multicast listener done", - 133: "router solicitation", - 134: "router advertisement", - 135: "neighbor solicitation", - 136: "neighbor advertisement", - 137: "redirect message", - 138: "router renumbering", - 139: "icmp node information query", - 140: "icmp node information response", - 141: "inverse neighbor discovery solicitation message", - 142: "inverse neighbor discovery advertisement message", - 143: "version 2 multicast listener report", - 144: "home agent address discovery request message", - 145: "home agent address discovery reply message", - 146: "mobile prefix solicitation", - 147: "mobile prefix advertisement", - 148: "certification path solicitation message", - 149: "certification path advertisement message", - 151: "multicast router advertisement", - 152: "multicast router solicitation", - 153: "multicast router termination", - 154: "fmipv6 messages", - 155: "rpl control message", - 156: "ilnpv6 locator update message", - 157: "duplicate address request", - 158: "duplicate address confirmation", - 159: "mpl control message", - 160: "extended echo request", - 161: "extended echo reply", -} diff --git a/vendor/golang.org/x/net/ipv6/icmp.go b/vendor/golang.org/x/net/ipv6/icmp.go deleted file mode 100644 index b7f48e27b8..0000000000 --- a/vendor/golang.org/x/net/ipv6/icmp.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import "golang.org/x/net/internal/iana" - -// BUG(mikio): On Windows, methods related to ICMPFilter are not -// implemented. - -// An ICMPType represents a type of ICMP message. -type ICMPType int - -func (typ ICMPType) String() string { - s, ok := icmpTypes[typ] - if !ok { - return "" - } - return s -} - -// Protocol returns the ICMPv6 protocol number. -func (typ ICMPType) Protocol() int { - return iana.ProtocolIPv6ICMP -} - -// An ICMPFilter represents an ICMP message filter for incoming -// packets. The filter belongs to a packet delivery path on a host and -// it cannot interact with forwarding packets or tunnel-outer packets. -// -// Note: RFC 8200 defines a reasonable role model. A node means a -// device that implements IP. A router means a node that forwards IP -// packets not explicitly addressed to itself, and a host means a node -// that is not a router. -type ICMPFilter struct { - icmpv6Filter -} - -// Accept accepts incoming ICMP packets including the type field value -// typ. -func (f *ICMPFilter) Accept(typ ICMPType) { - f.accept(typ) -} - -// Block blocks incoming ICMP packets including the type field value -// typ. -func (f *ICMPFilter) Block(typ ICMPType) { - f.block(typ) -} - -// SetAll sets the filter action to the filter. -func (f *ICMPFilter) SetAll(block bool) { - f.setAll(block) -} - -// WillBlock reports whether the ICMP type will be blocked. -func (f *ICMPFilter) WillBlock(typ ICMPType) bool { - return f.willBlock(typ) -} diff --git a/vendor/golang.org/x/net/ipv6/icmp_bsd.go b/vendor/golang.org/x/net/ipv6/icmp_bsd.go deleted file mode 100644 index e1a791de46..0000000000 --- a/vendor/golang.org/x/net/ipv6/icmp_bsd.go +++ /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 darwin dragonfly freebsd netbsd openbsd - -package ipv6 - -func (f *icmpv6Filter) accept(typ ICMPType) { - f.Filt[typ>>5] |= 1 << (uint32(typ) & 31) -} - -func (f *icmpv6Filter) block(typ ICMPType) { - f.Filt[typ>>5] &^= 1 << (uint32(typ) & 31) -} - -func (f *icmpv6Filter) setAll(block bool) { - for i := range f.Filt { - if block { - f.Filt[i] = 0 - } else { - f.Filt[i] = 1<<32 - 1 - } - } -} - -func (f *icmpv6Filter) willBlock(typ ICMPType) bool { - return f.Filt[typ>>5]&(1<<(uint32(typ)&31)) == 0 -} diff --git a/vendor/golang.org/x/net/ipv6/icmp_linux.go b/vendor/golang.org/x/net/ipv6/icmp_linux.go deleted file mode 100644 index 647f6b44ff..0000000000 --- a/vendor/golang.org/x/net/ipv6/icmp_linux.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -func (f *icmpv6Filter) accept(typ ICMPType) { - f.Data[typ>>5] &^= 1 << (uint32(typ) & 31) -} - -func (f *icmpv6Filter) block(typ ICMPType) { - f.Data[typ>>5] |= 1 << (uint32(typ) & 31) -} - -func (f *icmpv6Filter) setAll(block bool) { - for i := range f.Data { - if block { - f.Data[i] = 1<<32 - 1 - } else { - f.Data[i] = 0 - } - } -} - -func (f *icmpv6Filter) willBlock(typ ICMPType) bool { - return f.Data[typ>>5]&(1<<(uint32(typ)&31)) != 0 -} diff --git a/vendor/golang.org/x/net/ipv6/icmp_solaris.go b/vendor/golang.org/x/net/ipv6/icmp_solaris.go deleted file mode 100644 index 7c23bb1cf6..0000000000 --- a/vendor/golang.org/x/net/ipv6/icmp_solaris.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -func (f *icmpv6Filter) accept(typ ICMPType) { - f.X__icmp6_filt[typ>>5] |= 1 << (uint32(typ) & 31) -} - -func (f *icmpv6Filter) block(typ ICMPType) { - f.X__icmp6_filt[typ>>5] &^= 1 << (uint32(typ) & 31) -} - -func (f *icmpv6Filter) setAll(block bool) { - for i := range f.X__icmp6_filt { - if block { - f.X__icmp6_filt[i] = 0 - } else { - f.X__icmp6_filt[i] = 1<<32 - 1 - } - } -} - -func (f *icmpv6Filter) willBlock(typ ICMPType) bool { - return f.X__icmp6_filt[typ>>5]&(1<<(uint32(typ)&31)) == 0 -} diff --git a/vendor/golang.org/x/net/ipv6/icmp_stub.go b/vendor/golang.org/x/net/ipv6/icmp_stub.go deleted file mode 100644 index c4b9be6dbf..0000000000 --- a/vendor/golang.org/x/net/ipv6/icmp_stub.go +++ /dev/null @@ -1,23 +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 !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows - -package ipv6 - -type icmpv6Filter struct { -} - -func (f *icmpv6Filter) accept(typ ICMPType) { -} - -func (f *icmpv6Filter) block(typ ICMPType) { -} - -func (f *icmpv6Filter) setAll(block bool) { -} - -func (f *icmpv6Filter) willBlock(typ ICMPType) bool { - return false -} diff --git a/vendor/golang.org/x/net/ipv6/icmp_windows.go b/vendor/golang.org/x/net/ipv6/icmp_windows.go deleted file mode 100644 index 443cd07367..0000000000 --- a/vendor/golang.org/x/net/ipv6/icmp_windows.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -func (f *icmpv6Filter) accept(typ ICMPType) { - // TODO(mikio): implement this -} - -func (f *icmpv6Filter) block(typ ICMPType) { - // TODO(mikio): implement this -} - -func (f *icmpv6Filter) setAll(block bool) { - // TODO(mikio): implement this -} - -func (f *icmpv6Filter) willBlock(typ ICMPType) bool { - // TODO(mikio): implement this - return false -} diff --git a/vendor/golang.org/x/net/ipv6/payload.go b/vendor/golang.org/x/net/ipv6/payload.go deleted file mode 100644 index a8197f1695..0000000000 --- a/vendor/golang.org/x/net/ipv6/payload.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "net" - - "golang.org/x/net/internal/socket" -) - -// BUG(mikio): On Windows, the ControlMessage for ReadFrom and WriteTo -// methods of PacketConn is not implemented. - -// A payloadHandler represents the IPv6 datagram payload handler. -type payloadHandler struct { - net.PacketConn - *socket.Conn - rawOpt -} - -func (c *payloadHandler) ok() bool { return c != nil && c.PacketConn != nil && c.Conn != nil } diff --git a/vendor/golang.org/x/net/ipv6/payload_cmsg.go b/vendor/golang.org/x/net/ipv6/payload_cmsg.go deleted file mode 100644 index 3f23b5d21d..0000000000 --- a/vendor/golang.org/x/net/ipv6/payload_cmsg.go +++ /dev/null @@ -1,32 +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 !js,!nacl,!plan9,!windows - -package ipv6 - -import "net" - -// ReadFrom reads a payload of the received IPv6 datagram, from the -// endpoint c, copying the payload into b. It returns the number of -// bytes copied into b, the control message cm and the source address -// src of the received datagram. -func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { - if !c.ok() { - return 0, nil, nil, errInvalidConn - } - return c.readFrom(b) -} - -// WriteTo writes a payload of the IPv6 datagram, to the destination -// address dst through the endpoint c, copying the payload from b. It -// returns the number of bytes written. The control message cm allows -// the IPv6 header fields and the datagram path to be specified. The -// cm may be nil if control of the outgoing datagram is not required. -func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { - if !c.ok() { - return 0, errInvalidConn - } - return c.writeTo(b, cm, dst) -} diff --git a/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_8.go b/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_8.go deleted file mode 100644 index bc4209db70..0000000000 --- a/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_8.go +++ /dev/null @@ -1,55 +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 !go1.9 -// +build !js,!nacl,!plan9,!windows - -package ipv6 - -import "net" - -func (c *payloadHandler) readFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { - c.rawOpt.RLock() - oob := NewControlMessage(c.rawOpt.cflags) - c.rawOpt.RUnlock() - var nn int - switch c := c.PacketConn.(type) { - case *net.UDPConn: - if n, nn, _, src, err = c.ReadMsgUDP(b, oob); err != nil { - return 0, nil, nil, err - } - case *net.IPConn: - if n, nn, _, src, err = c.ReadMsgIP(b, oob); err != nil { - return 0, nil, nil, err - } - default: - return 0, nil, nil, &net.OpError{Op: "read", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Err: errInvalidConnType} - } - if nn > 0 { - cm = new(ControlMessage) - if err = cm.Parse(oob[:nn]); err != nil { - return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} - } - } - if cm != nil { - cm.Src = netAddrToIP16(src) - } - return -} - -func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { - oob := cm.Marshal() - if dst == nil { - return 0, &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errMissingAddress} - } - switch c := c.PacketConn.(type) { - case *net.UDPConn: - n, _, err = c.WriteMsgUDP(b, oob, dst.(*net.UDPAddr)) - case *net.IPConn: - n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr)) - default: - return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Addr: opAddr(dst), Err: errInvalidConnType} - } - return -} diff --git a/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_9.go b/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_9.go deleted file mode 100644 index 7dd6504802..0000000000 --- a/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_9.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 -// +build !js,!nacl,!plan9,!windows - -package ipv6 - -import ( - "net" - - "golang.org/x/net/internal/socket" -) - -func (c *payloadHandler) readFrom(b []byte) (int, *ControlMessage, net.Addr, error) { - c.rawOpt.RLock() - m := socket.Message{ - Buffers: [][]byte{b}, - OOB: NewControlMessage(c.rawOpt.cflags), - } - c.rawOpt.RUnlock() - switch c.PacketConn.(type) { - case *net.UDPConn: - if err := c.RecvMsg(&m, 0); err != nil { - return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} - } - case *net.IPConn: - if err := c.RecvMsg(&m, 0); err != nil { - return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} - } - default: - return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errInvalidConnType} - } - var cm *ControlMessage - if m.NN > 0 { - cm = new(ControlMessage) - if err := cm.Parse(m.OOB[:m.NN]); err != nil { - return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} - } - cm.Src = netAddrToIP16(m.Addr) - } - return m.N, cm, m.Addr, nil -} - -func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (int, error) { - m := socket.Message{ - Buffers: [][]byte{b}, - OOB: cm.Marshal(), - Addr: dst, - } - err := c.SendMsg(&m, 0) - if err != nil { - err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Addr: opAddr(dst), Err: err} - } - return m.N, err -} diff --git a/vendor/golang.org/x/net/ipv6/payload_nocmsg.go b/vendor/golang.org/x/net/ipv6/payload_nocmsg.go deleted file mode 100644 index 459142d264..0000000000 --- a/vendor/golang.org/x/net/ipv6/payload_nocmsg.go +++ /dev/null @@ -1,38 +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 js nacl plan9 windows - -package ipv6 - -import "net" - -// ReadFrom reads a payload of the received IPv6 datagram, from the -// endpoint c, copying the payload into b. It returns the number of -// bytes copied into b, the control message cm and the source address -// src of the received datagram. -func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { - if !c.ok() { - return 0, nil, nil, errInvalidConn - } - if n, src, err = c.PacketConn.ReadFrom(b); err != nil { - return 0, nil, nil, err - } - return -} - -// WriteTo writes a payload of the IPv6 datagram, to the destination -// address dst through the endpoint c, copying the payload from b. It -// returns the number of bytes written. The control message cm allows -// the IPv6 header fields and the datagram path to be specified. The -// cm may be nil if control of the outgoing datagram is not required. -func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { - if !c.ok() { - return 0, errInvalidConn - } - if dst == nil { - return 0, errMissingAddress - } - return c.PacketConn.WriteTo(b, dst) -} diff --git a/vendor/golang.org/x/net/ipv6/sockopt.go b/vendor/golang.org/x/net/ipv6/sockopt.go deleted file mode 100644 index cc3907df38..0000000000 --- a/vendor/golang.org/x/net/ipv6/sockopt.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import "golang.org/x/net/internal/socket" - -// Sticky socket options -const ( - ssoTrafficClass = iota // header field for unicast packet, RFC 3542 - ssoHopLimit // header field for unicast packet, RFC 3493 - ssoMulticastInterface // outbound interface for multicast packet, RFC 3493 - ssoMulticastHopLimit // header field for multicast packet, RFC 3493 - ssoMulticastLoopback // loopback for multicast packet, RFC 3493 - ssoReceiveTrafficClass // header field on received packet, RFC 3542 - ssoReceiveHopLimit // header field on received packet, RFC 2292 or 3542 - ssoReceivePacketInfo // incbound or outbound packet path, RFC 2292 or 3542 - ssoReceivePathMTU // path mtu, RFC 3542 - ssoPathMTU // path mtu, RFC 3542 - ssoChecksum // packet checksum, RFC 2292 or 3542 - ssoICMPFilter // icmp filter, RFC 2292 or 3542 - ssoJoinGroup // any-source multicast, RFC 3493 - ssoLeaveGroup // any-source multicast, RFC 3493 - ssoJoinSourceGroup // source-specific multicast - ssoLeaveSourceGroup // source-specific multicast - ssoBlockSourceGroup // any-source or source-specific multicast - ssoUnblockSourceGroup // any-source or source-specific multicast - ssoAttachFilter // attach BPF for filtering inbound traffic -) - -// Sticky socket option value types -const ( - ssoTypeIPMreq = iota + 1 - ssoTypeGroupReq - ssoTypeGroupSourceReq -) - -// A sockOpt represents a binding for sticky socket option. -type sockOpt struct { - socket.Option - typ int // hint for option value type; optional -} diff --git a/vendor/golang.org/x/net/ipv6/sockopt_posix.go b/vendor/golang.org/x/net/ipv6/sockopt_posix.go deleted file mode 100644 index 0eac86eb8c..0000000000 --- a/vendor/golang.org/x/net/ipv6/sockopt_posix.go +++ /dev/null @@ -1,87 +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 darwin dragonfly freebsd linux netbsd openbsd solaris windows - -package ipv6 - -import ( - "net" - "unsafe" - - "golang.org/x/net/bpf" - "golang.org/x/net/internal/socket" -) - -func (so *sockOpt) getMulticastInterface(c *socket.Conn) (*net.Interface, error) { - n, err := so.GetInt(c) - if err != nil { - return nil, err - } - return net.InterfaceByIndex(n) -} - -func (so *sockOpt) setMulticastInterface(c *socket.Conn, ifi *net.Interface) error { - var n int - if ifi != nil { - n = ifi.Index - } - return so.SetInt(c, n) -} - -func (so *sockOpt) getICMPFilter(c *socket.Conn) (*ICMPFilter, error) { - b := make([]byte, so.Len) - n, err := so.Get(c, b) - if err != nil { - return nil, err - } - if n != sizeofICMPv6Filter { - return nil, errOpNoSupport - } - return (*ICMPFilter)(unsafe.Pointer(&b[0])), nil -} - -func (so *sockOpt) setICMPFilter(c *socket.Conn, f *ICMPFilter) error { - b := (*[sizeofICMPv6Filter]byte)(unsafe.Pointer(f))[:sizeofICMPv6Filter] - return so.Set(c, b) -} - -func (so *sockOpt) getMTUInfo(c *socket.Conn) (*net.Interface, int, error) { - b := make([]byte, so.Len) - n, err := so.Get(c, b) - if err != nil { - return nil, 0, err - } - if n != sizeofIPv6Mtuinfo { - return nil, 0, errOpNoSupport - } - mi := (*ipv6Mtuinfo)(unsafe.Pointer(&b[0])) - if mi.Addr.Scope_id == 0 { - return nil, int(mi.Mtu), nil - } - ifi, err := net.InterfaceByIndex(int(mi.Addr.Scope_id)) - if err != nil { - return nil, 0, err - } - return ifi, int(mi.Mtu), nil -} - -func (so *sockOpt) setGroup(c *socket.Conn, ifi *net.Interface, grp net.IP) error { - switch so.typ { - case ssoTypeIPMreq: - return so.setIPMreq(c, ifi, grp) - case ssoTypeGroupReq: - return so.setGroupReq(c, ifi, grp) - default: - return errOpNoSupport - } -} - -func (so *sockOpt) setSourceGroup(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { - return so.setGroupSourceReq(c, ifi, grp, src) -} - -func (so *sockOpt) setBPF(c *socket.Conn, f []bpf.RawInstruction) error { - return so.setAttachFilter(c, f) -} diff --git a/vendor/golang.org/x/net/ipv6/sockopt_stub.go b/vendor/golang.org/x/net/ipv6/sockopt_stub.go deleted file mode 100644 index 1f4a273e44..0000000000 --- a/vendor/golang.org/x/net/ipv6/sockopt_stub.go +++ /dev/null @@ -1,46 +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 !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows - -package ipv6 - -import ( - "net" - - "golang.org/x/net/bpf" - "golang.org/x/net/internal/socket" -) - -func (so *sockOpt) getMulticastInterface(c *socket.Conn) (*net.Interface, error) { - return nil, errOpNoSupport -} - -func (so *sockOpt) setMulticastInterface(c *socket.Conn, ifi *net.Interface) error { - return errOpNoSupport -} - -func (so *sockOpt) getICMPFilter(c *socket.Conn) (*ICMPFilter, error) { - return nil, errOpNoSupport -} - -func (so *sockOpt) setICMPFilter(c *socket.Conn, f *ICMPFilter) error { - return errOpNoSupport -} - -func (so *sockOpt) getMTUInfo(c *socket.Conn) (*net.Interface, int, error) { - return nil, 0, errOpNoSupport -} - -func (so *sockOpt) setGroup(c *socket.Conn, ifi *net.Interface, grp net.IP) error { - return errOpNoSupport -} - -func (so *sockOpt) setSourceGroup(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { - return errOpNoSupport -} - -func (so *sockOpt) setBPF(c *socket.Conn, f []bpf.RawInstruction) error { - return errOpNoSupport -} diff --git a/vendor/golang.org/x/net/ipv6/sys_asmreq.go b/vendor/golang.org/x/net/ipv6/sys_asmreq.go deleted file mode 100644 index b0510c0b5d..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_asmreq.go +++ /dev/null @@ -1,24 +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 darwin dragonfly freebsd linux netbsd openbsd solaris windows - -package ipv6 - -import ( - "net" - "unsafe" - - "golang.org/x/net/internal/socket" -) - -func (so *sockOpt) setIPMreq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { - var mreq ipv6Mreq - copy(mreq.Multiaddr[:], grp) - if ifi != nil { - mreq.setIfindex(ifi.Index) - } - b := (*[sizeofIPv6Mreq]byte)(unsafe.Pointer(&mreq))[:sizeofIPv6Mreq] - return so.Set(c, b) -} diff --git a/vendor/golang.org/x/net/ipv6/sys_asmreq_stub.go b/vendor/golang.org/x/net/ipv6/sys_asmreq_stub.go deleted file mode 100644 index eece96187b..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_asmreq_stub.go +++ /dev/null @@ -1,17 +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 !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows - -package ipv6 - -import ( - "net" - - "golang.org/x/net/internal/socket" -) - -func (so *sockOpt) setIPMreq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { - return errOpNoSupport -} diff --git a/vendor/golang.org/x/net/ipv6/sys_bpf.go b/vendor/golang.org/x/net/ipv6/sys_bpf.go deleted file mode 100644 index b2dbcb2f28..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_bpf.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux - -package ipv6 - -import ( - "unsafe" - - "golang.org/x/net/bpf" - "golang.org/x/net/internal/socket" -) - -func (so *sockOpt) setAttachFilter(c *socket.Conn, f []bpf.RawInstruction) error { - prog := sockFProg{ - Len: uint16(len(f)), - Filter: (*sockFilter)(unsafe.Pointer(&f[0])), - } - b := (*[sizeofSockFprog]byte)(unsafe.Pointer(&prog))[:sizeofSockFprog] - return so.Set(c, b) -} diff --git a/vendor/golang.org/x/net/ipv6/sys_bpf_stub.go b/vendor/golang.org/x/net/ipv6/sys_bpf_stub.go deleted file mode 100644 index 676bea555f..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_bpf_stub.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !linux - -package ipv6 - -import ( - "golang.org/x/net/bpf" - "golang.org/x/net/internal/socket" -) - -func (so *sockOpt) setAttachFilter(c *socket.Conn, f []bpf.RawInstruction) error { - return errOpNoSupport -} diff --git a/vendor/golang.org/x/net/ipv6/sys_bsd.go b/vendor/golang.org/x/net/ipv6/sys_bsd.go deleted file mode 100644 index e416eaa1fe..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_bsd.go +++ /dev/null @@ -1,57 +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 netbsd openbsd - -package ipv6 - -import ( - "net" - "syscall" - - "golang.org/x/net/internal/iana" - "golang.org/x/net/internal/socket" -) - -var ( - ctlOpts = [ctlMax]ctlOpt{ - ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, - ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, - ctlPacketInfo: {sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, - ctlNextHop: {sysIPV6_NEXTHOP, sizeofSockaddrInet6, marshalNextHop, parseNextHop}, - ctlPathMTU: {sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, - } - - sockOpts = map[int]*sockOpt{ - ssoTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}}, - ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, - ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, - ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, - ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, - ssoReceiveTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}}, - ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}}, - ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}}, - ssoReceivePathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}}, - ssoPathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}}, - ssoChecksum: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_CHECKSUM, Len: 4}}, - ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMP6_FILTER, Len: sizeofICMPv6Filter}}, - ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_JOIN_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, - ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_LEAVE_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, - } -) - -func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { - sa.Len = sizeofSockaddrInet6 - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], ip) - sa.Scope_id = uint32(i) -} - -func (pi *inet6Pktinfo) setIfindex(i int) { - pi.Ifindex = uint32(i) -} - -func (mreq *ipv6Mreq) setIfindex(i int) { - mreq.Interface = uint32(i) -} diff --git a/vendor/golang.org/x/net/ipv6/sys_darwin.go b/vendor/golang.org/x/net/ipv6/sys_darwin.go deleted file mode 100644 index e3d0443927..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_darwin.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "net" - "strconv" - "strings" - "syscall" - "unsafe" - - "golang.org/x/net/internal/iana" - "golang.org/x/net/internal/socket" -) - -var ( - ctlOpts = [ctlMax]ctlOpt{ - ctlHopLimit: {sysIPV6_2292HOPLIMIT, 4, marshal2292HopLimit, parseHopLimit}, - ctlPacketInfo: {sysIPV6_2292PKTINFO, sizeofInet6Pktinfo, marshal2292PacketInfo, parsePacketInfo}, - } - - sockOpts = map[int]*sockOpt{ - ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, - ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, - ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, - ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, - ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_2292HOPLIMIT, Len: 4}}, - ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_2292PKTINFO, Len: 4}}, - ssoChecksum: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_CHECKSUM, Len: 4}}, - ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMP6_FILTER, Len: sizeofICMPv6Filter}}, - ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_JOIN_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, - ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_LEAVE_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, - } -) - -func init() { - // Seems like kern.osreldate is veiled on latest OS X. We use - // kern.osrelease instead. - s, err := syscall.Sysctl("kern.osrelease") - if err != nil { - return - } - ss := strings.Split(s, ".") - if len(ss) == 0 { - return - } - // The IP_PKTINFO and protocol-independent multicast API were - // introduced in OS X 10.7 (Darwin 11). But it looks like - // those features require OS X 10.8 (Darwin 12) or above. - // See http://support.apple.com/kb/HT1633. - if mjver, err := strconv.Atoi(ss[0]); err != nil || mjver < 12 { - return - } - ctlOpts[ctlTrafficClass] = ctlOpt{sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass} - ctlOpts[ctlHopLimit] = ctlOpt{sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit} - ctlOpts[ctlPacketInfo] = ctlOpt{sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo} - ctlOpts[ctlNextHop] = ctlOpt{sysIPV6_NEXTHOP, sizeofSockaddrInet6, marshalNextHop, parseNextHop} - ctlOpts[ctlPathMTU] = ctlOpt{sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU} - sockOpts[ssoTrafficClass] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}} - sockOpts[ssoReceiveTrafficClass] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}} - sockOpts[ssoReceiveHopLimit] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}} - sockOpts[ssoReceivePacketInfo] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}} - sockOpts[ssoReceivePathMTU] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}} - sockOpts[ssoPathMTU] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}} - sockOpts[ssoJoinGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq} - sockOpts[ssoLeaveGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq} - sockOpts[ssoJoinSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} - sockOpts[ssoLeaveSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} - sockOpts[ssoBlockSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} - sockOpts[ssoUnblockSourceGroup] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq} -} - -func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { - sa.Len = sizeofSockaddrInet6 - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], ip) - sa.Scope_id = uint32(i) -} - -func (pi *inet6Pktinfo) setIfindex(i int) { - pi.Ifindex = uint32(i) -} - -func (mreq *ipv6Mreq) setIfindex(i int) { - mreq.Interface = uint32(i) -} - -func (gr *groupReq) setGroup(grp net.IP) { - sa := (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gr)) + 4)) - sa.Len = sizeofSockaddrInet6 - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], grp) -} - -func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { - sa := (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 4)) - sa.Len = sizeofSockaddrInet6 - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], grp) - sa = (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 132)) - sa.Len = sizeofSockaddrInet6 - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], src) -} diff --git a/vendor/golang.org/x/net/ipv6/sys_freebsd.go b/vendor/golang.org/x/net/ipv6/sys_freebsd.go deleted file mode 100644 index e9349dc2cc..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_freebsd.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "net" - "runtime" - "strings" - "syscall" - "unsafe" - - "golang.org/x/net/internal/iana" - "golang.org/x/net/internal/socket" -) - -var ( - ctlOpts = [ctlMax]ctlOpt{ - ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, - ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, - ctlPacketInfo: {sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, - ctlNextHop: {sysIPV6_NEXTHOP, sizeofSockaddrInet6, marshalNextHop, parseNextHop}, - ctlPathMTU: {sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, - } - - sockOpts = map[int]sockOpt{ - ssoTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}}, - ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, - ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, - ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, - ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, - ssoReceiveTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}}, - ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}}, - ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}}, - ssoReceivePathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}}, - ssoPathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}}, - ssoChecksum: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_CHECKSUM, Len: 4}}, - ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMP6_FILTER, Len: sizeofICMPv6Filter}}, - ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, - ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, - ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - } -) - -func init() { - if runtime.GOOS == "freebsd" && runtime.GOARCH == "386" { - archs, _ := syscall.Sysctl("kern.supported_archs") - for _, s := range strings.Fields(archs) { - if s == "amd64" { - freebsd32o64 = true - break - } - } - } -} - -func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { - sa.Len = sizeofSockaddrInet6 - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], ip) - sa.Scope_id = uint32(i) -} - -func (pi *inet6Pktinfo) setIfindex(i int) { - pi.Ifindex = uint32(i) -} - -func (mreq *ipv6Mreq) setIfindex(i int) { - mreq.Interface = uint32(i) -} - -func (gr *groupReq) setGroup(grp net.IP) { - sa := (*sockaddrInet6)(unsafe.Pointer(&gr.Group)) - sa.Len = sizeofSockaddrInet6 - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], grp) -} - -func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { - sa := (*sockaddrInet6)(unsafe.Pointer(&gsr.Group)) - sa.Len = sizeofSockaddrInet6 - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], grp) - sa = (*sockaddrInet6)(unsafe.Pointer(&gsr.Source)) - sa.Len = sizeofSockaddrInet6 - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], src) -} diff --git a/vendor/golang.org/x/net/ipv6/sys_linux.go b/vendor/golang.org/x/net/ipv6/sys_linux.go deleted file mode 100644 index bc218103c1..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_linux.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "net" - "syscall" - "unsafe" - - "golang.org/x/net/internal/iana" - "golang.org/x/net/internal/socket" -) - -var ( - ctlOpts = [ctlMax]ctlOpt{ - ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, - ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, - ctlPacketInfo: {sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, - ctlPathMTU: {sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, - } - - sockOpts = map[int]*sockOpt{ - ssoTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}}, - ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, - ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, - ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, - ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, - ssoReceiveTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}}, - ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}}, - ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}}, - ssoReceivePathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}}, - ssoPathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}}, - ssoChecksum: {Option: socket.Option{Level: iana.ProtocolReserved, Name: sysIPV6_CHECKSUM, Len: 4}}, - ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMPV6_FILTER, Len: sizeofICMPv6Filter}}, - ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, - ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, - ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - ssoAttachFilter: {Option: socket.Option{Level: sysSOL_SOCKET, Name: sysSO_ATTACH_FILTER, Len: sizeofSockFprog}}, - } -) - -func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], ip) - sa.Scope_id = uint32(i) -} - -func (pi *inet6Pktinfo) setIfindex(i int) { - pi.Ifindex = int32(i) -} - -func (mreq *ipv6Mreq) setIfindex(i int) { - mreq.Ifindex = int32(i) -} - -func (gr *groupReq) setGroup(grp net.IP) { - sa := (*sockaddrInet6)(unsafe.Pointer(&gr.Group)) - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], grp) -} - -func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { - sa := (*sockaddrInet6)(unsafe.Pointer(&gsr.Group)) - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], grp) - sa = (*sockaddrInet6)(unsafe.Pointer(&gsr.Source)) - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], src) -} diff --git a/vendor/golang.org/x/net/ipv6/sys_solaris.go b/vendor/golang.org/x/net/ipv6/sys_solaris.go deleted file mode 100644 index d348b5f6e4..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_solaris.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "net" - "syscall" - "unsafe" - - "golang.org/x/net/internal/iana" - "golang.org/x/net/internal/socket" -) - -var ( - ctlOpts = [ctlMax]ctlOpt{ - ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, - ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, - ctlPacketInfo: {sysIPV6_PKTINFO, sizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, - ctlNextHop: {sysIPV6_NEXTHOP, sizeofSockaddrInet6, marshalNextHop, parseNextHop}, - ctlPathMTU: {sysIPV6_PATHMTU, sizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, - } - - sockOpts = map[int]*sockOpt{ - ssoTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_TCLASS, Len: 4}}, - ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, - ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, - ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, - ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, - ssoReceiveTrafficClass: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVTCLASS, Len: 4}}, - ssoReceiveHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVHOPLIMIT, Len: 4}}, - ssoReceivePacketInfo: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPKTINFO, Len: 4}}, - ssoReceivePathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_RECVPATHMTU, Len: 4}}, - ssoPathMTU: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_PATHMTU, Len: sizeofIPv6Mtuinfo}}, - ssoChecksum: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_CHECKSUM, Len: 4}}, - ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolIPv6ICMP, Name: sysICMP6_FILTER, Len: sizeofICMPv6Filter}}, - ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, - ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, - ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, - } -) - -func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], ip) - sa.Scope_id = uint32(i) -} - -func (pi *inet6Pktinfo) setIfindex(i int) { - pi.Ifindex = uint32(i) -} - -func (mreq *ipv6Mreq) setIfindex(i int) { - mreq.Interface = uint32(i) -} - -func (gr *groupReq) setGroup(grp net.IP) { - sa := (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gr)) + 4)) - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], grp) -} - -func (gsr *groupSourceReq) setSourceGroup(grp, src net.IP) { - sa := (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 4)) - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], grp) - sa = (*sockaddrInet6)(unsafe.Pointer(uintptr(unsafe.Pointer(gsr)) + 260)) - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], src) -} diff --git a/vendor/golang.org/x/net/ipv6/sys_ssmreq.go b/vendor/golang.org/x/net/ipv6/sys_ssmreq.go deleted file mode 100644 index add8ccc0b1..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_ssmreq.go +++ /dev/null @@ -1,54 +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 darwin freebsd linux solaris - -package ipv6 - -import ( - "net" - "unsafe" - - "golang.org/x/net/internal/socket" -) - -var freebsd32o64 bool - -func (so *sockOpt) setGroupReq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { - var gr groupReq - if ifi != nil { - gr.Interface = uint32(ifi.Index) - } - gr.setGroup(grp) - var b []byte - if freebsd32o64 { - var d [sizeofGroupReq + 4]byte - s := (*[sizeofGroupReq]byte)(unsafe.Pointer(&gr)) - copy(d[:4], s[:4]) - copy(d[8:], s[4:]) - b = d[:] - } else { - b = (*[sizeofGroupReq]byte)(unsafe.Pointer(&gr))[:sizeofGroupReq] - } - return so.Set(c, b) -} - -func (so *sockOpt) setGroupSourceReq(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { - var gsr groupSourceReq - if ifi != nil { - gsr.Interface = uint32(ifi.Index) - } - gsr.setSourceGroup(grp, src) - var b []byte - if freebsd32o64 { - var d [sizeofGroupSourceReq + 4]byte - s := (*[sizeofGroupSourceReq]byte)(unsafe.Pointer(&gsr)) - copy(d[:4], s[:4]) - copy(d[8:], s[4:]) - b = d[:] - } else { - b = (*[sizeofGroupSourceReq]byte)(unsafe.Pointer(&gsr))[:sizeofGroupSourceReq] - } - return so.Set(c, b) -} diff --git a/vendor/golang.org/x/net/ipv6/sys_ssmreq_stub.go b/vendor/golang.org/x/net/ipv6/sys_ssmreq_stub.go deleted file mode 100644 index 581ee490ff..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_ssmreq_stub.go +++ /dev/null @@ -1,21 +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 !darwin,!freebsd,!linux,!solaris - -package ipv6 - -import ( - "net" - - "golang.org/x/net/internal/socket" -) - -func (so *sockOpt) setGroupReq(c *socket.Conn, ifi *net.Interface, grp net.IP) error { - return errOpNoSupport -} - -func (so *sockOpt) setGroupSourceReq(c *socket.Conn, ifi *net.Interface, grp, src net.IP) error { - return errOpNoSupport -} diff --git a/vendor/golang.org/x/net/ipv6/sys_stub.go b/vendor/golang.org/x/net/ipv6/sys_stub.go deleted file mode 100644 index b845388ea4..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_stub.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows - -package ipv6 - -var ( - ctlOpts = [ctlMax]ctlOpt{} - - sockOpts = map[int]*sockOpt{} -) diff --git a/vendor/golang.org/x/net/ipv6/sys_windows.go b/vendor/golang.org/x/net/ipv6/sys_windows.go deleted file mode 100644 index fc36b018bd..0000000000 --- a/vendor/golang.org/x/net/ipv6/sys_windows.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ipv6 - -import ( - "net" - "syscall" - - "golang.org/x/net/internal/iana" - "golang.org/x/net/internal/socket" -) - -const ( - // See ws2tcpip.h. - sysIPV6_UNICAST_HOPS = 0x4 - sysIPV6_MULTICAST_IF = 0x9 - sysIPV6_MULTICAST_HOPS = 0xa - sysIPV6_MULTICAST_LOOP = 0xb - sysIPV6_JOIN_GROUP = 0xc - sysIPV6_LEAVE_GROUP = 0xd - sysIPV6_PKTINFO = 0x13 - - sizeofSockaddrInet6 = 0x1c - - sizeofIPv6Mreq = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofICMPv6Filter = 0 -) - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type icmpv6Filter struct { - // TODO(mikio): implement this -} - -var ( - ctlOpts = [ctlMax]ctlOpt{} - - sockOpts = map[int]*sockOpt{ - ssoHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_UNICAST_HOPS, Len: 4}}, - ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_IF, Len: 4}}, - ssoMulticastHopLimit: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_HOPS, Len: 4}}, - ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_MULTICAST_LOOP, Len: 4}}, - ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_JOIN_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, - ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIPv6, Name: sysIPV6_LEAVE_GROUP, Len: sizeofIPv6Mreq}, typ: ssoTypeIPMreq}, - } -) - -func (sa *sockaddrInet6) setSockaddr(ip net.IP, i int) { - sa.Family = syscall.AF_INET6 - copy(sa.Addr[:], ip) - sa.Scope_id = uint32(i) -} - -func (mreq *ipv6Mreq) setIfindex(i int) { - mreq.Interface = uint32(i) -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_darwin.go b/vendor/golang.org/x/net/ipv6/zsys_darwin.go deleted file mode 100644 index 6aab1dfab7..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_darwin.go +++ /dev/null @@ -1,131 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_darwin.go - -package ipv6 - -const ( - sysIPV6_UNICAST_HOPS = 0x4 - sysIPV6_MULTICAST_IF = 0x9 - sysIPV6_MULTICAST_HOPS = 0xa - sysIPV6_MULTICAST_LOOP = 0xb - sysIPV6_JOIN_GROUP = 0xc - sysIPV6_LEAVE_GROUP = 0xd - - sysIPV6_PORTRANGE = 0xe - sysICMP6_FILTER = 0x12 - sysIPV6_2292PKTINFO = 0x13 - sysIPV6_2292HOPLIMIT = 0x14 - sysIPV6_2292NEXTHOP = 0x15 - sysIPV6_2292HOPOPTS = 0x16 - sysIPV6_2292DSTOPTS = 0x17 - sysIPV6_2292RTHDR = 0x18 - - sysIPV6_2292PKTOPTIONS = 0x19 - - sysIPV6_CHECKSUM = 0x1a - sysIPV6_V6ONLY = 0x1b - - sysIPV6_IPSEC_POLICY = 0x1c - - sysIPV6_RECVTCLASS = 0x23 - sysIPV6_TCLASS = 0x24 - - sysIPV6_RTHDRDSTOPTS = 0x39 - - sysIPV6_RECVPKTINFO = 0x3d - - sysIPV6_RECVHOPLIMIT = 0x25 - sysIPV6_RECVRTHDR = 0x26 - sysIPV6_RECVHOPOPTS = 0x27 - sysIPV6_RECVDSTOPTS = 0x28 - - sysIPV6_USE_MIN_MTU = 0x2a - sysIPV6_RECVPATHMTU = 0x2b - - sysIPV6_PATHMTU = 0x2c - - sysIPV6_PKTINFO = 0x2e - sysIPV6_HOPLIMIT = 0x2f - sysIPV6_NEXTHOP = 0x30 - sysIPV6_HOPOPTS = 0x31 - sysIPV6_DSTOPTS = 0x32 - sysIPV6_RTHDR = 0x33 - - sysIPV6_AUTOFLOWLABEL = 0x3b - - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_PREFER_TEMPADDR = 0x3f - - sysIPV6_MSFILTER = 0x4a - sysMCAST_JOIN_GROUP = 0x50 - sysMCAST_LEAVE_GROUP = 0x51 - sysMCAST_JOIN_SOURCE_GROUP = 0x52 - sysMCAST_LEAVE_SOURCE_GROUP = 0x53 - sysMCAST_BLOCK_SOURCE = 0x54 - sysMCAST_UNBLOCK_SOURCE = 0x55 - - sysIPV6_BOUND_IF = 0x7d - - sysIPV6_PORTRANGE_DEFAULT = 0x0 - sysIPV6_PORTRANGE_HIGH = 0x1 - sysIPV6_PORTRANGE_LOW = 0x2 - - sizeofSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x84 - sizeofGroupSourceReq = 0x104 - - sizeofICMPv6Filter = 0x20 -) - -type sockaddrStorage struct { - Len uint8 - Family uint8 - X__ss_pad1 [6]int8 - X__ss_align int64 - X__ss_pad2 [112]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type icmpv6Filter struct { - Filt [8]uint32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [128]byte -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [128]byte - Pad_cgo_1 [128]byte -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_dragonfly.go b/vendor/golang.org/x/net/ipv6/zsys_dragonfly.go deleted file mode 100644 index d2de804d88..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_dragonfly.go +++ /dev/null @@ -1,88 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_dragonfly.go - -package ipv6 - -const ( - sysIPV6_UNICAST_HOPS = 0x4 - sysIPV6_MULTICAST_IF = 0x9 - sysIPV6_MULTICAST_HOPS = 0xa - sysIPV6_MULTICAST_LOOP = 0xb - sysIPV6_JOIN_GROUP = 0xc - sysIPV6_LEAVE_GROUP = 0xd - sysIPV6_PORTRANGE = 0xe - sysICMP6_FILTER = 0x12 - - sysIPV6_CHECKSUM = 0x1a - sysIPV6_V6ONLY = 0x1b - - sysIPV6_IPSEC_POLICY = 0x1c - - sysIPV6_RTHDRDSTOPTS = 0x23 - sysIPV6_RECVPKTINFO = 0x24 - sysIPV6_RECVHOPLIMIT = 0x25 - sysIPV6_RECVRTHDR = 0x26 - sysIPV6_RECVHOPOPTS = 0x27 - sysIPV6_RECVDSTOPTS = 0x28 - - sysIPV6_USE_MIN_MTU = 0x2a - sysIPV6_RECVPATHMTU = 0x2b - - sysIPV6_PATHMTU = 0x2c - - sysIPV6_PKTINFO = 0x2e - sysIPV6_HOPLIMIT = 0x2f - sysIPV6_NEXTHOP = 0x30 - sysIPV6_HOPOPTS = 0x31 - sysIPV6_DSTOPTS = 0x32 - sysIPV6_RTHDR = 0x33 - - sysIPV6_RECVTCLASS = 0x39 - - sysIPV6_AUTOFLOWLABEL = 0x3b - - sysIPV6_TCLASS = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_PREFER_TEMPADDR = 0x3f - - sysIPV6_PORTRANGE_DEFAULT = 0x0 - sysIPV6_PORTRANGE_HIGH = 0x1 - sysIPV6_PORTRANGE_LOW = 0x2 - - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - - sizeofIPv6Mreq = 0x14 - - sizeofICMPv6Filter = 0x20 -) - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type icmpv6Filter struct { - Filt [8]uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_freebsd_386.go b/vendor/golang.org/x/net/ipv6/zsys_freebsd_386.go deleted file mode 100644 index 919e572d4a..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_freebsd_386.go +++ /dev/null @@ -1,122 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_freebsd.go - -package ipv6 - -const ( - sysIPV6_UNICAST_HOPS = 0x4 - sysIPV6_MULTICAST_IF = 0x9 - sysIPV6_MULTICAST_HOPS = 0xa - sysIPV6_MULTICAST_LOOP = 0xb - sysIPV6_JOIN_GROUP = 0xc - sysIPV6_LEAVE_GROUP = 0xd - sysIPV6_PORTRANGE = 0xe - sysICMP6_FILTER = 0x12 - - sysIPV6_CHECKSUM = 0x1a - sysIPV6_V6ONLY = 0x1b - - sysIPV6_IPSEC_POLICY = 0x1c - - sysIPV6_RTHDRDSTOPTS = 0x23 - - sysIPV6_RECVPKTINFO = 0x24 - sysIPV6_RECVHOPLIMIT = 0x25 - sysIPV6_RECVRTHDR = 0x26 - sysIPV6_RECVHOPOPTS = 0x27 - sysIPV6_RECVDSTOPTS = 0x28 - - sysIPV6_USE_MIN_MTU = 0x2a - sysIPV6_RECVPATHMTU = 0x2b - - sysIPV6_PATHMTU = 0x2c - - sysIPV6_PKTINFO = 0x2e - sysIPV6_HOPLIMIT = 0x2f - sysIPV6_NEXTHOP = 0x30 - sysIPV6_HOPOPTS = 0x31 - sysIPV6_DSTOPTS = 0x32 - sysIPV6_RTHDR = 0x33 - - sysIPV6_RECVTCLASS = 0x39 - - sysIPV6_AUTOFLOWLABEL = 0x3b - - sysIPV6_TCLASS = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_PREFER_TEMPADDR = 0x3f - - sysIPV6_BINDANY = 0x40 - - sysIPV6_MSFILTER = 0x4a - - sysMCAST_JOIN_GROUP = 0x50 - sysMCAST_LEAVE_GROUP = 0x51 - sysMCAST_JOIN_SOURCE_GROUP = 0x52 - sysMCAST_LEAVE_SOURCE_GROUP = 0x53 - sysMCAST_BLOCK_SOURCE = 0x54 - sysMCAST_UNBLOCK_SOURCE = 0x55 - - sysIPV6_PORTRANGE_DEFAULT = 0x0 - sysIPV6_PORTRANGE_HIGH = 0x1 - sysIPV6_PORTRANGE_LOW = 0x2 - - sizeofSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x84 - sizeofGroupSourceReq = 0x104 - - sizeofICMPv6Filter = 0x20 -) - -type sockaddrStorage struct { - Len uint8 - Family uint8 - X__ss_pad1 [6]int8 - X__ss_align int64 - X__ss_pad2 [112]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type groupReq struct { - Interface uint32 - Group sockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Group sockaddrStorage - Source sockaddrStorage -} - -type icmpv6Filter struct { - Filt [8]uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_freebsd_amd64.go b/vendor/golang.org/x/net/ipv6/zsys_freebsd_amd64.go deleted file mode 100644 index cb8141f9c6..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_freebsd_amd64.go +++ /dev/null @@ -1,124 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_freebsd.go - -package ipv6 - -const ( - sysIPV6_UNICAST_HOPS = 0x4 - sysIPV6_MULTICAST_IF = 0x9 - sysIPV6_MULTICAST_HOPS = 0xa - sysIPV6_MULTICAST_LOOP = 0xb - sysIPV6_JOIN_GROUP = 0xc - sysIPV6_LEAVE_GROUP = 0xd - sysIPV6_PORTRANGE = 0xe - sysICMP6_FILTER = 0x12 - - sysIPV6_CHECKSUM = 0x1a - sysIPV6_V6ONLY = 0x1b - - sysIPV6_IPSEC_POLICY = 0x1c - - sysIPV6_RTHDRDSTOPTS = 0x23 - - sysIPV6_RECVPKTINFO = 0x24 - sysIPV6_RECVHOPLIMIT = 0x25 - sysIPV6_RECVRTHDR = 0x26 - sysIPV6_RECVHOPOPTS = 0x27 - sysIPV6_RECVDSTOPTS = 0x28 - - sysIPV6_USE_MIN_MTU = 0x2a - sysIPV6_RECVPATHMTU = 0x2b - - sysIPV6_PATHMTU = 0x2c - - sysIPV6_PKTINFO = 0x2e - sysIPV6_HOPLIMIT = 0x2f - sysIPV6_NEXTHOP = 0x30 - sysIPV6_HOPOPTS = 0x31 - sysIPV6_DSTOPTS = 0x32 - sysIPV6_RTHDR = 0x33 - - sysIPV6_RECVTCLASS = 0x39 - - sysIPV6_AUTOFLOWLABEL = 0x3b - - sysIPV6_TCLASS = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_PREFER_TEMPADDR = 0x3f - - sysIPV6_BINDANY = 0x40 - - sysIPV6_MSFILTER = 0x4a - - sysMCAST_JOIN_GROUP = 0x50 - sysMCAST_LEAVE_GROUP = 0x51 - sysMCAST_JOIN_SOURCE_GROUP = 0x52 - sysMCAST_LEAVE_SOURCE_GROUP = 0x53 - sysMCAST_BLOCK_SOURCE = 0x54 - sysMCAST_UNBLOCK_SOURCE = 0x55 - - sysIPV6_PORTRANGE_DEFAULT = 0x0 - sysIPV6_PORTRANGE_HIGH = 0x1 - sysIPV6_PORTRANGE_LOW = 0x2 - - sizeofSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x88 - sizeofGroupSourceReq = 0x108 - - sizeofICMPv6Filter = 0x20 -) - -type sockaddrStorage struct { - Len uint8 - Family uint8 - X__ss_pad1 [6]int8 - X__ss_align int64 - X__ss_pad2 [112]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group sockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group sockaddrStorage - Source sockaddrStorage -} - -type icmpv6Filter struct { - Filt [8]uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_freebsd_arm.go b/vendor/golang.org/x/net/ipv6/zsys_freebsd_arm.go deleted file mode 100644 index cb8141f9c6..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_freebsd_arm.go +++ /dev/null @@ -1,124 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_freebsd.go - -package ipv6 - -const ( - sysIPV6_UNICAST_HOPS = 0x4 - sysIPV6_MULTICAST_IF = 0x9 - sysIPV6_MULTICAST_HOPS = 0xa - sysIPV6_MULTICAST_LOOP = 0xb - sysIPV6_JOIN_GROUP = 0xc - sysIPV6_LEAVE_GROUP = 0xd - sysIPV6_PORTRANGE = 0xe - sysICMP6_FILTER = 0x12 - - sysIPV6_CHECKSUM = 0x1a - sysIPV6_V6ONLY = 0x1b - - sysIPV6_IPSEC_POLICY = 0x1c - - sysIPV6_RTHDRDSTOPTS = 0x23 - - sysIPV6_RECVPKTINFO = 0x24 - sysIPV6_RECVHOPLIMIT = 0x25 - sysIPV6_RECVRTHDR = 0x26 - sysIPV6_RECVHOPOPTS = 0x27 - sysIPV6_RECVDSTOPTS = 0x28 - - sysIPV6_USE_MIN_MTU = 0x2a - sysIPV6_RECVPATHMTU = 0x2b - - sysIPV6_PATHMTU = 0x2c - - sysIPV6_PKTINFO = 0x2e - sysIPV6_HOPLIMIT = 0x2f - sysIPV6_NEXTHOP = 0x30 - sysIPV6_HOPOPTS = 0x31 - sysIPV6_DSTOPTS = 0x32 - sysIPV6_RTHDR = 0x33 - - sysIPV6_RECVTCLASS = 0x39 - - sysIPV6_AUTOFLOWLABEL = 0x3b - - sysIPV6_TCLASS = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_PREFER_TEMPADDR = 0x3f - - sysIPV6_BINDANY = 0x40 - - sysIPV6_MSFILTER = 0x4a - - sysMCAST_JOIN_GROUP = 0x50 - sysMCAST_LEAVE_GROUP = 0x51 - sysMCAST_JOIN_SOURCE_GROUP = 0x52 - sysMCAST_LEAVE_SOURCE_GROUP = 0x53 - sysMCAST_BLOCK_SOURCE = 0x54 - sysMCAST_UNBLOCK_SOURCE = 0x55 - - sysIPV6_PORTRANGE_DEFAULT = 0x0 - sysIPV6_PORTRANGE_HIGH = 0x1 - sysIPV6_PORTRANGE_LOW = 0x2 - - sizeofSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x88 - sizeofGroupSourceReq = 0x108 - - sizeofICMPv6Filter = 0x20 -) - -type sockaddrStorage struct { - Len uint8 - Family uint8 - X__ss_pad1 [6]int8 - X__ss_align int64 - X__ss_pad2 [112]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group sockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group sockaddrStorage - Source sockaddrStorage -} - -type icmpv6Filter struct { - Filt [8]uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_386.go b/vendor/golang.org/x/net/ipv6/zsys_linux_386.go deleted file mode 100644 index 73aa8c6dfc..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_386.go +++ /dev/null @@ -1,170 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x84 - sizeofGroupSourceReq = 0x104 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x8 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_amd64.go b/vendor/golang.org/x/net/ipv6/zsys_linux_amd64.go deleted file mode 100644 index b64f0157d7..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_amd64.go +++ /dev/null @@ -1,172 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x88 - sizeofGroupSourceReq = 0x108 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x10 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_arm.go b/vendor/golang.org/x/net/ipv6/zsys_linux_arm.go deleted file mode 100644 index 73aa8c6dfc..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_arm.go +++ /dev/null @@ -1,170 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x84 - sizeofGroupSourceReq = 0x104 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x8 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_arm64.go b/vendor/golang.org/x/net/ipv6/zsys_linux_arm64.go deleted file mode 100644 index b64f0157d7..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_arm64.go +++ /dev/null @@ -1,172 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x88 - sizeofGroupSourceReq = 0x108 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x10 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_mips.go b/vendor/golang.org/x/net/ipv6/zsys_linux_mips.go deleted file mode 100644 index 73aa8c6dfc..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_mips.go +++ /dev/null @@ -1,170 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x84 - sizeofGroupSourceReq = 0x104 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x8 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_mips64.go b/vendor/golang.org/x/net/ipv6/zsys_linux_mips64.go deleted file mode 100644 index b64f0157d7..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_mips64.go +++ /dev/null @@ -1,172 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x88 - sizeofGroupSourceReq = 0x108 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x10 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_mips64le.go b/vendor/golang.org/x/net/ipv6/zsys_linux_mips64le.go deleted file mode 100644 index b64f0157d7..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_mips64le.go +++ /dev/null @@ -1,172 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x88 - sizeofGroupSourceReq = 0x108 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x10 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_mipsle.go b/vendor/golang.org/x/net/ipv6/zsys_linux_mipsle.go deleted file mode 100644 index 73aa8c6dfc..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_mipsle.go +++ /dev/null @@ -1,170 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x84 - sizeofGroupSourceReq = 0x104 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x8 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_ppc.go b/vendor/golang.org/x/net/ipv6/zsys_linux_ppc.go deleted file mode 100644 index c9bf6a87ef..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_ppc.go +++ /dev/null @@ -1,170 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x84 - sizeofGroupSourceReq = 0x104 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x8 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_ppc64.go b/vendor/golang.org/x/net/ipv6/zsys_linux_ppc64.go deleted file mode 100644 index b64f0157d7..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_ppc64.go +++ /dev/null @@ -1,172 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x88 - sizeofGroupSourceReq = 0x108 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x10 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_ppc64le.go b/vendor/golang.org/x/net/ipv6/zsys_linux_ppc64le.go deleted file mode 100644 index b64f0157d7..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_ppc64le.go +++ /dev/null @@ -1,172 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x88 - sizeofGroupSourceReq = 0x108 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x10 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_linux_s390x.go b/vendor/golang.org/x/net/ipv6/zsys_linux_s390x.go deleted file mode 100644 index b64f0157d7..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_linux_s390x.go +++ /dev/null @@ -1,172 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package ipv6 - -const ( - sysIPV6_ADDRFORM = 0x1 - sysIPV6_2292PKTINFO = 0x2 - sysIPV6_2292HOPOPTS = 0x3 - sysIPV6_2292DSTOPTS = 0x4 - sysIPV6_2292RTHDR = 0x5 - sysIPV6_2292PKTOPTIONS = 0x6 - sysIPV6_CHECKSUM = 0x7 - sysIPV6_2292HOPLIMIT = 0x8 - sysIPV6_NEXTHOP = 0x9 - sysIPV6_FLOWINFO = 0xb - - sysIPV6_UNICAST_HOPS = 0x10 - sysIPV6_MULTICAST_IF = 0x11 - sysIPV6_MULTICAST_HOPS = 0x12 - sysIPV6_MULTICAST_LOOP = 0x13 - sysIPV6_ADD_MEMBERSHIP = 0x14 - sysIPV6_DROP_MEMBERSHIP = 0x15 - sysMCAST_JOIN_GROUP = 0x2a - sysMCAST_LEAVE_GROUP = 0x2d - sysMCAST_JOIN_SOURCE_GROUP = 0x2e - sysMCAST_LEAVE_SOURCE_GROUP = 0x2f - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_MSFILTER = 0x30 - sysIPV6_ROUTER_ALERT = 0x16 - sysIPV6_MTU_DISCOVER = 0x17 - sysIPV6_MTU = 0x18 - sysIPV6_RECVERR = 0x19 - sysIPV6_V6ONLY = 0x1a - sysIPV6_JOIN_ANYCAST = 0x1b - sysIPV6_LEAVE_ANYCAST = 0x1c - - sysIPV6_FLOWLABEL_MGR = 0x20 - sysIPV6_FLOWINFO_SEND = 0x21 - - sysIPV6_IPSEC_POLICY = 0x22 - sysIPV6_XFRM_POLICY = 0x23 - - sysIPV6_RECVPKTINFO = 0x31 - sysIPV6_PKTINFO = 0x32 - sysIPV6_RECVHOPLIMIT = 0x33 - sysIPV6_HOPLIMIT = 0x34 - sysIPV6_RECVHOPOPTS = 0x35 - sysIPV6_HOPOPTS = 0x36 - sysIPV6_RTHDRDSTOPTS = 0x37 - sysIPV6_RECVRTHDR = 0x38 - sysIPV6_RTHDR = 0x39 - sysIPV6_RECVDSTOPTS = 0x3a - sysIPV6_DSTOPTS = 0x3b - sysIPV6_RECVPATHMTU = 0x3c - sysIPV6_PATHMTU = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_RECVTCLASS = 0x42 - sysIPV6_TCLASS = 0x43 - - sysIPV6_ADDR_PREFERENCES = 0x48 - - sysIPV6_PREFER_SRC_TMP = 0x1 - sysIPV6_PREFER_SRC_PUBLIC = 0x2 - sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 - sysIPV6_PREFER_SRC_COA = 0x4 - sysIPV6_PREFER_SRC_HOME = 0x400 - sysIPV6_PREFER_SRC_CGA = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x800 - - sysIPV6_MINHOPCOUNT = 0x49 - - sysIPV6_ORIGDSTADDR = 0x4a - sysIPV6_RECVORIGDSTADDR = 0x4a - sysIPV6_TRANSPARENT = 0x4b - sysIPV6_UNICAST_IF = 0x4c - - sysICMPV6_FILTER = 0x1 - - sysICMPV6_FILTER_BLOCK = 0x1 - sysICMPV6_FILTER_PASS = 0x2 - sysICMPV6_FILTER_BLOCKOTHERS = 0x3 - sysICMPV6_FILTER_PASSONLY = 0x4 - - sysSOL_SOCKET = 0x1 - sysSO_ATTACH_FILTER = 0x1a - - sizeofKernelSockaddrStorage = 0x80 - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - sizeofIPv6FlowlabelReq = 0x20 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x88 - sizeofGroupSourceReq = 0x108 - - sizeofICMPv6Filter = 0x20 - - sizeofSockFprog = 0x10 -) - -type kernelSockaddrStorage struct { - Family uint16 - X__data [126]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex int32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6FlowlabelReq struct { - Dst [16]byte /* in6_addr */ - Label uint32 - Action uint8 - Share uint8 - Flags uint16 - Expires uint16 - Linger uint16 - X__flr_pad uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Ifindex int32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [4]byte - Group kernelSockaddrStorage - Source kernelSockaddrStorage -} - -type icmpv6Filter struct { - Data [8]uint32 -} - -type sockFProg struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *sockFilter -} - -type sockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_netbsd.go b/vendor/golang.org/x/net/ipv6/zsys_netbsd.go deleted file mode 100644 index bcada13b7a..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_netbsd.go +++ /dev/null @@ -1,84 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_netbsd.go - -package ipv6 - -const ( - sysIPV6_UNICAST_HOPS = 0x4 - sysIPV6_MULTICAST_IF = 0x9 - sysIPV6_MULTICAST_HOPS = 0xa - sysIPV6_MULTICAST_LOOP = 0xb - sysIPV6_JOIN_GROUP = 0xc - sysIPV6_LEAVE_GROUP = 0xd - sysIPV6_PORTRANGE = 0xe - sysICMP6_FILTER = 0x12 - - sysIPV6_CHECKSUM = 0x1a - sysIPV6_V6ONLY = 0x1b - - sysIPV6_IPSEC_POLICY = 0x1c - - sysIPV6_RTHDRDSTOPTS = 0x23 - - sysIPV6_RECVPKTINFO = 0x24 - sysIPV6_RECVHOPLIMIT = 0x25 - sysIPV6_RECVRTHDR = 0x26 - sysIPV6_RECVHOPOPTS = 0x27 - sysIPV6_RECVDSTOPTS = 0x28 - - sysIPV6_USE_MIN_MTU = 0x2a - sysIPV6_RECVPATHMTU = 0x2b - sysIPV6_PATHMTU = 0x2c - - sysIPV6_PKTINFO = 0x2e - sysIPV6_HOPLIMIT = 0x2f - sysIPV6_NEXTHOP = 0x30 - sysIPV6_HOPOPTS = 0x31 - sysIPV6_DSTOPTS = 0x32 - sysIPV6_RTHDR = 0x33 - - sysIPV6_RECVTCLASS = 0x39 - - sysIPV6_TCLASS = 0x3d - sysIPV6_DONTFRAG = 0x3e - - sysIPV6_PORTRANGE_DEFAULT = 0x0 - sysIPV6_PORTRANGE_HIGH = 0x1 - sysIPV6_PORTRANGE_LOW = 0x2 - - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - - sizeofIPv6Mreq = 0x14 - - sizeofICMPv6Filter = 0x20 -) - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type icmpv6Filter struct { - Filt [8]uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_openbsd.go b/vendor/golang.org/x/net/ipv6/zsys_openbsd.go deleted file mode 100644 index 86cf3c6379..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_openbsd.go +++ /dev/null @@ -1,93 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_openbsd.go - -package ipv6 - -const ( - sysIPV6_UNICAST_HOPS = 0x4 - sysIPV6_MULTICAST_IF = 0x9 - sysIPV6_MULTICAST_HOPS = 0xa - sysIPV6_MULTICAST_LOOP = 0xb - sysIPV6_JOIN_GROUP = 0xc - sysIPV6_LEAVE_GROUP = 0xd - sysIPV6_PORTRANGE = 0xe - sysICMP6_FILTER = 0x12 - - sysIPV6_CHECKSUM = 0x1a - sysIPV6_V6ONLY = 0x1b - - sysIPV6_RTHDRDSTOPTS = 0x23 - - sysIPV6_RECVPKTINFO = 0x24 - sysIPV6_RECVHOPLIMIT = 0x25 - sysIPV6_RECVRTHDR = 0x26 - sysIPV6_RECVHOPOPTS = 0x27 - sysIPV6_RECVDSTOPTS = 0x28 - - sysIPV6_USE_MIN_MTU = 0x2a - sysIPV6_RECVPATHMTU = 0x2b - - sysIPV6_PATHMTU = 0x2c - - sysIPV6_PKTINFO = 0x2e - sysIPV6_HOPLIMIT = 0x2f - sysIPV6_NEXTHOP = 0x30 - sysIPV6_HOPOPTS = 0x31 - sysIPV6_DSTOPTS = 0x32 - sysIPV6_RTHDR = 0x33 - - sysIPV6_AUTH_LEVEL = 0x35 - sysIPV6_ESP_TRANS_LEVEL = 0x36 - sysIPV6_ESP_NETWORK_LEVEL = 0x37 - sysIPSEC6_OUTSA = 0x38 - sysIPV6_RECVTCLASS = 0x39 - - sysIPV6_AUTOFLOWLABEL = 0x3b - sysIPV6_IPCOMP_LEVEL = 0x3c - - sysIPV6_TCLASS = 0x3d - sysIPV6_DONTFRAG = 0x3e - sysIPV6_PIPEX = 0x3f - - sysIPV6_RTABLE = 0x1021 - - sysIPV6_PORTRANGE_DEFAULT = 0x0 - sysIPV6_PORTRANGE_HIGH = 0x1 - sysIPV6_PORTRANGE_LOW = 0x2 - - sizeofSockaddrInet6 = 0x1c - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x20 - - sizeofIPv6Mreq = 0x14 - - sizeofICMPv6Filter = 0x20 -) - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type icmpv6Filter struct { - Filt [8]uint32 -} diff --git a/vendor/golang.org/x/net/ipv6/zsys_solaris.go b/vendor/golang.org/x/net/ipv6/zsys_solaris.go deleted file mode 100644 index cf1837dd2a..0000000000 --- a/vendor/golang.org/x/net/ipv6/zsys_solaris.go +++ /dev/null @@ -1,131 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_solaris.go - -package ipv6 - -const ( - sysIPV6_UNICAST_HOPS = 0x5 - sysIPV6_MULTICAST_IF = 0x6 - sysIPV6_MULTICAST_HOPS = 0x7 - sysIPV6_MULTICAST_LOOP = 0x8 - sysIPV6_JOIN_GROUP = 0x9 - sysIPV6_LEAVE_GROUP = 0xa - - sysIPV6_PKTINFO = 0xb - - sysIPV6_HOPLIMIT = 0xc - sysIPV6_NEXTHOP = 0xd - sysIPV6_HOPOPTS = 0xe - sysIPV6_DSTOPTS = 0xf - - sysIPV6_RTHDR = 0x10 - sysIPV6_RTHDRDSTOPTS = 0x11 - - sysIPV6_RECVPKTINFO = 0x12 - sysIPV6_RECVHOPLIMIT = 0x13 - sysIPV6_RECVHOPOPTS = 0x14 - - sysIPV6_RECVRTHDR = 0x16 - - sysIPV6_RECVRTHDRDSTOPTS = 0x17 - - sysIPV6_CHECKSUM = 0x18 - sysIPV6_RECVTCLASS = 0x19 - sysIPV6_USE_MIN_MTU = 0x20 - sysIPV6_DONTFRAG = 0x21 - sysIPV6_SEC_OPT = 0x22 - sysIPV6_SRC_PREFERENCES = 0x23 - sysIPV6_RECVPATHMTU = 0x24 - sysIPV6_PATHMTU = 0x25 - sysIPV6_TCLASS = 0x26 - sysIPV6_V6ONLY = 0x27 - - sysIPV6_RECVDSTOPTS = 0x28 - - sysMCAST_JOIN_GROUP = 0x29 - sysMCAST_LEAVE_GROUP = 0x2a - sysMCAST_BLOCK_SOURCE = 0x2b - sysMCAST_UNBLOCK_SOURCE = 0x2c - sysMCAST_JOIN_SOURCE_GROUP = 0x2d - sysMCAST_LEAVE_SOURCE_GROUP = 0x2e - - sysIPV6_PREFER_SRC_HOME = 0x1 - sysIPV6_PREFER_SRC_COA = 0x2 - sysIPV6_PREFER_SRC_PUBLIC = 0x4 - sysIPV6_PREFER_SRC_TMP = 0x8 - sysIPV6_PREFER_SRC_NONCGA = 0x10 - sysIPV6_PREFER_SRC_CGA = 0x20 - - sysIPV6_PREFER_SRC_MIPMASK = 0x3 - sysIPV6_PREFER_SRC_MIPDEFAULT = 0x1 - sysIPV6_PREFER_SRC_TMPMASK = 0xc - sysIPV6_PREFER_SRC_TMPDEFAULT = 0x4 - sysIPV6_PREFER_SRC_CGAMASK = 0x30 - sysIPV6_PREFER_SRC_CGADEFAULT = 0x10 - - sysIPV6_PREFER_SRC_MASK = 0x3f - - sysIPV6_PREFER_SRC_DEFAULT = 0x15 - - sysIPV6_BOUND_IF = 0x41 - sysIPV6_UNSPEC_SRC = 0x42 - - sysICMP6_FILTER = 0x1 - - sizeofSockaddrStorage = 0x100 - sizeofSockaddrInet6 = 0x20 - sizeofInet6Pktinfo = 0x14 - sizeofIPv6Mtuinfo = 0x24 - - sizeofIPv6Mreq = 0x14 - sizeofGroupReq = 0x104 - sizeofGroupSourceReq = 0x204 - - sizeofICMPv6Filter = 0x20 -) - -type sockaddrStorage struct { - Family uint16 - X_ss_pad1 [6]int8 - X_ss_align float64 - X_ss_pad2 [240]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 - X__sin6_src_id uint32 -} - -type inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type ipv6Mtuinfo struct { - Addr sockaddrInet6 - Mtu uint32 -} - -type ipv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type groupReq struct { - Interface uint32 - Pad_cgo_0 [256]byte -} - -type groupSourceReq struct { - Interface uint32 - Pad_cgo_0 [256]byte - Pad_cgo_1 [256]byte -} - -type icmpv6Filter struct { - X__icmp6_filt [8]uint32 -} diff --git a/vendor/vendor.json b/vendor/vendor.json index 9568a1e27d..76ac677414 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -332,6 +332,12 @@ "revision": "18b2b544842cab16f3ff418fb5290d8f2896a069", "revisionTime": "2018-06-19T03:18:29Z" }, + { + "checksumSHA1": "BqYzEsFXlvPUtDV0f6I9AIkyCmI=", + "path": "github.com/admpub/go-isatty", + "revision": "da60ac76bf7019a8b005f8dd1ad9d1a0e6434155", + "revisionTime": "2019-07-08T05:43:38Z" + }, { "checksumSHA1": "ldUoX2UET664gw2oAUp9YR98XZc=", "path": "github.com/admpub/go-phantomjs-fetcher", @@ -345,16 +351,16 @@ "revisionTime": "2019-05-09T15:24:50Z" }, { - "checksumSHA1": "52G0QF6gbJ/Dp+PuHFy5+GyxRho=", + "checksumSHA1": "VP3anyh0taq6wgbX0WIVdbwUmqI=", "path": "github.com/admpub/go-pretty/table", - "revision": "b096cc397c2e7490dfdc34f2b553501b30018203", - "revisionTime": "2019-05-09T15:24:50Z" + "revision": "566e5c19f609cbeb3b7aa381a005e7cb2effc698", + "revisionTime": "2019-07-28T12:40:51Z" }, { - "checksumSHA1": "3rmgAn73P/hom9/lDYRgvByJ0Xg=", + "checksumSHA1": "hD81Wx//ad6kBXu/bIFTJpg0tqI=", "path": "github.com/admpub/go-pretty/text", - "revision": "b096cc397c2e7490dfdc34f2b553501b30018203", - "revisionTime": "2019-05-09T15:24:50Z" + "revision": "566e5c19f609cbeb3b7aa381a005e7cb2effc698", + "revisionTime": "2019-07-28T12:40:51Z" }, { "checksumSHA1": "HNy5ugQBnIvfpSEFaQsWvLUb458=", @@ -1031,226 +1037,226 @@ "revisionTime": "2019-07-04T15:46:56Z" }, { - "checksumSHA1": "22kX0V02PDzzmd8Oorn5JYvaqWI=", + "checksumSHA1": "CQaqa+UaPx3UfVOisPQhXQIWra4=", "path": "github.com/caddyserver/caddy", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "JRu12Cm5DJgJL7x6yc9YxhhJ7S0=", "path": "github.com/caddyserver/caddy/caddyfile", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "z9FSU4cwmjD5Paxu8CeMm93SkIA=", "path": "github.com/caddyserver/caddy/caddyhttp", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { - "checksumSHA1": "ha4zu7vW2c5hhscDduiBPoMOFOw=", + "checksumSHA1": "adVmCdmMOSNrMp9lqSEvQCStVMU=", "path": "github.com/caddyserver/caddy/caddyhttp/basicauth", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "uKL96RZedgwnIKEoNevlr/UQ2Yw=", "path": "github.com/caddyserver/caddy/caddyhttp/bind", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { - "checksumSHA1": "3HeTqZcdcahlVNBz7hFQscay85s=", + "checksumSHA1": "2ZOclDppH73oDtYBnhtB/rFEbRI=", "path": "github.com/caddyserver/caddy/caddyhttp/browse", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "yMo4b0HYfj6JujZnSb02nS1j4B4=", "path": "github.com/caddyserver/caddy/caddyhttp/errors", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "1e55nmhjN/w102nW4UXQjaTpjJ0=", "path": "github.com/caddyserver/caddy/caddyhttp/expvar", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "1qGffsCD90Enr/9nmTprncS7QAs=", "path": "github.com/caddyserver/caddy/caddyhttp/extensions", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "+kKhMI3Ui/0OCKyYf0TiMVTingw=", "path": "github.com/caddyserver/caddy/caddyhttp/fastcgi", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "gd946M4niEZyKBi8D3zwaMVBmA8=", "path": "github.com/caddyserver/caddy/caddyhttp/gzip", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "P5mDkTXaKR0wWhgpqFodpZ8KzPY=", "path": "github.com/caddyserver/caddy/caddyhttp/header", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { - "checksumSHA1": "FnLzmwkRBZkk2BJuHu1vgFgg+sY=", + "checksumSHA1": "gWxmeIRjT2hmtUDG+Sc0Z0yUNlE=", "path": "github.com/caddyserver/caddy/caddyhttp/httpserver", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "OfHVq4lIEplow0mLYSgBXQrV6r0=", "path": "github.com/caddyserver/caddy/caddyhttp/index", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "L0UhdqzaONFy0B0qdSYbRRLtYuU=", "path": "github.com/caddyserver/caddy/caddyhttp/internalsrv", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "v394rodBOuGUrOfClRFHWLf75ek=", "path": "github.com/caddyserver/caddy/caddyhttp/limits", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "aVDRr9GXjpSx45iHLoiMBohafEQ=", "path": "github.com/caddyserver/caddy/caddyhttp/log", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "Qu4mqU2xer1OC9bTPoHdkz5O/lA=", "path": "github.com/caddyserver/caddy/caddyhttp/markdown", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "MiZ4KHhEgnfkOeX3zJzwCFt6+Wo=", "path": "github.com/caddyserver/caddy/caddyhttp/markdown/metadata", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "Kn2QODSsOjlJf+DyjgX7lQ3Y5ww=", "path": "github.com/caddyserver/caddy/caddyhttp/markdown/summary", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "R3Hb4xmg/K0/i9qkPRYE548imw8=", "path": "github.com/caddyserver/caddy/caddyhttp/mime", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "Q+eqpCqbHUOGrpuBC8+jRtSjEgc=", "path": "github.com/caddyserver/caddy/caddyhttp/pprof", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { - "checksumSHA1": "cLx3ybhMVCeg/CjEIRJtIrWJhi4=", + "checksumSHA1": "ua6VaC29DxACStaHvyM3bswAi4U=", "path": "github.com/caddyserver/caddy/caddyhttp/proxy", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "kAf43ogpRLXFew3f6HJgDLbgaKo=", "path": "github.com/caddyserver/caddy/caddyhttp/push", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "Rscre/9cxlz+h/e/3a9L7LK9kLw=", "path": "github.com/caddyserver/caddy/caddyhttp/redirect", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { - "checksumSHA1": "wWD4nlR0f7kUFo3U6rRCoAg8rSQ=", + "checksumSHA1": "atMHY4lefdd7OecOgyM5XhIUG8s=", "path": "github.com/caddyserver/caddy/caddyhttp/requestid", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "azjk35HygzAfVHu2IHPchnQPVas=", "path": "github.com/caddyserver/caddy/caddyhttp/rewrite", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "aKxlRuYFQxuYrIIjigpgKeYaciw=", "path": "github.com/caddyserver/caddy/caddyhttp/root", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { - "checksumSHA1": "cJxPV1YikxJbzzzymX4KhNvpOVo=", + "checksumSHA1": "0qlkLHNRx7++sHBnlP2nx61dS+8=", "path": "github.com/caddyserver/caddy/caddyhttp/staticfiles", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "0vHCkaTeFgl4EayTuZLU6+07ims=", "path": "github.com/caddyserver/caddy/caddyhttp/status", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "ChbtRLys7t8BFRq4jKn68t/QMOU=", "path": "github.com/caddyserver/caddy/caddyhttp/templates", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "HxmQFT9f4EGTexkMH/FD6JgCwTI=", "path": "github.com/caddyserver/caddy/caddyhttp/timeouts", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { - "checksumSHA1": "RViv1CYv/0CRBy046PqGIQI3ADY=", + "checksumSHA1": "KbKQsFPXRWCv+HQCss2poYvrktI=", "path": "github.com/caddyserver/caddy/caddyhttp/websocket", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { - "checksumSHA1": "7RSLB2qzgm4EKhLmuWpOs2Tdqfk=", + "checksumSHA1": "7VNTdXvFeA9XZMh8AT9QqeaCch0=", "path": "github.com/caddyserver/caddy/caddytls", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { - "checksumSHA1": "yh+7itHbtyrkK9yrsm/Yn8Ct62o=", + "checksumSHA1": "Cp2GiTdU2VW8Oe588aol7Q7CZAE=", "path": "github.com/caddyserver/caddy/onevent", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "R8GXjgav0IIB2ETk0hL/yxkxqzI=", "path": "github.com/caddyserver/caddy/onevent/hook", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "8ufPrU8ju1XUcCFTJJ0aMy8DCfg=", "path": "github.com/caddyserver/caddy/telemetry", - "revision": "f6ee100bae9c0de566a2f7ae531113be0a9a0b83", - "revisionTime": "2019-07-02T19:08:31Z" + "revision": "0ba427a6f44edb5169e022e3cbc23f7b6de35a81", + "revisionTime": "2019-07-19T19:29:49Z" }, { "checksumSHA1": "xhz5SprqgVRCF8BazSJkYBPdXYA=", @@ -1259,12 +1265,6 @@ "revision": "b9bafc582ce3ef7263217fdfe22e2a3e59f0d216", "revisionTime": "2019-05-09T11:58:24Z" }, - { - "checksumSHA1": "PYXuf7wvcj492uWhjvmXlyyQUYc=", - "path": "github.com/cheekybits/genny/generic", - "revision": "df3d48aa411e8e28498e452e42cc1e40498a9e58", - "revisionTime": "2019-06-11T08:46:15Z" - }, { "checksumSHA1": "AKfVkkAyUy2805EQl4cfiKetlmc=", "path": "github.com/chromedp/cdproto", @@ -2350,48 +2350,6 @@ "revision": "e2917784d0fb41e3b84847f84302a287a2988f7a", "revisionTime": "2016-11-27T12:35:54Z" }, - { - "checksumSHA1": "tyBJkJQ8R/T3er4LHDuxMqE3D+o=", - "path": "github.com/lucas-clemente/quic-go/internal/ackhandler", - "revision": "3dcbaee89e97ce15e4b9f1167e88a4184bb21e2d", - "revisionTime": "2019-07-01T07:44:43Z" - }, - { - "checksumSHA1": "56X0wvNj7vc3TNmknwUkO5U8Vi4=", - "path": "github.com/lucas-clemente/quic-go/internal/congestion", - "revision": "3dcbaee89e97ce15e4b9f1167e88a4184bb21e2d", - "revisionTime": "2019-07-01T07:44:43Z" - }, - { - "checksumSHA1": "HDkX616FVT7b8nZ0H5poD3xzD2I=", - "path": "github.com/lucas-clemente/quic-go/internal/flowcontrol", - "revision": "3dcbaee89e97ce15e4b9f1167e88a4184bb21e2d", - "revisionTime": "2019-07-01T07:44:43Z" - }, - { - "checksumSHA1": "hABDVsjoiiEqbGmnjhO5GsHBzSY=", - "path": "github.com/lucas-clemente/quic-go/internal/handshake", - "revision": "3dcbaee89e97ce15e4b9f1167e88a4184bb21e2d", - "revisionTime": "2019-07-01T07:44:43Z" - }, - { - "checksumSHA1": "o+eY4M2c2qXFhuNzWl/fpzT6gog=", - "path": "github.com/lucas-clemente/quic-go/internal/protocol", - "revision": "3dcbaee89e97ce15e4b9f1167e88a4184bb21e2d", - "revisionTime": "2019-07-01T07:44:43Z" - }, - { - "checksumSHA1": "eOBm9o3NgesqqCvlzbmtxlPtJf0=", - "path": "github.com/lucas-clemente/quic-go/internal/qerr", - "revision": "3dcbaee89e97ce15e4b9f1167e88a4184bb21e2d", - "revisionTime": "2019-07-01T07:44:43Z" - }, - { - "checksumSHA1": "1+6PeuB5gWGUP1G2PjLkN09XaOk=", - "path": "github.com/lucas-clemente/quic-go/internal/wire", - "revision": "3dcbaee89e97ce15e4b9f1167e88a4184bb21e2d", - "revisionTime": "2019-07-01T07:44:43Z" - }, { "checksumSHA1": "/6mNcj1JQ1KnGH98BBbp1LyQydg=", "origin": "github.com/mholt/caddy/vendor/github.com/lucas-clemente/quic-go/protocol", @@ -2406,18 +2364,6 @@ "revision": "e2917784d0fb41e3b84847f84302a287a2988f7a", "revisionTime": "2016-11-27T12:35:54Z" }, - { - "checksumSHA1": "QIwVxQPQYFoXXGDdHk7yCKSe22U=", - "path": "github.com/lucas-clemente/quic-go/quictrace", - "revision": "3dcbaee89e97ce15e4b9f1167e88a4184bb21e2d", - "revisionTime": "2019-07-01T07:44:43Z" - }, - { - "checksumSHA1": "BEmwZjenZ5kQw704NYtyHqaW8NQ=", - "path": "github.com/lucas-clemente/quic-go/quictrace/pb", - "revision": "3dcbaee89e97ce15e4b9f1167e88a4184bb21e2d", - "revisionTime": "2019-07-01T07:44:43Z" - }, { "checksumSHA1": "g8EyPzqekr2jmCUsEwIIZSyttgQ=", "origin": "github.com/mholt/caddy/vendor/github.com/lucas-clemente/quic-go/utils", @@ -2623,12 +2569,6 @@ "revision": "39d29b2c1a1ad66dddd33063b8389f4e25ddcef5", "revisionTime": "2019-04-03T18:46:37Z" }, - { - "checksumSHA1": "fV/dWDjobpxleSwnZ4lR1/8hDu4=", - "path": "github.com/marten-seemann/qtls", - "revision": "65ca381cd298d7e0aef0de8ba523a870ec5a96fe", - "revisionTime": "2019-03-29T07:59:07Z" - }, { "checksumSHA1": "17pyIRa4+1+bbKXX92qPB7znaPI=", "origin": "github.com/admpub/qrcode/vendor/github.com/maruel/rs", @@ -3000,13 +2940,6 @@ "revision": "185b4288413d2a0dd0806f78c90dde719829e5ae", "revisionTime": "2018-10-05T14:02:18Z" }, - { - "checksumSHA1": "Kmjs49lbjGmlgUPx3pks0tVDed0=", - "origin": "github.com/nats-io/nats-streaming-server/vendor/github.com/prometheus/procfs/internal/fs", - "path": "github.com/prometheus/procfs/internal/fs", - "revision": "502d27d6cb364ae4517675687c7d85625099c523", - "revisionTime": "2019-07-09T18:21:20Z" - }, { "checksumSHA1": "8E1IbrgtLBee7J404VKPyoI+qsk=", "path": "github.com/prometheus/procfs/internal/util", @@ -3375,10 +3308,10 @@ "revisionTime": "2018-07-27T14:15:59Z" }, { - "checksumSHA1": "6Fyr+CF4oKPdATmMzNuCxjauyik=", + "checksumSHA1": "HZSUUVlrks7E82ZrA/oFEYbPe5o=", "path": "github.com/webx-top/com", - "revision": "35b72a2f09167d084b4a6aea2309b0a8b3840ea7", - "revisionTime": "2019-07-28T09:02:33Z" + "revision": "d513d413914611f235e1c35a6a1f496636b51fa4", + "revisionTime": "2019-07-28T12:28:30Z" }, { "checksumSHA1": "g9Su7l1p/0yOFZMZiK4rL9Y9Zso=", @@ -3750,18 +3683,6 @@ "revision": "4def268fd1a49955bfb3dda92fe3db4f924f2285", "revisionTime": "2019-07-01T08:59:26Z" }, - { - "checksumSHA1": "1ezNasqd516o9HG59beqc5s+2Ro=", - "path": "golang.org/x/crypto/cryptobyte", - "revision": "4def268fd1a49955bfb3dda92fe3db4f924f2285", - "revisionTime": "2019-07-01T08:59:26Z" - }, - { - "checksumSHA1": "YEoV2AiZZPDuF7pMVzDt7buS9gc=", - "path": "golang.org/x/crypto/cryptobyte/asn1", - "revision": "4def268fd1a49955bfb3dda92fe3db4f924f2285", - "revisionTime": "2019-07-01T08:59:26Z" - }, { "checksumSHA1": "VhYw+/2jaraoUukY6CBcCUQbLtU=", "origin": "github.com/mholt/caddy/vendor/golang.org/x/crypto/curve25519", @@ -3982,12 +3903,6 @@ "revision": "f5e5bdd778241bfefa8627f7124c39cd6ad8d74f", "revisionTime": "2018-10-01T16:28:04Z" }, - { - "checksumSHA1": "pCY4YtdNKVBYRbNvODjx8hj0hIs=", - "path": "golang.org/x/net/http/httpguts", - "revision": "3b0461eec859c4b73bb64fdc8285971fd33e3938", - "revisionTime": "2019-06-20T19:42:36Z" - }, { "checksumSHA1": "FI29wkykYDjZYqVbRrYQSzNqf70=", "origin": "github.com/mholt/caddy/vendor/golang.org/x/net/http2", @@ -4036,13 +3951,6 @@ "revision": "f6c265d783d6c18c57cc4844e8db5a348ebff0a2", "revisionTime": "2018-07-29T04:33:30Z" }, - { - "checksumSHA1": "hDszlYGI8m9puPsEIDr59ccTiF8=", - "origin": "github.com/go-acme/lego/vendor/golang.org/x/net/ipv6", - "path": "golang.org/x/net/ipv6", - "revision": "6647ce7b1de3dd120968ffcd2d03181b4000d3c3", - "revisionTime": "2019-06-27T17:30:10Z" - }, { "checksumSHA1": "M67VbeXMkCwHoiKOrKN7gd4TOFg=", "origin": "github.com/mholt/caddy/vendor/golang.org/x/net/lex/httplex",