diff --git a/libnetwork/libnetwork_test.go b/libnetwork/libnetwork_test.go index e7e0ad5c95..8b18070eb7 100644 --- a/libnetwork/libnetwork_test.go +++ b/libnetwork/libnetwork_test.go @@ -210,7 +210,7 @@ func TestUnknownDriver(t *testing.T) { t.Fatal("Expected to fail. But instead succeeded") } - if errdefs.IsNotFound(err) { + if !errdefs.IsNotFound(err) { t.Fatalf("Did not fail with expected error. Actual error: %v", err) } } diff --git a/libnetwork/vendor.conf b/libnetwork/vendor.conf index 370c66c9a9..5237c5588a 100644 --- a/libnetwork/vendor.conf +++ b/libnetwork/vendor.conf @@ -14,8 +14,8 @@ github.com/coreos/go-systemd v17 github.com/coreos/pkg fa29b1d70f0beaddd4c7021607cc3c3be8ce94b8 github.com/deckarep/golang-set ef32fa3046d9f249d399f98ebaf9be944430fd1d +github.com/docker/docker 162ba6016def672690ee4a1f3978368853a1e149 github.com/docker/go-connections 7beb39f0b969b075d1325fecb092faf27fd357b6 -github.com/docker/docker 71cd53e4a197b303c6ba086bd584ffd67a884281 github.com/docker/go-events 9461782956ad83b30282bf90e31fa6a70c255ba9 github.com/docker/go-units 9e638d38cf6977a37a8ea0078f3ee75a7cdb2dd1 github.com/docker/libkv 1d8431073ae03cdaedb198a89722f3aab6d418ef diff --git a/libnetwork/vendor/github.com/containerd/console/tc_openbsd_cgo.go b/libnetwork/vendor/github.com/containerd/console/tc_openbsd_cgo.go deleted file mode 100644 index f0cec06a72..0000000000 --- a/libnetwork/vendor/github.com/containerd/console/tc_openbsd_cgo.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build openbsd,cgo - -/* - Copyright The containerd 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 console - -import ( - "os" - - "golang.org/x/sys/unix" -) - -//#include -import "C" - -const ( - cmdTcGet = unix.TIOCGETA - cmdTcSet = unix.TIOCSETA -) - -// ptsname retrieves the name of the first available pts for the given master. -func ptsname(f *os.File) (string, error) { - ptspath, err := C.ptsname(C.int(f.Fd())) - if err != nil { - return "", err - } - return C.GoString(ptspath), nil -} - -// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f. -// unlockpt should be called before opening the slave side of a pty. -func unlockpt(f *os.File) error { - if _, err := C.grantpt(C.int(f.Fd())); err != nil { - return err - } - return nil -} diff --git a/libnetwork/vendor/github.com/containerd/console/tc_openbsd_nocgo.go b/libnetwork/vendor/github.com/containerd/console/tc_openbsd_nocgo.go deleted file mode 100644 index daccce2058..0000000000 --- a/libnetwork/vendor/github.com/containerd/console/tc_openbsd_nocgo.go +++ /dev/null @@ -1,47 +0,0 @@ -// +build openbsd,!cgo - -/* - Copyright The containerd 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. -*/ - -// -// Implementing the functions below requires cgo support. Non-cgo stubs -// versions are defined below to enable cross-compilation of source code -// that depends on these functions, but the resultant cross-compiled -// binaries cannot actually be used. If the stub function(s) below are -// actually invoked they will display an error message and cause the -// calling process to exit. -// - -package console - -import ( - "os" - - "golang.org/x/sys/unix" -) - -const ( - cmdTcGet = unix.TIOCGETA - cmdTcSet = unix.TIOCSETA -) - -func ptsname(f *os.File) (string, error) { - panic("ptsname() support requires cgo.") -} - -func unlockpt(f *os.File) error { - panic("unlockpt() support requires cgo.") -} diff --git a/libnetwork/vendor/github.com/coreos/go-systemd/NOTICE b/libnetwork/vendor/github.com/coreos/go-systemd/NOTICE deleted file mode 100644 index 23a0ada2fb..0000000000 --- a/libnetwork/vendor/github.com/coreos/go-systemd/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -CoreOS Project -Copyright 2018 CoreOS, Inc - -This product includes software developed at CoreOS, Inc. -(http://www.coreos.com/). diff --git a/libnetwork/vendor/github.com/coreos/go-systemd/util/util_cgo.go b/libnetwork/vendor/github.com/coreos/go-systemd/util/util_cgo.go deleted file mode 100644 index 6269bc7323..0000000000 --- a/libnetwork/vendor/github.com/coreos/go-systemd/util/util_cgo.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright 2016 CoreOS, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build cgo - -package util - -// #include -// #include -// #include -// -// int -// my_sd_pid_get_owner_uid(void *f, pid_t pid, uid_t *uid) -// { -// int (*sd_pid_get_owner_uid)(pid_t, uid_t *); -// -// sd_pid_get_owner_uid = (int (*)(pid_t, uid_t *))f; -// return sd_pid_get_owner_uid(pid, uid); -// } -// -// int -// my_sd_pid_get_unit(void *f, pid_t pid, char **unit) -// { -// int (*sd_pid_get_unit)(pid_t, char **); -// -// sd_pid_get_unit = (int (*)(pid_t, char **))f; -// return sd_pid_get_unit(pid, unit); -// } -// -// int -// my_sd_pid_get_slice(void *f, pid_t pid, char **slice) -// { -// int (*sd_pid_get_slice)(pid_t, char **); -// -// sd_pid_get_slice = (int (*)(pid_t, char **))f; -// return sd_pid_get_slice(pid, slice); -// } -// -// int -// am_session_leader() -// { -// return (getsid(0) == getpid()); -// } -import "C" -import ( - "fmt" - "syscall" - "unsafe" - - "github.com/coreos/pkg/dlopen" -) - -var libsystemdNames = []string{ - // systemd < 209 - "libsystemd-login.so.0", - "libsystemd-login.so", - - // systemd >= 209 merged libsystemd-login into libsystemd proper - "libsystemd.so.0", - "libsystemd.so", -} - -func getRunningSlice() (slice string, err error) { - var h *dlopen.LibHandle - h, err = dlopen.GetHandle(libsystemdNames) - if err != nil { - return - } - defer func() { - if err1 := h.Close(); err1 != nil { - err = err1 - } - }() - - sd_pid_get_slice, err := h.GetSymbolPointer("sd_pid_get_slice") - if err != nil { - return - } - - var s string - sl := C.CString(s) - defer C.free(unsafe.Pointer(sl)) - - ret := C.my_sd_pid_get_slice(sd_pid_get_slice, 0, &sl) - if ret < 0 { - err = fmt.Errorf("error calling sd_pid_get_slice: %v", syscall.Errno(-ret)) - return - } - - return C.GoString(sl), nil -} - -func runningFromSystemService() (ret bool, err error) { - var h *dlopen.LibHandle - h, err = dlopen.GetHandle(libsystemdNames) - if err != nil { - return - } - defer func() { - if err1 := h.Close(); err1 != nil { - err = err1 - } - }() - - sd_pid_get_owner_uid, err := h.GetSymbolPointer("sd_pid_get_owner_uid") - if err != nil { - return - } - - var uid C.uid_t - errno := C.my_sd_pid_get_owner_uid(sd_pid_get_owner_uid, 0, &uid) - serrno := syscall.Errno(-errno) - // when we're running from a unit file, sd_pid_get_owner_uid returns - // ENOENT (systemd <220), ENXIO (systemd 220-223), or ENODATA - // (systemd >=234) - switch { - case errno >= 0: - ret = false - case serrno == syscall.ENOENT, serrno == syscall.ENXIO, serrno == syscall.ENODATA: - // Since the implementation of sessions in systemd relies on - // the `pam_systemd` module, using the sd_pid_get_owner_uid - // heuristic alone can result in false positives if that module - // (or PAM itself) is not present or properly configured on the - // system. As such, we also check if we're the session leader, - // which should be the case if we're invoked from a unit file, - // but not if e.g. we're invoked from the command line from a - // user's login session - ret = C.am_session_leader() == 1 - default: - err = fmt.Errorf("error calling sd_pid_get_owner_uid: %v", syscall.Errno(-errno)) - } - return -} - -func currentUnitName() (unit string, err error) { - var h *dlopen.LibHandle - h, err = dlopen.GetHandle(libsystemdNames) - if err != nil { - return - } - defer func() { - if err1 := h.Close(); err1 != nil { - err = err1 - } - }() - - sd_pid_get_unit, err := h.GetSymbolPointer("sd_pid_get_unit") - if err != nil { - return - } - - var s string - u := C.CString(s) - defer C.free(unsafe.Pointer(u)) - - ret := C.my_sd_pid_get_unit(sd_pid_get_unit, 0, &u) - if ret < 0 { - err = fmt.Errorf("error calling sd_pid_get_unit: %v", syscall.Errno(-ret)) - return - } - - unit = C.GoString(u) - return -} diff --git a/libnetwork/vendor/github.com/coreos/go-systemd/util/util_stub.go b/libnetwork/vendor/github.com/coreos/go-systemd/util/util_stub.go deleted file mode 100644 index 477589e122..0000000000 --- a/libnetwork/vendor/github.com/coreos/go-systemd/util/util_stub.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2016 CoreOS, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build !cgo - -package util - -func getRunningSlice() (string, error) { return "", ErrNoCGO } - -func runningFromSystemService() (bool, error) { return false, ErrNoCGO } - -func currentUnitName() (string, error) { return "", ErrNoCGO } diff --git a/libnetwork/vendor/github.com/coreos/pkg/NOTICE b/libnetwork/vendor/github.com/coreos/pkg/NOTICE deleted file mode 100644 index b39ddfa5cb..0000000000 --- a/libnetwork/vendor/github.com/coreos/pkg/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -CoreOS Project -Copyright 2014 CoreOS, Inc - -This product includes software developed at CoreOS, Inc. -(http://www.coreos.com/). diff --git a/libnetwork/vendor/github.com/coreos/pkg/README.md b/libnetwork/vendor/github.com/coreos/pkg/README.md deleted file mode 100644 index ca68a07f0f..0000000000 --- a/libnetwork/vendor/github.com/coreos/pkg/README.md +++ /dev/null @@ -1,4 +0,0 @@ -a collection of go utility packages - -[![Build Status](https://travis-ci.org/coreos/pkg.png?branch=master)](https://travis-ci.org/coreos/pkg) -[![Godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/coreos/pkg) diff --git a/libnetwork/vendor/github.com/coreos/pkg/dlopen/dlopen.go b/libnetwork/vendor/github.com/coreos/pkg/dlopen/dlopen.go deleted file mode 100644 index 23774f612e..0000000000 --- a/libnetwork/vendor/github.com/coreos/pkg/dlopen/dlopen.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2016 CoreOS, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package dlopen provides some convenience functions to dlopen a library and -// get its symbols. -package dlopen - -// #cgo LDFLAGS: -ldl -// #include -// #include -import "C" -import ( - "errors" - "fmt" - "unsafe" -) - -var ErrSoNotFound = errors.New("unable to open a handle to the library") - -// LibHandle represents an open handle to a library (.so) -type LibHandle struct { - Handle unsafe.Pointer - Libname string -} - -// GetHandle tries to get a handle to a library (.so), attempting to access it -// by the names specified in libs and returning the first that is successfully -// opened. Callers are responsible for closing the handler. If no library can -// be successfully opened, an error is returned. -func GetHandle(libs []string) (*LibHandle, error) { - for _, name := range libs { - libname := C.CString(name) - defer C.free(unsafe.Pointer(libname)) - handle := C.dlopen(libname, C.RTLD_LAZY) - if handle != nil { - h := &LibHandle{ - Handle: handle, - Libname: name, - } - return h, nil - } - } - return nil, ErrSoNotFound -} - -// GetSymbolPointer takes a symbol name and returns a pointer to the symbol. -func (l *LibHandle) GetSymbolPointer(symbol string) (unsafe.Pointer, error) { - sym := C.CString(symbol) - defer C.free(unsafe.Pointer(sym)) - - C.dlerror() - p := C.dlsym(l.Handle, sym) - e := C.dlerror() - if e != nil { - return nil, fmt.Errorf("error resolving symbol %q: %v", symbol, errors.New(C.GoString(e))) - } - - return p, nil -} - -// Close closes a LibHandle. -func (l *LibHandle) Close() error { - C.dlerror() - C.dlclose(l.Handle) - e := C.dlerror() - if e != nil { - return fmt.Errorf("error closing %v: %v", l.Libname, errors.New(C.GoString(e))) - } - - return nil -} diff --git a/libnetwork/vendor/github.com/coreos/pkg/dlopen/dlopen_example.go b/libnetwork/vendor/github.com/coreos/pkg/dlopen/dlopen_example.go deleted file mode 100644 index 48a660104f..0000000000 --- a/libnetwork/vendor/github.com/coreos/pkg/dlopen/dlopen_example.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2015 CoreOS, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// +build linux - -package dlopen - -// #include -// #include -// -// int -// my_strlen(void *f, const char *s) -// { -// size_t (*strlen)(const char *); -// -// strlen = (size_t (*)(const char *))f; -// return strlen(s); -// } -import "C" - -import ( - "fmt" - "unsafe" -) - -func strlen(libs []string, s string) (int, error) { - h, err := GetHandle(libs) - if err != nil { - return -1, fmt.Errorf(`couldn't get a handle to the library: %v`, err) - } - defer h.Close() - - f := "strlen" - cs := C.CString(s) - defer C.free(unsafe.Pointer(cs)) - - strlen, err := h.GetSymbolPointer(f) - if err != nil { - return -1, fmt.Errorf(`couldn't get symbol %q: %v`, f, err) - } - - len := C.my_strlen(strlen, cs) - - return int(len), nil -} diff --git a/libnetwork/vendor/github.com/cyphar/filepath-securejoin/README.md b/libnetwork/vendor/github.com/cyphar/filepath-securejoin/README.md deleted file mode 100644 index 49b2baa9f3..0000000000 --- a/libnetwork/vendor/github.com/cyphar/filepath-securejoin/README.md +++ /dev/null @@ -1,65 +0,0 @@ -## `filepath-securejoin` ## - -[![Build Status](https://travis-ci.org/cyphar/filepath-securejoin.svg?branch=master)](https://travis-ci.org/cyphar/filepath-securejoin) - -An implementation of `SecureJoin`, a [candidate for inclusion in the Go -standard library][go#20126]. The purpose of this function is to be a "secure" -alternative to `filepath.Join`, and in particular it provides certain -guarantees that are not provided by `filepath.Join`. - -This is the function prototype: - -```go -func SecureJoin(root, unsafePath string) (string, error) -``` - -This library **guarantees** the following: - -* If no error is set, the resulting string **must** be a child path of - `SecureJoin` and will not contain any symlink path components (they will all - be expanded). - -* When expanding symlinks, all symlink path components **must** be resolved - relative to the provided root. In particular, this can be considered a - userspace implementation of how `chroot(2)` operates on file paths. Note that - these symlinks will **not** be expanded lexically (`filepath.Clean` is not - called on the input before processing). - -* Non-existant path components are unaffected by `SecureJoin` (similar to - `filepath.EvalSymlinks`'s semantics). - -* The returned path will always be `filepath.Clean`ed and thus not contain any - `..` components. - -A (trivial) implementation of this function on GNU/Linux systems could be done -with the following (note that this requires root privileges and is far more -opaque than the implementation in this library, and also requires that -`readlink` is inside the `root` path): - -```go -package securejoin - -import ( - "os/exec" - "path/filepath" -) - -func SecureJoin(root, unsafePath string) (string, error) { - unsafePath = string(filepath.Separator) + unsafePath - cmd := exec.Command("chroot", root, - "readlink", "--canonicalize-missing", "--no-newline", unsafePath) - output, err := cmd.CombinedOutput() - if err != nil { - return "", err - } - expanded := string(output) - return filepath.Join(root, expanded), nil -} -``` - -[go#20126]: https://github.com/golang/go/issues/20126 - -### License ### - -The license of this project is the same as Go, which is a BSD 3-clause license -available in the `LICENSE` file. diff --git a/libnetwork/vendor/github.com/cyphar/filepath-securejoin/join.go b/libnetwork/vendor/github.com/cyphar/filepath-securejoin/join.go deleted file mode 100644 index f20985479d..0000000000 --- a/libnetwork/vendor/github.com/cyphar/filepath-securejoin/join.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (C) 2014-2015 Docker Inc & Go Authors. All rights reserved. -// Copyright (C) 2017 SUSE LLC. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package securejoin is an implementation of the hopefully-soon-to-be-included -// SecureJoin helper that is meant to be part of the "path/filepath" package. -// The purpose of this project is to provide a PoC implementation to make the -// SecureJoin proposal (https://github.com/golang/go/issues/20126) more -// tangible. -package securejoin - -import ( - "bytes" - "fmt" - "os" - "path/filepath" - "strings" - "syscall" - - "github.com/pkg/errors" -) - -// ErrSymlinkLoop is returned by SecureJoinVFS when too many symlinks have been -// evaluated in attempting to securely join the two given paths. -var ErrSymlinkLoop = fmt.Errorf("SecureJoin: too many links") - -// IsNotExist tells you if err is an error that implies that either the path -// accessed does not exist (or path components don't exist). This is -// effectively a more broad version of os.IsNotExist. -func IsNotExist(err error) bool { - // If it's a bone-fide ENOENT just bail. - if os.IsNotExist(errors.Cause(err)) { - return true - } - - // Check that it's not actually an ENOTDIR, which in some cases is a more - // convoluted case of ENOENT (usually involving weird paths). - var errno error - switch err := errors.Cause(err).(type) { - case *os.PathError: - errno = err.Err - case *os.LinkError: - errno = err.Err - case *os.SyscallError: - errno = err.Err - } - return errno == syscall.ENOTDIR || errno == syscall.ENOENT -} - -// SecureJoinVFS joins the two given path components (similar to Join) except -// that the returned path is guaranteed to be scoped inside the provided root -// path (when evaluated). Any symbolic links in the path are evaluated with the -// given root treated as the root of the filesystem, similar to a chroot. The -// filesystem state is evaluated through the given VFS interface (if nil, the -// standard os.* family of functions are used). -// -// Note that the guarantees provided by this function only apply if the path -// components in the returned string are not modified (in other words are not -// replaced with symlinks on the filesystem) after this function has returned. -// Such a symlink race is necessarily out-of-scope of SecureJoin. -func SecureJoinVFS(root, unsafePath string, vfs VFS) (string, error) { - // Use the os.* VFS implementation if none was specified. - if vfs == nil { - vfs = osVFS{} - } - - var path bytes.Buffer - n := 0 - for unsafePath != "" { - if n > 255 { - return "", ErrSymlinkLoop - } - - // Next path component, p. - i := strings.IndexRune(unsafePath, filepath.Separator) - var p string - if i == -1 { - p, unsafePath = unsafePath, "" - } else { - p, unsafePath = unsafePath[:i], unsafePath[i+1:] - } - - // Create a cleaned path, using the lexical semantics of /../a, to - // create a "scoped" path component which can safely be joined to fullP - // for evaluation. At this point, path.String() doesn't contain any - // symlink components. - cleanP := filepath.Clean(string(filepath.Separator) + path.String() + p) - if cleanP == string(filepath.Separator) { - path.Reset() - continue - } - fullP := filepath.Clean(root + cleanP) - - // Figure out whether the path is a symlink. - fi, err := vfs.Lstat(fullP) - if err != nil && !IsNotExist(err) { - return "", err - } - // Treat non-existent path components the same as non-symlinks (we - // can't do any better here). - if IsNotExist(err) || fi.Mode()&os.ModeSymlink == 0 { - path.WriteString(p) - path.WriteRune(filepath.Separator) - continue - } - - // Only increment when we actually dereference a link. - n++ - - // It's a symlink, expand it by prepending it to the yet-unparsed path. - dest, err := vfs.Readlink(fullP) - if err != nil { - return "", err - } - // Absolute symlinks reset any work we've already done. - if filepath.IsAbs(dest) { - path.Reset() - } - unsafePath = dest + string(filepath.Separator) + unsafePath - } - - // We have to clean path.String() here because it may contain '..' - // components that are entirely lexical, but would be misleading otherwise. - // And finally do a final clean to ensure that root is also lexically - // clean. - fullP := filepath.Clean(string(filepath.Separator) + path.String()) - return filepath.Clean(root + fullP), nil -} - -// SecureJoin is a wrapper around SecureJoinVFS that just uses the os.* library -// of functions as the VFS. If in doubt, use this function over SecureJoinVFS. -func SecureJoin(root, unsafePath string) (string, error) { - return SecureJoinVFS(root, unsafePath, nil) -} diff --git a/libnetwork/vendor/github.com/cyphar/filepath-securejoin/vendor.conf b/libnetwork/vendor/github.com/cyphar/filepath-securejoin/vendor.conf deleted file mode 100644 index 66bb574b95..0000000000 --- a/libnetwork/vendor/github.com/cyphar/filepath-securejoin/vendor.conf +++ /dev/null @@ -1 +0,0 @@ -github.com/pkg/errors v0.8.0 diff --git a/libnetwork/vendor/github.com/cyphar/filepath-securejoin/vfs.go b/libnetwork/vendor/github.com/cyphar/filepath-securejoin/vfs.go deleted file mode 100644 index a82a5eae11..0000000000 --- a/libnetwork/vendor/github.com/cyphar/filepath-securejoin/vfs.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2017 SUSE LLC. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package securejoin - -import "os" - -// In future this should be moved into a separate package, because now there -// are several projects (umoci and go-mtree) that are using this sort of -// interface. - -// VFS is the minimal interface necessary to use SecureJoinVFS. A nil VFS is -// equivalent to using the standard os.* family of functions. This is mainly -// used for the purposes of mock testing, but also can be used to otherwise use -// SecureJoin with VFS-like system. -type VFS interface { - // Lstat returns a FileInfo describing the named file. If the file is a - // symbolic link, the returned FileInfo describes the symbolic link. Lstat - // makes no attempt to follow the link. These semantics are identical to - // os.Lstat. - Lstat(name string) (os.FileInfo, error) - - // Readlink returns the destination of the named symbolic link. These - // semantics are identical to os.Readlink. - Readlink(name string) (string, error) -} - -// osVFS is the "nil" VFS, in that it just passes everything through to the os -// module. -type osVFS struct{} - -// Lstat returns a FileInfo describing the named file. If the file is a -// symbolic link, the returned FileInfo describes the symbolic link. Lstat -// makes no attempt to follow the link. These semantics are identical to -// os.Lstat. -func (o osVFS) Lstat(name string) (os.FileInfo, error) { return os.Lstat(name) } - -// Readlink returns the destination of the named symbolic link. These -// semantics are identical to os.Readlink. -func (o osVFS) Readlink(name string) (string, error) { return os.Readlink(name) } diff --git a/libnetwork/vendor/github.com/docker/docker/contrib/README.md b/libnetwork/vendor/github.com/docker/docker/contrib/README.md deleted file mode 100644 index 92b1d94433..0000000000 --- a/libnetwork/vendor/github.com/docker/docker/contrib/README.md +++ /dev/null @@ -1,4 +0,0 @@ -The `contrib` directory contains scripts, images, and other helpful things -which are not part of the core docker distribution. Please note that they -could be out of date, since they do not receive the same attention as the -rest of the repository. diff --git a/libnetwork/vendor/github.com/docker/docker/contrib/nnp-test/nnp-test.c b/libnetwork/vendor/github.com/docker/docker/contrib/nnp-test/nnp-test.c deleted file mode 100644 index b767da7e1a..0000000000 --- a/libnetwork/vendor/github.com/docker/docker/contrib/nnp-test/nnp-test.c +++ /dev/null @@ -1,10 +0,0 @@ -#include -#include -#include - -int main(int argc, char *argv[]) -{ - printf("EUID=%d\n", geteuid()); - return 0; -} - diff --git a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/acct.c b/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/acct.c deleted file mode 100644 index 88ac287966..0000000000 --- a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/acct.c +++ /dev/null @@ -1,16 +0,0 @@ -#define _GNU_SOURCE -#include -#include -#include -#include -#include - -int main(int argc, char **argv) -{ - int err = acct("/tmp/t"); - if (err == -1) { - fprintf(stderr, "acct failed: %s\n", strerror(errno)); - exit(EXIT_FAILURE); - } - exit(EXIT_SUCCESS); -} diff --git a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/exit32.s b/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/exit32.s deleted file mode 100644 index 8bbb5c58b3..0000000000 --- a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/exit32.s +++ /dev/null @@ -1,7 +0,0 @@ -.globl _start -.text -_start: - xorl %eax, %eax - incl %eax - movb $0, %bl - int $0x80 diff --git a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/ns.c b/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/ns.c deleted file mode 100644 index 624388630a..0000000000 --- a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/ns.c +++ /dev/null @@ -1,63 +0,0 @@ -#define _GNU_SOURCE -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define STACK_SIZE (1024 * 1024) /* Stack size for cloned child */ - -struct clone_args { - char **argv; -}; - -// child_exec is the func that will be executed as the result of clone -static int child_exec(void *stuff) -{ - struct clone_args *args = (struct clone_args *)stuff; - if (execvp(args->argv[0], args->argv) != 0) { - fprintf(stderr, "failed to execvp arguments %s\n", - strerror(errno)); - exit(-1); - } - // we should never reach here! - exit(EXIT_FAILURE); -} - -int main(int argc, char **argv) -{ - struct clone_args args; - args.argv = &argv[1]; - - int clone_flags = CLONE_NEWNS | CLONE_NEWPID | SIGCHLD; - - // allocate stack for child - char *stack; /* Start of stack buffer */ - char *child_stack; /* End of stack buffer */ - stack = - mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE, - MAP_SHARED | MAP_ANON | MAP_STACK, -1, 0); - if (stack == MAP_FAILED) { - fprintf(stderr, "mmap failed: %s\n", strerror(errno)); - exit(EXIT_FAILURE); - } - child_stack = stack + STACK_SIZE; /* Assume stack grows downward */ - - // the result of this call is that our child_exec will be run in another - // process returning its pid - pid_t pid = clone(child_exec, child_stack, clone_flags, &args); - if (pid < 0) { - fprintf(stderr, "clone failed: %s\n", strerror(errno)); - exit(EXIT_FAILURE); - } - // lets wait on our child process here before we, the parent, exits - if (waitpid(pid, NULL, 0) == -1) { - fprintf(stderr, "failed to wait pid %d\n", pid); - exit(EXIT_FAILURE); - } - exit(EXIT_SUCCESS); -} diff --git a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/raw.c b/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/raw.c deleted file mode 100644 index 7995a0d3a5..0000000000 --- a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/raw.c +++ /dev/null @@ -1,14 +0,0 @@ -#include -#include -#include -#include -#include - -int main() { - if (socket(PF_INET, SOCK_RAW, IPPROTO_UDP) == -1) { - perror("socket"); - return 1; - } - - return 0; -} diff --git a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/setgid.c b/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/setgid.c deleted file mode 100644 index df9680c869..0000000000 --- a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/setgid.c +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include -#include - -int main() { - if (setgid(1) == -1) { - perror("setgid"); - return 1; - } - return 0; -} diff --git a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/setuid.c b/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/setuid.c deleted file mode 100644 index 5b939677e9..0000000000 --- a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/setuid.c +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include -#include - -int main() { - if (setuid(1) == -1) { - perror("setuid"); - return 1; - } - return 0; -} diff --git a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/socket.c b/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/socket.c deleted file mode 100644 index d26c82f00f..0000000000 --- a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/socket.c +++ /dev/null @@ -1,30 +0,0 @@ -#include -#include -#include -#include -#include -#include - -int main() { - int s; - struct sockaddr_in sin; - - s = socket(AF_INET, SOCK_STREAM, 0); - if (s == -1) { - perror("socket"); - return 1; - } - - sin.sin_family = AF_INET; - sin.sin_addr.s_addr = INADDR_ANY; - sin.sin_port = htons(80); - - if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) == -1) { - perror("bind"); - return 1; - } - - close(s); - - return 0; -} diff --git a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/userns.c b/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/userns.c deleted file mode 100644 index 4c5c8d304e..0000000000 --- a/libnetwork/vendor/github.com/docker/docker/contrib/syscall-test/userns.c +++ /dev/null @@ -1,63 +0,0 @@ -#define _GNU_SOURCE -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define STACK_SIZE (1024 * 1024) /* Stack size for cloned child */ - -struct clone_args { - char **argv; -}; - -// child_exec is the func that will be executed as the result of clone -static int child_exec(void *stuff) -{ - struct clone_args *args = (struct clone_args *)stuff; - if (execvp(args->argv[0], args->argv) != 0) { - fprintf(stderr, "failed to execvp arguments %s\n", - strerror(errno)); - exit(-1); - } - // we should never reach here! - exit(EXIT_FAILURE); -} - -int main(int argc, char **argv) -{ - struct clone_args args; - args.argv = &argv[1]; - - int clone_flags = CLONE_NEWUSER | SIGCHLD; - - // allocate stack for child - char *stack; /* Start of stack buffer */ - char *child_stack; /* End of stack buffer */ - stack = - mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE, - MAP_SHARED | MAP_ANON | MAP_STACK, -1, 0); - if (stack == MAP_FAILED) { - fprintf(stderr, "mmap failed: %s\n", strerror(errno)); - exit(EXIT_FAILURE); - } - child_stack = stack + STACK_SIZE; /* Assume stack grows downward */ - - // the result of this call is that our child_exec will be run in another - // process returning its pid - pid_t pid = clone(child_exec, child_stack, clone_flags, &args); - if (pid < 0) { - fprintf(stderr, "clone failed: %s\n", strerror(errno)); - exit(EXIT_FAILURE); - } - // lets wait on our child process here before we, the parent, exits - if (waitpid(pid, NULL, 0) == -1) { - fprintf(stderr, "failed to wait pid %d\n", pid); - exit(EXIT_FAILURE); - } - exit(EXIT_SUCCESS); -} diff --git a/libnetwork/vendor/github.com/golang/protobuf/proto/discard.go b/libnetwork/vendor/github.com/golang/protobuf/proto/discard.go deleted file mode 100644 index dea2617ced..0000000000 --- a/libnetwork/vendor/github.com/golang/protobuf/proto/discard.go +++ /dev/null @@ -1,350 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2017 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -type generatedDiscarder interface { - XXX_DiscardUnknown() -} - -// DiscardUnknown recursively discards all unknown fields from this message -// and all embedded messages. -// -// When unmarshaling a message with unrecognized fields, the tags and values -// of such fields are preserved in the Message. This allows a later call to -// marshal to be able to produce a message that continues to have those -// unrecognized fields. To avoid this, DiscardUnknown is used to -// explicitly clear the unknown fields after unmarshaling. -// -// For proto2 messages, the unknown fields of message extensions are only -// discarded from messages that have been accessed via GetExtension. -func DiscardUnknown(m Message) { - if m, ok := m.(generatedDiscarder); ok { - m.XXX_DiscardUnknown() - return - } - // TODO: Dynamically populate a InternalMessageInfo for legacy messages, - // but the master branch has no implementation for InternalMessageInfo, - // so it would be more work to replicate that approach. - discardLegacy(m) -} - -// DiscardUnknown recursively discards all unknown fields. -func (a *InternalMessageInfo) DiscardUnknown(m Message) { - di := atomicLoadDiscardInfo(&a.discard) - if di == nil { - di = getDiscardInfo(reflect.TypeOf(m).Elem()) - atomicStoreDiscardInfo(&a.discard, di) - } - di.discard(toPointer(&m)) -} - -type discardInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []discardFieldInfo - unrecognized field -} - -type discardFieldInfo struct { - field field // Offset of field, guaranteed to be valid - discard func(src pointer) -} - -var ( - discardInfoMap = map[reflect.Type]*discardInfo{} - discardInfoLock sync.Mutex -) - -func getDiscardInfo(t reflect.Type) *discardInfo { - discardInfoLock.Lock() - defer discardInfoLock.Unlock() - di := discardInfoMap[t] - if di == nil { - di = &discardInfo{typ: t} - discardInfoMap[t] = di - } - return di -} - -func (di *discardInfo) discard(src pointer) { - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&di.initialized) == 0 { - di.computeDiscardInfo() - } - - for _, fi := range di.fields { - sfp := src.offset(fi.field) - fi.discard(sfp) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil { - // Ignore lock since DiscardUnknown is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - DiscardUnknown(m) - } - } - } - - if di.unrecognized.IsValid() { - *src.offset(di.unrecognized).toBytes() = nil - } -} - -func (di *discardInfo) computeDiscardInfo() { - di.lock.Lock() - defer di.lock.Unlock() - if di.initialized != 0 { - return - } - t := di.typ - n := t.NumField() - - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - dfi := discardFieldInfo{field: toField(&f)} - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name)) - case isSlice: // E.g., []*pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sps := src.getPointerSlice() - for _, sp := range sps { - if !sp.isNil() { - di.discard(sp) - } - } - } - default: // E.g., *pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sp := src.getPointer() - if !sp.isNil() { - di.discard(sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name)) - default: // E.g., map[K]V - if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T) - dfi.discard = func(src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - DiscardUnknown(val.Interface().(Message)) - } - } - } else { - dfi.discard = func(pointer) {} // Noop - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name)) - default: // E.g., interface{} - // TODO: Make this faster? - dfi.discard = func(src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - DiscardUnknown(sv.Interface().(Message)) - } - } - } - } - default: - continue - } - di.fields = append(di.fields, dfi) - } - - di.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - di.unrecognized = toField(&f) - } - - atomic.StoreInt32(&di.initialized, 1) -} - -func discardLegacy(m Message) { - v := reflect.ValueOf(m) - if v.Kind() != reflect.Ptr || v.IsNil() { - return - } - v = v.Elem() - if v.Kind() != reflect.Struct { - return - } - t := v.Type() - - for i := 0; i < v.NumField(); i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - vf := v.Field(i) - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name)) - case isSlice: // E.g., []*pb.T - for j := 0; j < vf.Len(); j++ { - discardLegacy(vf.Index(j).Interface().(Message)) - } - default: // E.g., *pb.T - discardLegacy(vf.Interface().(Message)) - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name)) - default: // E.g., map[K]V - tv := vf.Type().Elem() - if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T) - for _, key := range vf.MapKeys() { - val := vf.MapIndex(key) - discardLegacy(val.Interface().(Message)) - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name)) - default: // E.g., test_proto.isCommunique_Union interface - if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" { - vf = vf.Elem() // E.g., *test_proto.Communique_Msg - if !vf.IsNil() { - vf = vf.Elem() // E.g., test_proto.Communique_Msg - vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value - if vf.Kind() == reflect.Ptr { - discardLegacy(vf.Interface().(Message)) - } - } - } - } - } - } - - if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() { - if vf.Type() != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - vf.Set(reflect.ValueOf([]byte(nil))) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(m); err == nil { - // Ignore lock since discardLegacy is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - discardLegacy(m) - } - } - } -} diff --git a/libnetwork/vendor/github.com/golang/protobuf/proto/table_marshal.go b/libnetwork/vendor/github.com/golang/protobuf/proto/table_marshal.go deleted file mode 100644 index 0f212b3029..0000000000 --- a/libnetwork/vendor/github.com/golang/protobuf/proto/table_marshal.go +++ /dev/null @@ -1,2681 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// a sizer takes a pointer to a field and the size of its tag, computes the size of -// the encoded data. -type sizer func(pointer, int) int - -// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), -// marshals the field to the end of the slice, returns the slice and error (if any). -type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) - -// marshalInfo is the information used for marshaling a message. -type marshalInfo struct { - typ reflect.Type - fields []*marshalFieldInfo - unrecognized field // offset of XXX_unrecognized - extensions field // offset of XXX_InternalExtensions - v1extensions field // offset of XXX_extensions - sizecache field // offset of XXX_sizecache - initialized int32 // 0 -- only typ is set, 1 -- fully initialized - messageset bool // uses message set wire format - hasmarshaler bool // has custom marshaler - sync.RWMutex // protect extElems map, also for initialization - extElems map[int32]*marshalElemInfo // info of extension elements -} - -// marshalFieldInfo is the information used for marshaling a field of a message. -type marshalFieldInfo struct { - field field - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isPointer bool - required bool // field is required - name string // name of the field, for error reporting - oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements -} - -// marshalElemInfo is the information used for marshaling an extension or oneof element. -type marshalElemInfo struct { - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) -} - -var ( - marshalInfoMap = map[reflect.Type]*marshalInfo{} - marshalInfoLock sync.Mutex -) - -// getMarshalInfo returns the information to marshal a given type of message. -// The info it returns may not necessarily initialized. -// t is the type of the message (NOT the pointer to it). -func getMarshalInfo(t reflect.Type) *marshalInfo { - marshalInfoLock.Lock() - u, ok := marshalInfoMap[t] - if !ok { - u = &marshalInfo{typ: t} - marshalInfoMap[t] = u - } - marshalInfoLock.Unlock() - return u -} - -// Size is the entry point from generated code, -// and should be ONLY called by generated code. -// It computes the size of encoded data of msg. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Size(msg Message) int { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return 0 - } - return u.size(ptr) -} - -// Marshal is the entry point from generated code, -// and should be ONLY called by generated code. -// It marshals msg to the end of b. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return b, ErrNil - } - return u.marshal(b, ptr, deterministic) -} - -func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { - // u := a.marshal, but atomically. - // We use an atomic here to ensure memory consistency. - u := atomicLoadMarshalInfo(&a.marshal) - if u == nil { - // Get marshal information from type of message. - t := reflect.ValueOf(msg).Type() - if t.Kind() != reflect.Ptr { - panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) - } - u = getMarshalInfo(t.Elem()) - // Store it in the cache for later users. - // a.marshal = u, but atomically. - atomicStoreMarshalInfo(&a.marshal, u) - } - return u -} - -// size is the main function to compute the size of the encoded data of a message. -// ptr is the pointer to the message. -func (u *marshalInfo) size(ptr pointer) int { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b, _ := m.Marshal() - return len(b) - } - - n := 0 - for _, f := range u.fields { - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - n += f.sizer(ptr.offset(f.field), f.tagsize) - } - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - n += u.sizeMessageSet(e) - } else { - n += u.sizeExtensions(e) - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - n += u.sizeV1Extensions(m) - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - n += len(s) - } - // cache the result for use in marshal - if u.sizecache.IsValid() { - atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) - } - return n -} - -// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), -// fall back to compute the size. -func (u *marshalInfo) cachedsize(ptr pointer) int { - if u.sizecache.IsValid() { - return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) - } - return u.size(ptr) -} - -// marshal is the main function to marshal a message. It takes a byte slice and appends -// the encoded data to the end of the slice, returns the slice and error (if any). -// ptr is the pointer to the message. -// If deterministic is true, map is marshaled in deterministic order. -func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b1, err := m.Marshal() - b = append(b, b1...) - return b, err - } - - var err, errreq error - // The old marshaler encodes extensions at beginning. - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - b, err = u.appendMessageSet(b, e, deterministic) - } else { - b, err = u.appendExtensions(b, e, deterministic) - } - if err != nil { - return b, err - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - b, err = u.appendV1Extensions(b, m, deterministic) - if err != nil { - return b, err - } - } - for _, f := range u.fields { - if f.required && errreq == nil { - if ptr.offset(f.field).getPointer().isNil() { - // Required field is not set. - // We record the error but keep going, to give a complete marshaling. - errreq = &RequiredNotSetError{f.name} - continue - } - } - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) - if err != nil { - if err1, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errreq == nil { - errreq = &RequiredNotSetError{f.name + "." + err1.field} - } - continue - } - if err == errRepeatedHasNil { - err = errors.New("proto: repeated field " + f.name + " has nil element") - } - return b, err - } - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - b = append(b, s...) - } - return b, errreq -} - -// computeMarshalInfo initializes the marshal info. -func (u *marshalInfo) computeMarshalInfo() { - u.Lock() - defer u.Unlock() - if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock - return - } - - t := u.typ - u.unrecognized = invalidField - u.extensions = invalidField - u.v1extensions = invalidField - u.sizecache = invalidField - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if reflect.PtrTo(t).Implements(marshalerType) { - u.hasmarshaler = true - atomic.StoreInt32(&u.initialized, 1) - return - } - - // get oneof implementers - var oneofImplementers []interface{} - if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { - _, _, _, oneofImplementers = m.XXX_OneofFuncs() - } - - n := t.NumField() - - // deal with XXX fields first - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if !strings.HasPrefix(f.Name, "XXX_") { - continue - } - switch f.Name { - case "XXX_sizecache": - u.sizecache = toField(&f) - case "XXX_unrecognized": - u.unrecognized = toField(&f) - case "XXX_InternalExtensions": - u.extensions = toField(&f) - u.messageset = f.Tag.Get("protobuf_messageset") == "1" - case "XXX_extensions": - u.v1extensions = toField(&f) - case "XXX_NoUnkeyedLiteral": - // nothing to do - default: - panic("unknown XXX field: " + f.Name) - } - n-- - } - - // normal fields - fields := make([]marshalFieldInfo, n) // batch allocation - u.fields = make([]*marshalFieldInfo, 0, n) - for i, j := 0, 0; i < t.NumField(); i++ { - f := t.Field(i) - - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - field := &fields[j] - j++ - field.name = f.Name - u.fields = append(u.fields, field) - if f.Tag.Get("protobuf_oneof") != "" { - field.computeOneofFieldInfo(&f, oneofImplementers) - continue - } - if f.Tag.Get("protobuf") == "" { - // field has no tag (not in generated message), ignore it - u.fields = u.fields[:len(u.fields)-1] - j-- - continue - } - field.computeMarshalFieldInfo(&f) - } - - // fields are marshaled in tag order on the wire. - sort.Sort(byTag(u.fields)) - - atomic.StoreInt32(&u.initialized, 1) -} - -// helper for sorting fields by tag -type byTag []*marshalFieldInfo - -func (a byTag) Len() int { return len(a) } -func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } - -// getExtElemInfo returns the information to marshal an extension element. -// The info it returns is initialized. -func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { - // get from cache first - u.RLock() - e, ok := u.extElems[desc.Field] - u.RUnlock() - if ok { - return e - } - - t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct - tags := strings.Split(desc.Tag, ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(t, tags, false, false) - e = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - isptr: t.Kind() == reflect.Ptr, - } - - // update cache - u.Lock() - if u.extElems == nil { - u.extElems = make(map[int32]*marshalElemInfo) - } - u.extElems[desc.Field] = e - u.Unlock() - return e -} - -// computeMarshalFieldInfo fills up the information to marshal a field. -func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { - // parse protobuf tag of the field. - // tag has format of "bytes,49,opt,name=foo,def=hello!" - tags := strings.Split(f.Tag.Get("protobuf"), ",") - if tags[0] == "" { - return - } - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - if tags[2] == "req" { - fi.required = true - } - fi.setTag(f, tag, wt) - fi.setMarshaler(f, tags) -} - -func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { - fi.field = toField(f) - fi.wiretag = 1<<31 - 1 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. - fi.isPointer = true - fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) - fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) - - ityp := f.Type // interface type - for _, o := range oneofImplementers { - t := reflect.TypeOf(o) - if !t.Implements(ityp) { - continue - } - sf := t.Elem().Field(0) // oneof implementer is a struct with a single field - tags := strings.Split(sf.Tag.Get("protobuf"), ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value - fi.oneofElems[t.Elem()] = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - } - } -} - -type oneofMessage interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) -} - -// wiretype returns the wire encoding of the type. -func wiretype(encoding string) uint64 { - switch encoding { - case "fixed32": - return WireFixed32 - case "fixed64": - return WireFixed64 - case "varint", "zigzag32", "zigzag64": - return WireVarint - case "bytes": - return WireBytes - case "group": - return WireStartGroup - } - panic("unknown wire type " + encoding) -} - -// setTag fills up the tag (in wire format) and its size in the info of a field. -func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { - fi.field = toField(f) - fi.wiretag = uint64(tag)<<3 | wt - fi.tagsize = SizeVarint(uint64(tag) << 3) -} - -// setMarshaler fills up the sizer and marshaler in the info of a field. -func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { - switch f.Type.Kind() { - case reflect.Map: - // map field - fi.isPointer = true - fi.sizer, fi.marshaler = makeMapMarshaler(f) - return - case reflect.Ptr, reflect.Slice: - fi.isPointer = true - } - fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) -} - -// typeMarshaler returns the sizer and marshaler of a given field. -// t is the type of the field. -// tags is the generated "protobuf" tag of the field. -// If nozero is true, zero value is not marshaled to the wire. -// If oneof is true, it is a oneof field. -func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { - encoding := tags[0] - - pointer := false - slice := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - packed := false - proto3 := false - for i := 2; i < len(tags); i++ { - if tags[i] == "packed" { - packed = true - } - if tags[i] == "proto3" { - proto3 = true - } - } - - switch t.Kind() { - case reflect.Bool: - if pointer { - return sizeBoolPtr, appendBoolPtr - } - if slice { - if packed { - return sizeBoolPackedSlice, appendBoolPackedSlice - } - return sizeBoolSlice, appendBoolSlice - } - if nozero { - return sizeBoolValueNoZero, appendBoolValueNoZero - } - return sizeBoolValue, appendBoolValue - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixed32Ptr, appendFixed32Ptr - } - if slice { - if packed { - return sizeFixed32PackedSlice, appendFixed32PackedSlice - } - return sizeFixed32Slice, appendFixed32Slice - } - if nozero { - return sizeFixed32ValueNoZero, appendFixed32ValueNoZero - } - return sizeFixed32Value, appendFixed32Value - case "varint": - if pointer { - return sizeVarint32Ptr, appendVarint32Ptr - } - if slice { - if packed { - return sizeVarint32PackedSlice, appendVarint32PackedSlice - } - return sizeVarint32Slice, appendVarint32Slice - } - if nozero { - return sizeVarint32ValueNoZero, appendVarint32ValueNoZero - } - return sizeVarint32Value, appendVarint32Value - } - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixedS32Ptr, appendFixedS32Ptr - } - if slice { - if packed { - return sizeFixedS32PackedSlice, appendFixedS32PackedSlice - } - return sizeFixedS32Slice, appendFixedS32Slice - } - if nozero { - return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero - } - return sizeFixedS32Value, appendFixedS32Value - case "varint": - if pointer { - return sizeVarintS32Ptr, appendVarintS32Ptr - } - if slice { - if packed { - return sizeVarintS32PackedSlice, appendVarintS32PackedSlice - } - return sizeVarintS32Slice, appendVarintS32Slice - } - if nozero { - return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero - } - return sizeVarintS32Value, appendVarintS32Value - case "zigzag32": - if pointer { - return sizeZigzag32Ptr, appendZigzag32Ptr - } - if slice { - if packed { - return sizeZigzag32PackedSlice, appendZigzag32PackedSlice - } - return sizeZigzag32Slice, appendZigzag32Slice - } - if nozero { - return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero - } - return sizeZigzag32Value, appendZigzag32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixed64Ptr, appendFixed64Ptr - } - if slice { - if packed { - return sizeFixed64PackedSlice, appendFixed64PackedSlice - } - return sizeFixed64Slice, appendFixed64Slice - } - if nozero { - return sizeFixed64ValueNoZero, appendFixed64ValueNoZero - } - return sizeFixed64Value, appendFixed64Value - case "varint": - if pointer { - return sizeVarint64Ptr, appendVarint64Ptr - } - if slice { - if packed { - return sizeVarint64PackedSlice, appendVarint64PackedSlice - } - return sizeVarint64Slice, appendVarint64Slice - } - if nozero { - return sizeVarint64ValueNoZero, appendVarint64ValueNoZero - } - return sizeVarint64Value, appendVarint64Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixedS64Ptr, appendFixedS64Ptr - } - if slice { - if packed { - return sizeFixedS64PackedSlice, appendFixedS64PackedSlice - } - return sizeFixedS64Slice, appendFixedS64Slice - } - if nozero { - return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero - } - return sizeFixedS64Value, appendFixedS64Value - case "varint": - if pointer { - return sizeVarintS64Ptr, appendVarintS64Ptr - } - if slice { - if packed { - return sizeVarintS64PackedSlice, appendVarintS64PackedSlice - } - return sizeVarintS64Slice, appendVarintS64Slice - } - if nozero { - return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero - } - return sizeVarintS64Value, appendVarintS64Value - case "zigzag64": - if pointer { - return sizeZigzag64Ptr, appendZigzag64Ptr - } - if slice { - if packed { - return sizeZigzag64PackedSlice, appendZigzag64PackedSlice - } - return sizeZigzag64Slice, appendZigzag64Slice - } - if nozero { - return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero - } - return sizeZigzag64Value, appendZigzag64Value - } - case reflect.Float32: - if pointer { - return sizeFloat32Ptr, appendFloat32Ptr - } - if slice { - if packed { - return sizeFloat32PackedSlice, appendFloat32PackedSlice - } - return sizeFloat32Slice, appendFloat32Slice - } - if nozero { - return sizeFloat32ValueNoZero, appendFloat32ValueNoZero - } - return sizeFloat32Value, appendFloat32Value - case reflect.Float64: - if pointer { - return sizeFloat64Ptr, appendFloat64Ptr - } - if slice { - if packed { - return sizeFloat64PackedSlice, appendFloat64PackedSlice - } - return sizeFloat64Slice, appendFloat64Slice - } - if nozero { - return sizeFloat64ValueNoZero, appendFloat64ValueNoZero - } - return sizeFloat64Value, appendFloat64Value - case reflect.String: - if pointer { - return sizeStringPtr, appendStringPtr - } - if slice { - return sizeStringSlice, appendStringSlice - } - if nozero { - return sizeStringValueNoZero, appendStringValueNoZero - } - return sizeStringValue, appendStringValue - case reflect.Slice: - if slice { - return sizeBytesSlice, appendBytesSlice - } - if oneof { - // Oneof bytes field may also have "proto3" tag. - // We want to marshal it as a oneof field. Do this - // check before the proto3 check. - return sizeBytesOneof, appendBytesOneof - } - if proto3 { - return sizeBytes3, appendBytes3 - } - return sizeBytes, appendBytes - case reflect.Struct: - switch encoding { - case "group": - if slice { - return makeGroupSliceMarshaler(getMarshalInfo(t)) - } - return makeGroupMarshaler(getMarshalInfo(t)) - case "bytes": - if slice { - return makeMessageSliceMarshaler(getMarshalInfo(t)) - } - return makeMessageMarshaler(getMarshalInfo(t)) - } - } - panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) -} - -// Below are functions to size/marshal a specific type of a field. -// They are stored in the field's info, and called by function pointers. -// They have type sizer or marshaler. - -func sizeFixed32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixedS32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFloat32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - return (4 + tagsize) * len(s) -} -func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixed64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFixedS64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFloat64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - return (8 + tagsize) * len(s) -} -func sizeFloat64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeVarint32Value(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarint32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarint32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarint64Value(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - return SizeVarint(v) + tagsize -} -func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return SizeVarint(v) + tagsize -} -func sizeVarint64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return SizeVarint(*p) + tagsize -} -func sizeVarint64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(v) + tagsize - } - return n -} -func sizeVarint64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize - } - return n -} -func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize - } - return n -} -func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeBoolValue(_ pointer, tagsize int) int { - return 1 + tagsize -} -func sizeBoolValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toBool() - if !v { - return 0 - } - return 1 + tagsize -} -func sizeBoolPtr(ptr pointer, tagsize int) int { - p := *ptr.toBoolPtr() - if p == nil { - return 0 - } - return 1 + tagsize -} -func sizeBoolSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - return (1 + tagsize) * len(s) -} -func sizeBoolPackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return 0 - } - return len(s) + SizeVarint(uint64(len(s))) + tagsize -} -func sizeStringValue(ptr pointer, tagsize int) int { - v := *ptr.toString() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toString() - if v == "" { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringPtr(ptr pointer, tagsize int) int { - p := *ptr.toStringPtr() - if p == nil { - return 0 - } - v := *p - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringSlice(ptr pointer, tagsize int) int { - s := *ptr.toStringSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} -func sizeBytes(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if v == nil { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytes3(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if len(v) == 0 { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesOneof(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesSlice(ptr pointer, tagsize int) int { - s := *ptr.toBytesSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} - -// appendFixed32 appends an encoded fixed32 to b. -func appendFixed32(b []byte, v uint32) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24)) - return b -} - -// appendFixed64 appends an encoded fixed64 to b. -func appendFixed64(b []byte, v uint64) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24), - byte(v>>32), - byte(v>>40), - byte(v>>48), - byte(v>>56)) - return b -} - -// appendVarint appends an encoded varint to b. -func appendVarint(b []byte, v uint64) []byte { - // TODO: make 1-byte (maybe 2-byte) case inline-able, once we - // have non-leaf inliner. - switch { - case v < 1<<7: - b = append(b, byte(v)) - case v < 1<<14: - b = append(b, - byte(v&0x7f|0x80), - byte(v>>7)) - case v < 1<<21: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte(v>>14)) - case v < 1<<28: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte(v>>21)) - case v < 1<<35: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte(v>>28)) - case v < 1<<42: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte(v>>35)) - case v < 1<<49: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte(v>>42)) - case v < 1<<56: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte(v>>49)) - case v < 1<<63: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte(v>>56)) - default: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte((v>>56)&0x7f|0x80), - 1) - } - return b -} - -func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, *p) - return b, nil -} -func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(*p)) - return b, nil -} -func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(*p)) - return b, nil -} -func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, *p) - return b, nil -} -func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(*p)) - return b, nil -} -func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(*p)) - return b, nil -} -func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, *p) - return b, nil -} -func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - } - return b, nil -} -func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, v) - } - return b, nil -} -func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - if !v { - return b, nil - } - b = appendVarint(b, wiretag) - b = append(b, 1) - return b, nil -} - -func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toBoolPtr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - if *p { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(len(s))) - for _, v := range s { - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - if v == "" { - return b, nil - } - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toStringSlice() - for _, v := range s { - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} -func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if v == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if len(v) == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBytesSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} - -// makeGroupMarshaler returns the sizer and marshaler for a group. -// u is the marshal info of the underlying message. -func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - return u.size(p) + 2*tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - var err error - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, p, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - return b, err - } -} - -// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice. -// u is the marshal info of the underlying message. -func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - n += u.size(v) + 2*tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err, errreq error - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, v, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - if err != nil { - if _, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errreq == nil { - errreq = err - } - continue - } - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, errreq - } -} - -// makeMessageMarshaler returns the sizer and marshaler for a message field. -// u is the marshal info of the message. -func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.size(p) - return siz + SizeVarint(uint64(siz)) + tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(p) - b = appendVarint(b, uint64(siz)) - return u.marshal(b, p, deterministic) - } -} - -// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice. -// u is the marshal info of the message. -func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - siz := u.size(v) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err, errreq error - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(v) - b = appendVarint(b, uint64(siz)) - b, err = u.marshal(b, v, deterministic) - - if err != nil { - if _, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errreq == nil { - errreq = err - } - continue - } - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, errreq - } -} - -// makeMapMarshaler returns the sizer and marshaler for a map field. -// f is the pointer to the reflect data structure of the field. -func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) { - // figure out key and value type - t := f.Type - keyType := t.Key() - valType := t.Elem() - keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",") - valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") - keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map - valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map - keyWireTag := 1<<3 | wiretype(keyTags[0]) - valWireTag := 2<<3 | wiretype(valTags[0]) - - // We create an interface to get the addresses of the map key and value. - // If value is pointer-typed, the interface is a direct interface, the - // idata itself is the value. Otherwise, the idata is the pointer to the - // value. - // Key cannot be pointer-typed. - valIsPtr := valType.Kind() == reflect.Ptr - return func(ptr pointer, tagsize int) int { - m := ptr.asPointerTo(t).Elem() // the map - n := 0 - for _, k := range m.MapKeys() { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value - siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) { - m := ptr.asPointerTo(t).Elem() // the map - var err error - keys := m.MapKeys() - if len(keys) > 1 && deterministic { - sort.Sort(mapKeys(keys)) - } - for _, k := range keys { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value - b = appendVarint(b, tag) - siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - b = appendVarint(b, uint64(siz)) - b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic) - if err != nil { - return b, err - } - b, err = valMarshaler(b, vaddr, valWireTag, deterministic) - if err != nil && err != ErrNil { // allow nil value in map - return b, err - } - } - return b, nil - } -} - -// makeOneOfMarshaler returns the sizer and marshaler for a oneof field. -// fi is the marshal info of the field. -// f is the pointer to the reflect data structure of the field. -func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) { - // Oneof field is an interface. We need to get the actual data type on the fly. - t := f.Type - return func(ptr pointer, _ int) int { - p := ptr.getInterfacePointer() - if p.isNil() { - return 0 - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - e := fi.oneofElems[telem] - return e.sizer(p, e.tagsize) - }, - func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) { - p := ptr.getInterfacePointer() - if p.isNil() { - return b, nil - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() { - return b, errOneofHasNil - } - e := fi.oneofElems[telem] - return e.marshaler(b, p, e.wiretag, deterministic) - } -} - -// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field. -func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, ei.tagsize) - } - mu.Unlock() - return n -} - -// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b. -func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if err != nil { - return b, err - } - } - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - // Not sure this is required, but the old code does it. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if err != nil { - return b, err - } - } - return b, nil -} - -// message set format is: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } - -// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field -// in message set format (above). -func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for id, e := range m { - n += 2 // start group, end group. tag = 1 (size=1) - n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - siz := len(msgWithLen) - n += siz + 1 // message, tag = 3 (size=1) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, 1) // message, tag = 3 (size=1) - } - mu.Unlock() - return n -} - -// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above) -// to the end of byte slice b. -func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for id, e := range m { - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - if err != nil { - return b, err - } - b = append(b, 1<<3|WireEndGroup) - } - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, id := range keys { - e := m[int32(id)] - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - b = append(b, 1<<3|WireEndGroup) - if err != nil { - return b, err - } - } - return b, nil -} - -// sizeV1Extensions computes the size of encoded data for a V1-API extension field. -func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int { - if m == nil { - return 0 - } - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, ei.tagsize) - } - return n -} - -// appendV1Extensions marshals a V1-API extension field to the end of byte slice b. -func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) { - if m == nil { - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - var err error - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if err != nil { - return b, err - } - } - return b, nil -} - -// newMarshaler is the interface representing objects that can marshal themselves. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newMarshaler interface { - XXX_Size() int - XXX_Marshal(b []byte, deterministic bool) ([]byte, error) -} - -// Size returns the encoded size of a protocol buffer message. -// This is the main entry point. -func Size(pb Message) int { - if m, ok := pb.(newMarshaler); ok { - return m.XXX_Size() - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, _ := m.Marshal() - return len(b) - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return 0 - } - var info InternalMessageInfo - return info.Size(pb) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, returning the data. -// This is the main entry point. -func Marshal(pb Message) ([]byte, error) { - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - b := make([]byte, 0, siz) - return m.XXX_Marshal(b, false) - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - return m.Marshal() - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return nil, ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - b := make([]byte, 0, siz) - return info.Marshal(b, pb, false) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, writing the result to the -// Buffer. -// This is an alternative entry point. It is not necessary to use -// a Buffer for most applications. -func (p *Buffer) Marshal(pb Message) error { - var err error - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - p.grow(siz) // make sure buf has enough capacity - p.buf, err = m.XXX_Marshal(p.buf, p.deterministic) - return err - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, err := m.Marshal() - p.buf = append(p.buf, b...) - return err - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - p.grow(siz) // make sure buf has enough capacity - p.buf, err = info.Marshal(p.buf, pb, p.deterministic) - return err -} - -// grow grows the buffer's capacity, if necessary, to guarantee space for -// another n bytes. After grow(n), at least n bytes can be written to the -// buffer without another allocation. -func (p *Buffer) grow(n int) { - need := len(p.buf) + n - if need <= cap(p.buf) { - return - } - newCap := len(p.buf) * 2 - if newCap < need { - newCap = need - } - p.buf = append(make([]byte, 0, newCap), p.buf...) -} diff --git a/libnetwork/vendor/github.com/golang/protobuf/proto/table_merge.go b/libnetwork/vendor/github.com/golang/protobuf/proto/table_merge.go deleted file mode 100644 index 5525def6a5..0000000000 --- a/libnetwork/vendor/github.com/golang/protobuf/proto/table_merge.go +++ /dev/null @@ -1,654 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -// Merge merges the src message into dst. -// This assumes that dst and src of the same type and are non-nil. -func (a *InternalMessageInfo) Merge(dst, src Message) { - mi := atomicLoadMergeInfo(&a.merge) - if mi == nil { - mi = getMergeInfo(reflect.TypeOf(dst).Elem()) - atomicStoreMergeInfo(&a.merge, mi) - } - mi.merge(toPointer(&dst), toPointer(&src)) -} - -type mergeInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []mergeFieldInfo - unrecognized field // Offset of XXX_unrecognized -} - -type mergeFieldInfo struct { - field field // Offset of field, guaranteed to be valid - - // isPointer reports whether the value in the field is a pointer. - // This is true for the following situations: - // * Pointer to struct - // * Pointer to basic type (proto2 only) - // * Slice (first value in slice header is a pointer) - // * String (first value in string header is a pointer) - isPointer bool - - // basicWidth reports the width of the field assuming that it is directly - // embedded in the struct (as is the case for basic types in proto3). - // The possible values are: - // 0: invalid - // 1: bool - // 4: int32, uint32, float32 - // 8: int64, uint64, float64 - basicWidth int - - // Where dst and src are pointers to the types being merged. - merge func(dst, src pointer) -} - -var ( - mergeInfoMap = map[reflect.Type]*mergeInfo{} - mergeInfoLock sync.Mutex -) - -func getMergeInfo(t reflect.Type) *mergeInfo { - mergeInfoLock.Lock() - defer mergeInfoLock.Unlock() - mi := mergeInfoMap[t] - if mi == nil { - mi = &mergeInfo{typ: t} - mergeInfoMap[t] = mi - } - return mi -} - -// merge merges src into dst assuming they are both of type *mi.typ. -func (mi *mergeInfo) merge(dst, src pointer) { - if dst.isNil() { - panic("proto: nil destination") - } - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&mi.initialized) == 0 { - mi.computeMergeInfo() - } - - for _, fi := range mi.fields { - sfp := src.offset(fi.field) - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string - continue - } - if fi.basicWidth > 0 { - switch { - case fi.basicWidth == 1 && !*sfp.toBool(): - continue - case fi.basicWidth == 4 && *sfp.toUint32() == 0: - continue - case fi.basicWidth == 8 && *sfp.toUint64() == 0: - continue - } - } - } - - dfp := dst.offset(fi.field) - fi.merge(dfp, sfp) - } - - // TODO: Make this faster? - out := dst.asPointerTo(mi.typ).Elem() - in := src.asPointerTo(mi.typ).Elem() - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - if mi.unrecognized.IsValid() { - if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { - *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) - } - } -} - -func (mi *mergeInfo) computeMergeInfo() { - mi.lock.Lock() - defer mi.lock.Unlock() - if mi.initialized != 0 { - return - } - t := mi.typ - n := t.NumField() - - props := GetProperties(t) - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - mfi := mergeFieldInfo{field: toField(&f)} - tf := f.Type - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - switch tf.Kind() { - case reflect.Ptr, reflect.Slice, reflect.String: - // As a special case, we assume slices and strings are pointers - // since we know that the first field in the SliceSlice or - // StringHeader is a data pointer. - mfi.isPointer = true - case reflect.Bool: - mfi.basicWidth = 1 - case reflect.Int32, reflect.Uint32, reflect.Float32: - mfi.basicWidth = 4 - case reflect.Int64, reflect.Uint64, reflect.Float64: - mfi.basicWidth = 8 - } - } - - // Unwrap tf to get at its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + tf.Name()) - } - - switch tf.Kind() { - case reflect.Int32: - switch { - case isSlice: // E.g., []int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Slice is not defined (see pointer_reflect.go). - /* - sfsp := src.toInt32Slice() - if *sfsp != nil { - dfsp := dst.toInt32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - */ - sfs := src.getInt32Slice() - if sfs != nil { - dfs := dst.getInt32Slice() - dfs = append(dfs, sfs...) - if dfs == nil { - dfs = []int32{} - } - dst.setInt32Slice(dfs) - } - } - case isPointer: // E.g., *int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). - /* - sfpp := src.toInt32Ptr() - if *sfpp != nil { - dfpp := dst.toInt32Ptr() - if *dfpp == nil { - *dfpp = Int32(**sfpp) - } else { - **dfpp = **sfpp - } - } - */ - sfp := src.getInt32Ptr() - if sfp != nil { - dfp := dst.getInt32Ptr() - if dfp == nil { - dst.setInt32Ptr(*sfp) - } else { - *dfp = *sfp - } - } - } - default: // E.g., int32 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt32(); v != 0 { - *dst.toInt32() = v - } - } - } - case reflect.Int64: - switch { - case isSlice: // E.g., []int64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toInt64Slice() - if *sfsp != nil { - dfsp := dst.toInt64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - } - case isPointer: // E.g., *int64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toInt64Ptr() - if *sfpp != nil { - dfpp := dst.toInt64Ptr() - if *dfpp == nil { - *dfpp = Int64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., int64 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt64(); v != 0 { - *dst.toInt64() = v - } - } - } - case reflect.Uint32: - switch { - case isSlice: // E.g., []uint32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint32Slice() - if *sfsp != nil { - dfsp := dst.toUint32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint32{} - } - } - } - case isPointer: // E.g., *uint32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint32Ptr() - if *sfpp != nil { - dfpp := dst.toUint32Ptr() - if *dfpp == nil { - *dfpp = Uint32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint32 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint32(); v != 0 { - *dst.toUint32() = v - } - } - } - case reflect.Uint64: - switch { - case isSlice: // E.g., []uint64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint64Slice() - if *sfsp != nil { - dfsp := dst.toUint64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint64{} - } - } - } - case isPointer: // E.g., *uint64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint64Ptr() - if *sfpp != nil { - dfpp := dst.toUint64Ptr() - if *dfpp == nil { - *dfpp = Uint64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint64 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint64(); v != 0 { - *dst.toUint64() = v - } - } - } - case reflect.Float32: - switch { - case isSlice: // E.g., []float32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat32Slice() - if *sfsp != nil { - dfsp := dst.toFloat32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float32{} - } - } - } - case isPointer: // E.g., *float32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat32Ptr() - if *sfpp != nil { - dfpp := dst.toFloat32Ptr() - if *dfpp == nil { - *dfpp = Float32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float32 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat32(); v != 0 { - *dst.toFloat32() = v - } - } - } - case reflect.Float64: - switch { - case isSlice: // E.g., []float64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat64Slice() - if *sfsp != nil { - dfsp := dst.toFloat64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float64{} - } - } - } - case isPointer: // E.g., *float64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat64Ptr() - if *sfpp != nil { - dfpp := dst.toFloat64Ptr() - if *dfpp == nil { - *dfpp = Float64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float64 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat64(); v != 0 { - *dst.toFloat64() = v - } - } - } - case reflect.Bool: - switch { - case isSlice: // E.g., []bool - mfi.merge = func(dst, src pointer) { - sfsp := src.toBoolSlice() - if *sfsp != nil { - dfsp := dst.toBoolSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []bool{} - } - } - } - case isPointer: // E.g., *bool - mfi.merge = func(dst, src pointer) { - sfpp := src.toBoolPtr() - if *sfpp != nil { - dfpp := dst.toBoolPtr() - if *dfpp == nil { - *dfpp = Bool(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., bool - mfi.merge = func(dst, src pointer) { - if v := *src.toBool(); v { - *dst.toBool() = v - } - } - } - case reflect.String: - switch { - case isSlice: // E.g., []string - mfi.merge = func(dst, src pointer) { - sfsp := src.toStringSlice() - if *sfsp != nil { - dfsp := dst.toStringSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []string{} - } - } - } - case isPointer: // E.g., *string - mfi.merge = func(dst, src pointer) { - sfpp := src.toStringPtr() - if *sfpp != nil { - dfpp := dst.toStringPtr() - if *dfpp == nil { - *dfpp = String(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., string - mfi.merge = func(dst, src pointer) { - if v := *src.toString(); v != "" { - *dst.toString() = v - } - } - } - case reflect.Slice: - isProto3 := props.Prop[i].proto3 - switch { - case isPointer: - panic("bad pointer in byte slice case in " + tf.Name()) - case tf.Elem().Kind() != reflect.Uint8: - panic("bad element kind in byte slice case in " + tf.Name()) - case isSlice: // E.g., [][]byte - mfi.merge = func(dst, src pointer) { - sbsp := src.toBytesSlice() - if *sbsp != nil { - dbsp := dst.toBytesSlice() - for _, sb := range *sbsp { - if sb == nil { - *dbsp = append(*dbsp, nil) - } else { - *dbsp = append(*dbsp, append([]byte{}, sb...)) - } - } - if *dbsp == nil { - *dbsp = [][]byte{} - } - } - } - default: // E.g., []byte - mfi.merge = func(dst, src pointer) { - sbp := src.toBytes() - if *sbp != nil { - dbp := dst.toBytes() - if !isProto3 || len(*sbp) > 0 { - *dbp = append([]byte{}, *sbp...) - } - } - } - } - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("message field %s without pointer", tf)) - case isSlice: // E.g., []*pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sps := src.getPointerSlice() - if sps != nil { - dps := dst.getPointerSlice() - for _, sp := range sps { - var dp pointer - if !sp.isNil() { - dp = valToPointer(reflect.New(tf)) - mi.merge(dp, sp) - } - dps = append(dps, dp) - } - if dps == nil { - dps = []pointer{} - } - dst.setPointerSlice(dps) - } - } - default: // E.g., *pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sp := src.getPointer() - if !sp.isNil() { - dp := dst.getPointer() - if dp.isNil() { - dp = valToPointer(reflect.New(tf)) - dst.setPointer(dp) - } - mi.merge(dp, sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic("bad pointer or slice in map case in " + tf.Name()) - default: // E.g., map[K]V - mfi.merge = func(dst, src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - dm := dst.asPointerTo(tf).Elem() - if dm.IsNil() { - dm.Set(reflect.MakeMap(tf)) - } - - switch tf.Elem().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(Clone(val.Interface().(Message))) - dm.SetMapIndex(key, val) - } - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - dm.SetMapIndex(key, val) - } - default: // Basic type (e.g., string) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - dm.SetMapIndex(key, val) - } - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic("bad pointer or slice in interface case in " + tf.Name()) - default: // E.g., interface{} - // TODO: Make this faster? - mfi.merge = func(dst, src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - du := dst.asPointerTo(tf).Elem() - typ := su.Elem().Type() - if du.IsNil() || du.Elem().Type() != typ { - du.Set(reflect.New(typ.Elem())) // Initialize interface if empty - } - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - dv := du.Elem().Elem().Field(0) - if dv.Kind() == reflect.Ptr && dv.IsNil() { - dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - Merge(dv.Interface().(Message), sv.Interface().(Message)) - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) - default: // Basic type (e.g., string) - dv.Set(sv) - } - } - } - } - default: - panic(fmt.Sprintf("merger not found for type:%s", tf)) - } - mi.fields = append(mi.fields, mfi) - } - - mi.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - mi.unrecognized = toField(&f) - } - - atomic.StoreInt32(&mi.initialized, 1) -} diff --git a/libnetwork/vendor/github.com/golang/protobuf/proto/table_unmarshal.go b/libnetwork/vendor/github.com/golang/protobuf/proto/table_unmarshal.go deleted file mode 100644 index 55f0340a3f..0000000000 --- a/libnetwork/vendor/github.com/golang/protobuf/proto/table_unmarshal.go +++ /dev/null @@ -1,1967 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "errors" - "fmt" - "io" - "math" - "reflect" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// Unmarshal is the entry point from the generated .pb.go files. -// This function is not intended to be used by non-generated code. -// This function is not subject to any compatibility guarantee. -// msg contains a pointer to a protocol buffer struct. -// b is the data to be unmarshaled into the protocol buffer. -// a is a pointer to a place to store cached unmarshal information. -func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { - // Load the unmarshal information for this message type. - // The atomic load ensures memory consistency. - u := atomicLoadUnmarshalInfo(&a.unmarshal) - if u == nil { - // Slow path: find unmarshal info for msg, update a with it. - u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) - atomicStoreUnmarshalInfo(&a.unmarshal, u) - } - // Then do the unmarshaling. - err := u.unmarshal(toPointer(&msg), b) - return err -} - -type unmarshalInfo struct { - typ reflect.Type // type of the protobuf struct - - // 0 = only typ field is initialized - // 1 = completely initialized - initialized int32 - lock sync.Mutex // prevents double initialization - dense []unmarshalFieldInfo // fields indexed by tag # - sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # - reqFields []string // names of required fields - reqMask uint64 // 1< 0 { - // Read tag and wire type. - // Special case 1 and 2 byte varints. - var x uint64 - if b[0] < 128 { - x = uint64(b[0]) - b = b[1:] - } else if len(b) >= 2 && b[1] < 128 { - x = uint64(b[0]&0x7f) + uint64(b[1])<<7 - b = b[2:] - } else { - var n int - x, n = decodeVarint(b) - if n == 0 { - return io.ErrUnexpectedEOF - } - b = b[n:] - } - tag := x >> 3 - wire := int(x) & 7 - - // Dispatch on the tag to one of the unmarshal* functions below. - var f unmarshalFieldInfo - if tag < uint64(len(u.dense)) { - f = u.dense[tag] - } else { - f = u.sparse[tag] - } - if fn := f.unmarshal; fn != nil { - var err error - b, err = fn(b, m.offset(f.field), wire) - if err == nil { - reqMask |= f.reqMask - continue - } - if r, ok := err.(*RequiredNotSetError); ok { - // Remember this error, but keep parsing. We need to produce - // a full parse even if a required field is missing. - rnse = r - reqMask |= f.reqMask - continue - } - if err != errInternalBadWireType { - return err - } - // Fragments with bad wire type are treated as unknown fields. - } - - // Unknown tag. - if !u.unrecognized.IsValid() { - // Don't keep unrecognized data; just skip it. - var err error - b, err = skipField(b, wire) - if err != nil { - return err - } - continue - } - // Keep unrecognized data around. - // maybe in extensions, maybe in the unrecognized field. - z := m.offset(u.unrecognized).toBytes() - var emap map[int32]Extension - var e Extension - for _, r := range u.extensionRanges { - if uint64(r.Start) <= tag && tag <= uint64(r.End) { - if u.extensions.IsValid() { - mp := m.offset(u.extensions).toExtensions() - emap = mp.extensionsWrite() - e = emap[int32(tag)] - z = &e.enc - break - } - if u.oldExtensions.IsValid() { - p := m.offset(u.oldExtensions).toOldExtensions() - emap = *p - if emap == nil { - emap = map[int32]Extension{} - *p = emap - } - e = emap[int32(tag)] - z = &e.enc - break - } - panic("no extensions field available") - } - } - - // Use wire type to skip data. - var err error - b0 := b - b, err = skipField(b, wire) - if err != nil { - return err - } - *z = encodeVarint(*z, tag<<3|uint64(wire)) - *z = append(*z, b0[:len(b0)-len(b)]...) - - if emap != nil { - emap[int32(tag)] = e - } - } - if rnse != nil { - // A required field of a submessage/group is missing. Return that error. - return rnse - } - if reqMask != u.reqMask { - // A required field of this message is missing. - for _, n := range u.reqFields { - if reqMask&1 == 0 { - return &RequiredNotSetError{n} - } - reqMask >>= 1 - } - } - return nil -} - -// computeUnmarshalInfo fills in u with information for use -// in unmarshaling protocol buffers of type u.typ. -func (u *unmarshalInfo) computeUnmarshalInfo() { - u.lock.Lock() - defer u.lock.Unlock() - if u.initialized != 0 { - return - } - t := u.typ - n := t.NumField() - - // Set up the "not found" value for the unrecognized byte buffer. - // This is the default for proto3. - u.unrecognized = invalidField - u.extensions = invalidField - u.oldExtensions = invalidField - - // List of the generated type and offset for each oneof field. - type oneofField struct { - ityp reflect.Type // interface type of oneof field - field field // offset in containing message - } - var oneofFields []oneofField - - for i := 0; i < n; i++ { - f := t.Field(i) - if f.Name == "XXX_unrecognized" { - // The byte slice used to hold unrecognized input is special. - if f.Type != reflect.TypeOf(([]byte)(nil)) { - panic("bad type for XXX_unrecognized field: " + f.Type.Name()) - } - u.unrecognized = toField(&f) - continue - } - if f.Name == "XXX_InternalExtensions" { - // Ditto here. - if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { - panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) - } - u.extensions = toField(&f) - if f.Tag.Get("protobuf_messageset") == "1" { - u.isMessageSet = true - } - continue - } - if f.Name == "XXX_extensions" { - // An older form of the extensions field. - if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) { - panic("bad type for XXX_extensions field: " + f.Type.Name()) - } - u.oldExtensions = toField(&f) - continue - } - if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { - continue - } - - oneof := f.Tag.Get("protobuf_oneof") - if oneof != "" { - oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) - // The rest of oneof processing happens below. - continue - } - - tags := f.Tag.Get("protobuf") - tagArray := strings.Split(tags, ",") - if len(tagArray) < 2 { - panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) - } - tag, err := strconv.Atoi(tagArray[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tagArray[1]) - } - - name := "" - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - } - - // Extract unmarshaling function from the field (its type and tags). - unmarshal := fieldUnmarshaler(&f) - - // Required field? - var reqMask uint64 - if tagArray[2] == "req" { - bit := len(u.reqFields) - u.reqFields = append(u.reqFields, name) - reqMask = uint64(1) << uint(bit) - // TODO: if we have more than 64 required fields, we end up - // not verifying that all required fields are present. - // Fix this, perhaps using a count of required fields? - } - - // Store the info in the correct slot in the message. - u.setTag(tag, toField(&f), unmarshal, reqMask) - } - - // Find any types associated with oneof fields. - // TODO: XXX_OneofFuncs returns more info than we need. Get rid of some of it? - fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("XXX_OneofFuncs") - if fn.IsValid() { - res := fn.Call(nil)[3] // last return value from XXX_OneofFuncs: []interface{} - for i := res.Len() - 1; i >= 0; i-- { - v := res.Index(i) // interface{} - tptr := reflect.ValueOf(v.Interface()).Type() // *Msg_X - typ := tptr.Elem() // Msg_X - - f := typ.Field(0) // oneof implementers have one field - baseUnmarshal := fieldUnmarshaler(&f) - tagstr := strings.Split(f.Tag.Get("protobuf"), ",")[1] - tag, err := strconv.Atoi(tagstr) - if err != nil { - panic("protobuf tag field not an integer: " + tagstr) - } - - // Find the oneof field that this struct implements. - // Might take O(n^2) to process all of the oneofs, but who cares. - for _, of := range oneofFields { - if tptr.Implements(of.ityp) { - // We have found the corresponding interface for this struct. - // That lets us know where this struct should be stored - // when we encounter it during unmarshaling. - unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) - u.setTag(tag, of.field, unmarshal, 0) - } - } - } - } - - // Get extension ranges, if any. - fn = reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") - if fn.IsValid() { - if !u.extensions.IsValid() && !u.oldExtensions.IsValid() { - panic("a message with extensions, but no extensions field in " + t.Name()) - } - u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) - } - - // Explicitly disallow tag 0. This will ensure we flag an error - // when decoding a buffer of all zeros. Without this code, we - // would decode and skip an all-zero buffer of even length. - // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. - u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { - return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) - }, 0) - - // Set mask for required field check. - u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? - for len(u.dense) <= tag { - u.dense = append(u.dense, unmarshalFieldInfo{}) - } - u.dense[tag] = i - return - } - if u.sparse == nil { - u.sparse = map[uint64]unmarshalFieldInfo{} - } - u.sparse[uint64(tag)] = i -} - -// fieldUnmarshaler returns an unmarshaler for the given field. -func fieldUnmarshaler(f *reflect.StructField) unmarshaler { - if f.Type.Kind() == reflect.Map { - return makeUnmarshalMap(f) - } - return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) -} - -// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. -func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { - tagArray := strings.Split(tags, ",") - encoding := tagArray[0] - name := "unknown" - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - } - - // Figure out packaging (pointer, slice, or both) - slice := false - pointer := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - // We'll never have both pointer and slice for basic types. - if pointer && slice && t.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + t.Name()) - } - - switch t.Kind() { - case reflect.Bool: - if pointer { - return unmarshalBoolPtr - } - if slice { - return unmarshalBoolSlice - } - return unmarshalBoolValue - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixedS32Ptr - } - if slice { - return unmarshalFixedS32Slice - } - return unmarshalFixedS32Value - case "varint": - // this could be int32 or enum - if pointer { - return unmarshalInt32Ptr - } - if slice { - return unmarshalInt32Slice - } - return unmarshalInt32Value - case "zigzag32": - if pointer { - return unmarshalSint32Ptr - } - if slice { - return unmarshalSint32Slice - } - return unmarshalSint32Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixedS64Ptr - } - if slice { - return unmarshalFixedS64Slice - } - return unmarshalFixedS64Value - case "varint": - if pointer { - return unmarshalInt64Ptr - } - if slice { - return unmarshalInt64Slice - } - return unmarshalInt64Value - case "zigzag64": - if pointer { - return unmarshalSint64Ptr - } - if slice { - return unmarshalSint64Slice - } - return unmarshalSint64Value - } - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixed32Ptr - } - if slice { - return unmarshalFixed32Slice - } - return unmarshalFixed32Value - case "varint": - if pointer { - return unmarshalUint32Ptr - } - if slice { - return unmarshalUint32Slice - } - return unmarshalUint32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixed64Ptr - } - if slice { - return unmarshalFixed64Slice - } - return unmarshalFixed64Value - case "varint": - if pointer { - return unmarshalUint64Ptr - } - if slice { - return unmarshalUint64Slice - } - return unmarshalUint64Value - } - case reflect.Float32: - if pointer { - return unmarshalFloat32Ptr - } - if slice { - return unmarshalFloat32Slice - } - return unmarshalFloat32Value - case reflect.Float64: - if pointer { - return unmarshalFloat64Ptr - } - if slice { - return unmarshalFloat64Slice - } - return unmarshalFloat64Value - case reflect.Map: - panic("map type in typeUnmarshaler in " + t.Name()) - case reflect.Slice: - if pointer { - panic("bad pointer in slice case in " + t.Name()) - } - if slice { - return unmarshalBytesSlice - } - return unmarshalBytesValue - case reflect.String: - if pointer { - return unmarshalStringPtr - } - if slice { - return unmarshalStringSlice - } - return unmarshalStringValue - case reflect.Struct: - // message or group field - if !pointer { - panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding)) - } - switch encoding { - case "bytes": - if slice { - return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) - case "group": - if slice { - return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) - } - } - panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) -} - -// Below are all the unmarshalers for individual fields of various types. - -func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64() = v - return b, nil -} - -func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64() = v - return b, nil -} - -func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64() = v - return b, nil -} - -func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64Ptr() = &v - return b, nil -} - -func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - *f.toInt32() = v - return b, nil -} - -func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - *f.toInt32() = v - return b, nil -} - -func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32() = v - return b, nil -} - -func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32Ptr() = &v - return b, nil -} - -func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64() = v - return b[8:], nil -} - -func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64() = v - return b[8:], nil -} - -func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32() = v - return b[4:], nil -} - -func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32Ptr() = &v - return b[4:], nil -} - -func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - *f.toInt32() = v - return b[4:], nil -} - -func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.setInt32Ptr(v) - return b[4:], nil -} - -func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - return b[4:], nil -} - -func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - // Note: any length varint is allowed, even though any sane - // encoder will use one byte. - // See https://github.com/golang/protobuf/issues/76 - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - // TODO: check if x>1? Tests seem to indicate no. - v := x != 0 - *f.toBool() = v - return b[n:], nil -} - -func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - *f.toBoolPtr() = &v - return b[n:], nil -} - -func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - b = b[n:] - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - return b[n:], nil -} - -func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64() = v - return b[8:], nil -} - -func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64Ptr() = &v - return b[8:], nil -} - -func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32() = v - return b[4:], nil -} - -func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32Ptr() = &v - return b[4:], nil -} - -func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - *f.toString() = v - return b[x:], nil -} - -func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - *f.toStringPtr() = &v - return b[x:], nil -} - -func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - s := f.toStringSlice() - *s = append(*s, v) - return b[x:], nil -} - -var emptyBuf [0]byte - -func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // The use of append here is a trick which avoids the zeroing - // that would be required if we used a make/copy pair. - // We append to emptyBuf instead of nil because we want - // a non-nil result even when the length is 0. - v := append(emptyBuf[:], b[:x]...) - *f.toBytes() = v - return b[x:], nil -} - -func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := append(emptyBuf[:], b[:x]...) - s := f.toBytesSlice() - *s = append(*s, v) - return b[x:], nil -} - -func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // First read the message field to see if something is there. - // The semantics of multiple submessages are weird. Instead of - // the last one winning (as it is for all other fields), multiple - // submessages are merged. - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[x:], err - } -} - -func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[x:], err - } -} - -func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[y:], err - } -} - -func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[y:], err - } -} - -func makeUnmarshalMap(f *reflect.StructField) unmarshaler { - t := f.Type - kt := t.Key() - vt := t.Elem() - unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key")) - unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val")) - return func(b []byte, f pointer, w int) ([]byte, error) { - // The map entry is a submessage. Figure out how big it is. - if w != WireBytes { - return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes) - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - r := b[x:] // unused data to return - b = b[:x] // data for map entry - - // Note: we could use #keys * #values ~= 200 functions - // to do map decoding without reflection. Probably not worth it. - // Maps will be somewhat slow. Oh well. - - // Read key and value from data. - k := reflect.New(kt) - v := reflect.New(vt) - for len(b) > 0 { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - wire := int(x) & 7 - b = b[n:] - - var err error - switch x >> 3 { - case 1: - b, err = unmarshalKey(b, valToPointer(k), wire) - case 2: - b, err = unmarshalVal(b, valToPointer(v), wire) - default: - err = errInternalBadWireType // skip unknown tag - } - - if err == nil { - continue - } - if err != errInternalBadWireType { - return nil, err - } - - // Skip past unknown fields. - b, err = skipField(b, wire) - if err != nil { - return nil, err - } - } - - // Get map, allocate if needed. - m := f.asPointerTo(t).Elem() // an addressable map[K]T - if m.IsNil() { - m.Set(reflect.MakeMap(t)) - } - - // Insert into map. - m.SetMapIndex(k.Elem(), v.Elem()) - - return r, nil - } -} - -// makeUnmarshalOneof makes an unmarshaler for oneof fields. -// for: -// message Msg { -// oneof F { -// int64 X = 1; -// float64 Y = 2; -// } -// } -// typ is the type of the concrete entry for a oneof case (e.g. Msg_X). -// ityp is the interface type of the oneof field (e.g. isMsg_F). -// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64). -// Note that this function will be called once for each case in the oneof. -func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler { - sf := typ.Field(0) - field0 := toField(&sf) - return func(b []byte, f pointer, w int) ([]byte, error) { - // Allocate holder for value. - v := reflect.New(typ) - - // Unmarshal data into holder. - // We unmarshal into the first field of the holder object. - var err error - b, err = unmarshal(b, valToPointer(v).offset(field0), w) - if err != nil { - return nil, err - } - - // Write pointer to holder into target field. - f.asPointerTo(ityp).Elem().Set(v) - - return b, nil - } -} - -// Error used by decode internally. -var errInternalBadWireType = errors.New("proto: internal error: bad wiretype") - -// skipField skips past a field of type wire and returns the remaining bytes. -func skipField(b []byte, wire int) ([]byte, error) { - switch wire { - case WireVarint: - _, k := decodeVarint(b) - if k == 0 { - return b, io.ErrUnexpectedEOF - } - b = b[k:] - case WireFixed32: - if len(b) < 4 { - return b, io.ErrUnexpectedEOF - } - b = b[4:] - case WireFixed64: - if len(b) < 8 { - return b, io.ErrUnexpectedEOF - } - b = b[8:] - case WireBytes: - m, k := decodeVarint(b) - if k == 0 || uint64(len(b)-k) < m { - return b, io.ErrUnexpectedEOF - } - b = b[uint64(k)+m:] - case WireStartGroup: - _, i := findEndGroup(b) - if i == -1 { - return b, io.ErrUnexpectedEOF - } - b = b[i:] - default: - return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire) - } - return b, nil -} - -// findEndGroup finds the index of the next EndGroup tag. -// Groups may be nested, so the "next" EndGroup tag is the first -// unpaired EndGroup. -// findEndGroup returns the indexes of the start and end of the EndGroup tag. -// Returns (-1,-1) if it can't find one. -func findEndGroup(b []byte) (int, int) { - depth := 1 - i := 0 - for { - x, n := decodeVarint(b[i:]) - if n == 0 { - return -1, -1 - } - j := i - i += n - switch x & 7 { - case WireVarint: - _, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - case WireFixed32: - if len(b)-4 < i { - return -1, -1 - } - i += 4 - case WireFixed64: - if len(b)-8 < i { - return -1, -1 - } - i += 8 - case WireBytes: - m, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - if uint64(len(b)-i) < m { - return -1, -1 - } - i += int(m) - case WireStartGroup: - depth++ - case WireEndGroup: - depth-- - if depth == 0 { - return j, i - } - default: - return -1, -1 - } - } -} - -// encodeVarint appends a varint-encoded integer to b and returns the result. -func encodeVarint(b []byte, x uint64) []byte { - for x >= 1<<7 { - b = append(b, byte(x&0x7f|0x80)) - x >>= 7 - } - return append(b, byte(x)) -} - -// decodeVarint reads a varint-encoded integer from b. -// Returns the decoded integer and the number of bytes read. -// If there is an error, it returns 0,0. -func decodeVarint(b []byte) (uint64, int) { - var x, y uint64 - if len(b) <= 0 { - goto bad - } - x = uint64(b[0]) - if x < 0x80 { - return x, 1 - } - x -= 0x80 - - if len(b) <= 1 { - goto bad - } - y = uint64(b[1]) - x += y << 7 - if y < 0x80 { - return x, 2 - } - x -= 0x80 << 7 - - if len(b) <= 2 { - goto bad - } - y = uint64(b[2]) - x += y << 14 - if y < 0x80 { - return x, 3 - } - x -= 0x80 << 14 - - if len(b) <= 3 { - goto bad - } - y = uint64(b[3]) - x += y << 21 - if y < 0x80 { - return x, 4 - } - x -= 0x80 << 21 - - if len(b) <= 4 { - goto bad - } - y = uint64(b[4]) - x += y << 28 - if y < 0x80 { - return x, 5 - } - x -= 0x80 << 28 - - if len(b) <= 5 { - goto bad - } - y = uint64(b[5]) - x += y << 35 - if y < 0x80 { - return x, 6 - } - x -= 0x80 << 35 - - if len(b) <= 6 { - goto bad - } - y = uint64(b[6]) - x += y << 42 - if y < 0x80 { - return x, 7 - } - x -= 0x80 << 42 - - if len(b) <= 7 { - goto bad - } - y = uint64(b[7]) - x += y << 49 - if y < 0x80 { - return x, 8 - } - x -= 0x80 << 49 - - if len(b) <= 8 { - goto bad - } - y = uint64(b[8]) - x += y << 56 - if y < 0x80 { - return x, 9 - } - x -= 0x80 << 56 - - if len(b) <= 9 { - goto bad - } - y = uint64(b[9]) - x += y << 63 - if y < 2 { - return x, 10 - } - -bad: - return 0, 0 -} diff --git a/libnetwork/vendor/github.com/opencontainers/runc/libcontainer/mount/mount.go b/libnetwork/vendor/github.com/opencontainers/runc/libcontainer/mount/mount.go deleted file mode 100644 index e8965e081b..0000000000 --- a/libnetwork/vendor/github.com/opencontainers/runc/libcontainer/mount/mount.go +++ /dev/null @@ -1,23 +0,0 @@ -package mount - -// GetMounts retrieves a list of mounts for the current running process. -func GetMounts() ([]*Info, error) { - return parseMountTable() -} - -// Mounted looks at /proc/self/mountinfo to determine of the specified -// mountpoint has been mounted -func Mounted(mountpoint string) (bool, error) { - entries, err := parseMountTable() - if err != nil { - return false, err - } - - // Search the table for the mountpoint - for _, e := range entries { - if e.Mountpoint == mountpoint { - return true, nil - } - } - return false, nil -} diff --git a/libnetwork/vendor/github.com/opencontainers/runc/libcontainer/mount/mount_linux.go b/libnetwork/vendor/github.com/opencontainers/runc/libcontainer/mount/mount_linux.go deleted file mode 100644 index 1e5191928d..0000000000 --- a/libnetwork/vendor/github.com/opencontainers/runc/libcontainer/mount/mount_linux.go +++ /dev/null @@ -1,82 +0,0 @@ -// +build linux - -package mount - -import ( - "bufio" - "fmt" - "io" - "os" - "strings" -) - -const ( - /* 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue - (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11) - - (1) mount ID: unique identifier of the mount (may be reused after umount) - (2) parent ID: ID of parent (or of self for the top of the mount tree) - (3) major:minor: value of st_dev for files on filesystem - (4) root: root of the mount within the filesystem - (5) mount point: mount point relative to the process's root - (6) mount options: per mount options - (7) optional fields: zero or more fields of the form "tag[:value]" - (8) separator: marks the end of the optional fields - (9) filesystem type: name of filesystem of the form "type[.subtype]" - (10) mount source: filesystem specific information or "none" - (11) super options: per super block options*/ - mountinfoFormat = "%d %d %d:%d %s %s %s %s" -) - -// Parse /proc/self/mountinfo because comparing Dev and ino does not work from -// bind mounts -func parseMountTable() ([]*Info, error) { - f, err := os.Open("/proc/self/mountinfo") - if err != nil { - return nil, err - } - defer f.Close() - - return parseInfoFile(f) -} - -func parseInfoFile(r io.Reader) ([]*Info, error) { - var ( - s = bufio.NewScanner(r) - out = []*Info{} - ) - - for s.Scan() { - if err := s.Err(); err != nil { - return nil, err - } - - var ( - p = &Info{} - text = s.Text() - optionalFields string - ) - - if _, err := fmt.Sscanf(text, mountinfoFormat, - &p.ID, &p.Parent, &p.Major, &p.Minor, - &p.Root, &p.Mountpoint, &p.Opts, &optionalFields); err != nil { - return nil, fmt.Errorf("Scanning '%s' failed: %s", text, err) - } - // Safe as mountinfo encodes mountpoints with spaces as \040. - index := strings.Index(text, " - ") - postSeparatorFields := strings.Fields(text[index+3:]) - if len(postSeparatorFields) < 3 { - return nil, fmt.Errorf("Error found less than 3 fields post '-' in %q", text) - } - - if optionalFields != "-" { - p.Optional = optionalFields - } - - p.Fstype = postSeparatorFields[0] - p.Source = postSeparatorFields[1] - p.VfsOpts = strings.Join(postSeparatorFields[2:], " ") - out = append(out, p) - } - return out, nil -} diff --git a/libnetwork/vendor/github.com/opencontainers/runc/libcontainer/mount/mountinfo.go b/libnetwork/vendor/github.com/opencontainers/runc/libcontainer/mount/mountinfo.go deleted file mode 100644 index e3fc3535e9..0000000000 --- a/libnetwork/vendor/github.com/opencontainers/runc/libcontainer/mount/mountinfo.go +++ /dev/null @@ -1,40 +0,0 @@ -package mount - -// Info reveals information about a particular mounted filesystem. This -// struct is populated from the content in the /proc//mountinfo file. -type Info struct { - // ID is a unique identifier of the mount (may be reused after umount). - ID int - - // Parent indicates the ID of the mount parent (or of self for the top of the - // mount tree). - Parent int - - // Major indicates one half of the device ID which identifies the device class. - Major int - - // Minor indicates one half of the device ID which identifies a specific - // instance of device. - Minor int - - // Root of the mount within the filesystem. - Root string - - // Mountpoint indicates the mount point relative to the process's root. - Mountpoint string - - // Opts represents mount-specific options. - Opts string - - // Optional represents optional fields. - Optional string - - // Fstype indicates the type of filesystem, such as EXT3. - Fstype string - - // Source indicates filesystem specific information or "none". - Source string - - // VfsOpts represents per super block options. - VfsOpts string -} diff --git a/libnetwork/vendor/golang.org/x/crypto/otr/libotr_test_helper.c b/libnetwork/vendor/golang.org/x/crypto/otr/libotr_test_helper.c deleted file mode 100644 index b3ca072d48..0000000000 --- a/libnetwork/vendor/golang.org/x/crypto/otr/libotr_test_helper.c +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This code can be compiled and used to test the otr package against libotr. -// See otr_test.go. - -// +build ignore - -#include -#include -#include - -#include -#include -#include - -static int g_session_established = 0; - -OtrlPolicy policy(void *opdata, ConnContext *context) { - return OTRL_POLICY_ALWAYS; -} - -int is_logged_in(void *opdata, const char *accountname, const char *protocol, - const char *recipient) { - return 1; -} - -void inject_message(void *opdata, const char *accountname, const char *protocol, - const char *recipient, const char *message) { - printf("%s\n", message); - fflush(stdout); - fprintf(stderr, "libotr helper sent: %s\n", message); -} - -void update_context_list(void *opdata) {} - -void new_fingerprint(void *opdata, OtrlUserState us, const char *accountname, - const char *protocol, const char *username, - unsigned char fingerprint[20]) { - fprintf(stderr, "NEW FINGERPRINT\n"); - g_session_established = 1; -} - -void write_fingerprints(void *opdata) {} - -void gone_secure(void *opdata, ConnContext *context) {} - -void gone_insecure(void *opdata, ConnContext *context) {} - -void still_secure(void *opdata, ConnContext *context, int is_reply) {} - -int max_message_size(void *opdata, ConnContext *context) { return 99999; } - -const char *account_name(void *opdata, const char *account, - const char *protocol) { - return "ACCOUNT"; -} - -void account_name_free(void *opdata, const char *account_name) {} - -const char *error_message(void *opdata, ConnContext *context, - OtrlErrorCode err_code) { - return "ERR"; -} - -void error_message_free(void *opdata, const char *msg) {} - -void resent_msg_prefix_free(void *opdata, const char *prefix) {} - -void handle_smp_event(void *opdata, OtrlSMPEvent smp_event, - ConnContext *context, unsigned short progress_event, - char *question) {} - -void handle_msg_event(void *opdata, OtrlMessageEvent msg_event, - ConnContext *context, const char *message, - gcry_error_t err) { - fprintf(stderr, "msg event: %d %s\n", msg_event, message); -} - -OtrlMessageAppOps uiops = { - policy, - NULL, - is_logged_in, - inject_message, - update_context_list, - new_fingerprint, - write_fingerprints, - gone_secure, - gone_insecure, - still_secure, - max_message_size, - account_name, - account_name_free, - NULL, /* received_symkey */ - error_message, - error_message_free, - NULL, /* resent_msg_prefix */ - resent_msg_prefix_free, - handle_smp_event, - handle_msg_event, - NULL /* create_instag */, - NULL /* convert_msg */, - NULL /* convert_free */, - NULL /* timer_control */, -}; - -static const char kPrivateKeyData[] = - "(privkeys (account (name \"account\") (protocol proto) (private-key (dsa " - "(p " - "#00FC07ABCF0DC916AFF6E9AE47BEF60C7AB9B4D6B2469E436630E36F8A489BE812486A09F" - "30B71224508654940A835301ACC525A4FF133FC152CC53DCC59D65C30A54F1993FE13FE63E" - "5823D4C746DB21B90F9B9C00B49EC7404AB1D929BA7FBA12F2E45C6E0A651689750E8528AB" - "8C031D3561FECEE72EBB4A090D450A9B7A857#) (q " - "#00997BD266EF7B1F60A5C23F3A741F2AEFD07A2081#) (g " - "#535E360E8A95EBA46A4F7DE50AD6E9B2A6DB785A66B64EB9F20338D2A3E8FB0E94725848F" - "1AA6CC567CB83A1CC517EC806F2E92EAE71457E80B2210A189B91250779434B41FC8A8873F" - "6DB94BEA7D177F5D59E7E114EE10A49CFD9CEF88AE43387023B672927BA74B04EB6BBB5E57" - "597766A2F9CE3857D7ACE3E1E3BC1FC6F26#) (y " - "#0AC8670AD767D7A8D9D14CC1AC6744CD7D76F993B77FFD9E39DF01E5A6536EF65E775FCEF" - "2A983E2A19BD6415500F6979715D9FD1257E1FE2B6F5E1E74B333079E7C880D39868462A93" - "454B41877BE62E5EF0A041C2EE9C9E76BD1E12AE25D9628DECB097025DD625EF49C3258A1A" - "3C0FF501E3DC673B76D7BABF349009B6ECF#) (x " - "#14D0345A3562C480A039E3C72764F72D79043216#)))))\n"; - -int main() { - OTRL_INIT; - - // We have to write the private key information to a file because the libotr - // API demands a filename to read from. - const char *tmpdir = "/tmp"; - if (getenv("TMP")) { - tmpdir = getenv("TMP"); - } - - char private_key_file[256]; - snprintf(private_key_file, sizeof(private_key_file), - "%s/libotr_test_helper_privatekeys-XXXXXX", tmpdir); - int fd = mkstemp(private_key_file); - if (fd == -1) { - perror("creating temp file"); - } - write(fd, kPrivateKeyData, sizeof(kPrivateKeyData) - 1); - close(fd); - - OtrlUserState userstate = otrl_userstate_create(); - otrl_privkey_read(userstate, private_key_file); - unlink(private_key_file); - - fprintf(stderr, "libotr helper started\n"); - - char buf[4096]; - - for (;;) { - char *message = fgets(buf, sizeof(buf), stdin); - if (strlen(message) == 0) { - break; - } - message[strlen(message) - 1] = 0; - fprintf(stderr, "libotr helper got: %s\n", message); - - char *newmessage = NULL; - OtrlTLV *tlvs; - int ignore_message = otrl_message_receiving( - userstate, &uiops, NULL, "account", "proto", "peer", message, - &newmessage, &tlvs, NULL, NULL, NULL); - if (tlvs) { - otrl_tlv_free(tlvs); - } - - if (newmessage != NULL) { - fprintf(stderr, "libotr got: %s\n", newmessage); - otrl_message_free(newmessage); - - gcry_error_t err; - char *newmessage = NULL; - - err = otrl_message_sending(userstate, &uiops, NULL, "account", "proto", - "peer", 0, "test message", NULL, &newmessage, - OTRL_FRAGMENT_SEND_SKIP, NULL, NULL, NULL); - if (newmessage == NULL) { - fprintf(stderr, "libotr didn't encrypt message\n"); - return 1; - } - write(1, newmessage, strlen(newmessage)); - write(1, "\n", 1); - fprintf(stderr, "libotr sent: %s\n", newmessage); - otrl_message_free(newmessage); - - g_session_established = 0; - write(1, "?OTRv2?\n", 8); - fprintf(stderr, "libotr sent: ?OTRv2\n"); - } - } - - return 0; -} diff --git a/libnetwork/vendor/golang.org/x/crypto/otr/otr.go b/libnetwork/vendor/golang.org/x/crypto/otr/otr.go deleted file mode 100644 index 173b753dbd..0000000000 --- a/libnetwork/vendor/golang.org/x/crypto/otr/otr.go +++ /dev/null @@ -1,1415 +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 otr implements the Off The Record protocol as specified in -// http://www.cypherpunks.ca/otr/Protocol-v2-3.1.0.html -package otr // import "golang.org/x/crypto/otr" - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/dsa" - "crypto/hmac" - "crypto/rand" - "crypto/sha1" - "crypto/sha256" - "crypto/subtle" - "encoding/base64" - "encoding/hex" - "errors" - "hash" - "io" - "math/big" - "strconv" -) - -// SecurityChange describes a change in the security state of a Conversation. -type SecurityChange int - -const ( - NoChange SecurityChange = iota - // NewKeys indicates that a key exchange has completed. This occurs - // when a conversation first becomes encrypted, and when the keys are - // renegotiated within an encrypted conversation. - NewKeys - // SMPSecretNeeded indicates that the peer has started an - // authentication and that we need to supply a secret. Call SMPQuestion - // to get the optional, human readable challenge and then Authenticate - // to supply the matching secret. - SMPSecretNeeded - // SMPComplete indicates that an authentication completed. The identity - // of the peer has now been confirmed. - SMPComplete - // SMPFailed indicates that an authentication failed. - SMPFailed - // ConversationEnded indicates that the peer ended the secure - // conversation. - ConversationEnded -) - -// QueryMessage can be sent to a peer to start an OTR conversation. -var QueryMessage = "?OTRv2?" - -// ErrorPrefix can be used to make an OTR error by appending an error message -// to it. -var ErrorPrefix = "?OTR Error:" - -var ( - fragmentPartSeparator = []byte(",") - fragmentPrefix = []byte("?OTR,") - msgPrefix = []byte("?OTR:") - queryMarker = []byte("?OTR") -) - -// isQuery attempts to parse an OTR query from msg and returns the greatest -// common version, or 0 if msg is not an OTR query. -func isQuery(msg []byte) (greatestCommonVersion int) { - pos := bytes.Index(msg, queryMarker) - if pos == -1 { - return 0 - } - for i, c := range msg[pos+len(queryMarker):] { - if i == 0 { - if c == '?' { - // Indicates support for version 1, but we don't - // implement that. - continue - } - - if c != 'v' { - // Invalid message - return 0 - } - - continue - } - - if c == '?' { - // End of message - return - } - - if c == ' ' || c == '\t' { - // Probably an invalid message - return 0 - } - - if c == '2' { - greatestCommonVersion = 2 - } - } - - return 0 -} - -const ( - statePlaintext = iota - stateEncrypted - stateFinished -) - -const ( - authStateNone = iota - authStateAwaitingDHKey - authStateAwaitingRevealSig - authStateAwaitingSig -) - -const ( - msgTypeDHCommit = 2 - msgTypeData = 3 - msgTypeDHKey = 10 - msgTypeRevealSig = 17 - msgTypeSig = 18 -) - -const ( - // If the requested fragment size is less than this, it will be ignored. - minFragmentSize = 18 - // Messages are padded to a multiple of this number of bytes. - paddingGranularity = 256 - // The number of bytes in a Diffie-Hellman private value (320-bits). - dhPrivateBytes = 40 - // The number of bytes needed to represent an element of the DSA - // subgroup (160-bits). - dsaSubgroupBytes = 20 - // The number of bytes of the MAC that are sent on the wire (160-bits). - macPrefixBytes = 20 -) - -// These are the global, common group parameters for OTR. -var ( - p *big.Int // group prime - g *big.Int // group generator - q *big.Int // group order - pMinus2 *big.Int -) - -func init() { - p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", 16) - q, _ = new(big.Int).SetString("7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68948127044533E63A0105DF531D89CD9128A5043CC71A026EF7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6F71C35FDAD44CFD2D74F9208BE258FF324943328F6722D9EE1003E5C50B1DF82CC6D241B0E2AE9CD348B1FD47E9267AFC1B2AE91EE51D6CB0E3179AB1042A95DCF6A9483B84B4B36B3861AA7255E4C0278BA36046511B993FFFFFFFFFFFFFFFF", 16) - g = new(big.Int).SetInt64(2) - pMinus2 = new(big.Int).Sub(p, g) -} - -// Conversation represents a relation with a peer. The zero value is a valid -// Conversation, although PrivateKey must be set. -// -// When communicating with a peer, all inbound messages should be passed to -// Conversation.Receive and all outbound messages to Conversation.Send. The -// Conversation will take care of maintaining the encryption state and -// negotiating encryption as needed. -type Conversation struct { - // PrivateKey contains the private key to use to sign key exchanges. - PrivateKey *PrivateKey - - // Rand can be set to override the entropy source. Otherwise, - // crypto/rand will be used. - Rand io.Reader - // If FragmentSize is set, all messages produced by Receive and Send - // will be fragmented into messages of, at most, this number of bytes. - FragmentSize int - - // Once Receive has returned NewKeys once, the following fields are - // valid. - SSID [8]byte - TheirPublicKey PublicKey - - state, authState int - - r [16]byte - x, y *big.Int - gx, gy *big.Int - gxBytes []byte - digest [sha256.Size]byte - - revealKeys, sigKeys akeKeys - - myKeyId uint32 - myCurrentDHPub *big.Int - myCurrentDHPriv *big.Int - myLastDHPub *big.Int - myLastDHPriv *big.Int - - theirKeyId uint32 - theirCurrentDHPub *big.Int - theirLastDHPub *big.Int - - keySlots [4]keySlot - - myCounter [8]byte - theirLastCtr [8]byte - oldMACs []byte - - k, n int // fragment state - frag []byte - - smp smpState -} - -// A keySlot contains key material for a specific (their keyid, my keyid) pair. -type keySlot struct { - // used is true if this slot is valid. If false, it's free for reuse. - used bool - theirKeyId uint32 - myKeyId uint32 - sendAESKey, recvAESKey []byte - sendMACKey, recvMACKey []byte - theirLastCtr [8]byte -} - -// akeKeys are generated during key exchange. There's one set for the reveal -// signature message and another for the signature message. In the protocol -// spec the latter are indicated with a prime mark. -type akeKeys struct { - c [16]byte - m1, m2 [32]byte -} - -func (c *Conversation) rand() io.Reader { - if c.Rand != nil { - return c.Rand - } - return rand.Reader -} - -func (c *Conversation) randMPI(buf []byte) *big.Int { - _, err := io.ReadFull(c.rand(), buf) - if err != nil { - panic("otr: short read from random source") - } - - return new(big.Int).SetBytes(buf) -} - -// tlv represents the type-length value from the protocol. -type tlv struct { - typ, length uint16 - data []byte -} - -const ( - tlvTypePadding = 0 - tlvTypeDisconnected = 1 - tlvTypeSMP1 = 2 - tlvTypeSMP2 = 3 - tlvTypeSMP3 = 4 - tlvTypeSMP4 = 5 - tlvTypeSMPAbort = 6 - tlvTypeSMP1WithQuestion = 7 -) - -// Receive handles a message from a peer. It returns a human readable message, -// an indicator of whether that message was encrypted, a hint about the -// encryption state and zero or more messages to send back to the peer. -// These messages do not need to be passed to Send before transmission. -func (c *Conversation) Receive(in []byte) (out []byte, encrypted bool, change SecurityChange, toSend [][]byte, err error) { - if bytes.HasPrefix(in, fragmentPrefix) { - in, err = c.processFragment(in) - if in == nil || err != nil { - return - } - } - - if bytes.HasPrefix(in, msgPrefix) && in[len(in)-1] == '.' { - in = in[len(msgPrefix) : len(in)-1] - } else if version := isQuery(in); version > 0 { - c.authState = authStateAwaitingDHKey - c.reset() - toSend = c.encode(c.generateDHCommit()) - return - } else { - // plaintext message - out = in - return - } - - msg := make([]byte, base64.StdEncoding.DecodedLen(len(in))) - msgLen, err := base64.StdEncoding.Decode(msg, in) - if err != nil { - err = errors.New("otr: invalid base64 encoding in message") - return - } - msg = msg[:msgLen] - - // The first two bytes are the protocol version (2) - if len(msg) < 3 || msg[0] != 0 || msg[1] != 2 { - err = errors.New("otr: invalid OTR message") - return - } - - msgType := int(msg[2]) - msg = msg[3:] - - switch msgType { - case msgTypeDHCommit: - switch c.authState { - case authStateNone: - c.authState = authStateAwaitingRevealSig - if err = c.processDHCommit(msg); err != nil { - return - } - c.reset() - toSend = c.encode(c.generateDHKey()) - return - case authStateAwaitingDHKey: - // This is a 'SYN-crossing'. The greater digest wins. - var cmp int - if cmp, err = c.compareToDHCommit(msg); err != nil { - return - } - if cmp > 0 { - // We win. Retransmit DH commit. - toSend = c.encode(c.serializeDHCommit()) - return - } else { - // They win. We forget about our DH commit. - c.authState = authStateAwaitingRevealSig - if err = c.processDHCommit(msg); err != nil { - return - } - c.reset() - toSend = c.encode(c.generateDHKey()) - return - } - case authStateAwaitingRevealSig: - if err = c.processDHCommit(msg); err != nil { - return - } - toSend = c.encode(c.serializeDHKey()) - case authStateAwaitingSig: - if err = c.processDHCommit(msg); err != nil { - return - } - c.reset() - toSend = c.encode(c.generateDHKey()) - c.authState = authStateAwaitingRevealSig - default: - panic("bad state") - } - case msgTypeDHKey: - switch c.authState { - case authStateAwaitingDHKey: - var isSame bool - if isSame, err = c.processDHKey(msg); err != nil { - return - } - if isSame { - err = errors.New("otr: unexpected duplicate DH key") - return - } - toSend = c.encode(c.generateRevealSig()) - c.authState = authStateAwaitingSig - case authStateAwaitingSig: - var isSame bool - if isSame, err = c.processDHKey(msg); err != nil { - return - } - if isSame { - toSend = c.encode(c.serializeDHKey()) - } - } - case msgTypeRevealSig: - if c.authState != authStateAwaitingRevealSig { - return - } - if err = c.processRevealSig(msg); err != nil { - return - } - toSend = c.encode(c.generateSig()) - c.authState = authStateNone - c.state = stateEncrypted - change = NewKeys - case msgTypeSig: - if c.authState != authStateAwaitingSig { - return - } - if err = c.processSig(msg); err != nil { - return - } - c.authState = authStateNone - c.state = stateEncrypted - change = NewKeys - case msgTypeData: - if c.state != stateEncrypted { - err = errors.New("otr: encrypted message received without encrypted session established") - return - } - var tlvs []tlv - out, tlvs, err = c.processData(msg) - encrypted = true - - EachTLV: - for _, inTLV := range tlvs { - switch inTLV.typ { - case tlvTypeDisconnected: - change = ConversationEnded - c.state = stateFinished - break EachTLV - case tlvTypeSMP1, tlvTypeSMP2, tlvTypeSMP3, tlvTypeSMP4, tlvTypeSMPAbort, tlvTypeSMP1WithQuestion: - var reply tlv - var complete bool - reply, complete, err = c.processSMP(inTLV) - if err == smpSecretMissingError { - err = nil - change = SMPSecretNeeded - c.smp.saved = &inTLV - return - } - if err == smpFailureError { - err = nil - change = SMPFailed - } else if complete { - change = SMPComplete - } - if reply.typ != 0 { - toSend = c.encode(c.generateData(nil, &reply)) - } - break EachTLV - default: - // skip unknown TLVs - } - } - default: - err = errors.New("otr: unknown message type " + strconv.Itoa(msgType)) - } - - return -} - -// Send takes a human readable message from the local user, possibly encrypts -// it and returns zero one or more messages to send to the peer. -func (c *Conversation) Send(msg []byte) ([][]byte, error) { - switch c.state { - case statePlaintext: - return [][]byte{msg}, nil - case stateEncrypted: - return c.encode(c.generateData(msg, nil)), nil - case stateFinished: - return nil, errors.New("otr: cannot send message because secure conversation has finished") - } - - return nil, errors.New("otr: cannot send message in current state") -} - -// SMPQuestion returns the human readable challenge question from the peer. -// It's only valid after Receive has returned SMPSecretNeeded. -func (c *Conversation) SMPQuestion() string { - return c.smp.question -} - -// Authenticate begins an authentication with the peer. Authentication involves -// an optional challenge message and a shared secret. The authentication -// proceeds until either Receive returns SMPComplete, SMPSecretNeeded (which -// indicates that a new authentication is happening and thus this one was -// aborted) or SMPFailed. -func (c *Conversation) Authenticate(question string, mutualSecret []byte) (toSend [][]byte, err error) { - if c.state != stateEncrypted { - err = errors.New("otr: can't authenticate a peer without a secure conversation established") - return - } - - if c.smp.saved != nil { - c.calcSMPSecret(mutualSecret, false /* they started it */) - - var out tlv - var complete bool - out, complete, err = c.processSMP(*c.smp.saved) - if complete { - panic("SMP completed on the first message") - } - c.smp.saved = nil - if out.typ != 0 { - toSend = c.encode(c.generateData(nil, &out)) - } - return - } - - c.calcSMPSecret(mutualSecret, true /* we started it */) - outs := c.startSMP(question) - for _, out := range outs { - toSend = append(toSend, c.encode(c.generateData(nil, &out))...) - } - return -} - -// End ends a secure conversation by generating a termination message for -// the peer and switches to unencrypted communication. -func (c *Conversation) End() (toSend [][]byte) { - switch c.state { - case statePlaintext: - return nil - case stateEncrypted: - c.state = statePlaintext - return c.encode(c.generateData(nil, &tlv{typ: tlvTypeDisconnected})) - case stateFinished: - c.state = statePlaintext - return nil - } - panic("unreachable") -} - -// IsEncrypted returns true if a message passed to Send would be encrypted -// before transmission. This result remains valid until the next call to -// Receive or End, which may change the state of the Conversation. -func (c *Conversation) IsEncrypted() bool { - return c.state == stateEncrypted -} - -var fragmentError = errors.New("otr: invalid OTR fragment") - -// processFragment processes a fragmented OTR message and possibly returns a -// complete message. Fragmented messages look like "?OTR,k,n,msg," where k is -// the fragment number (starting from 1), n is the number of fragments in this -// message and msg is a substring of the base64 encoded message. -func (c *Conversation) processFragment(in []byte) (out []byte, err error) { - in = in[len(fragmentPrefix):] // remove "?OTR," - parts := bytes.Split(in, fragmentPartSeparator) - if len(parts) != 4 || len(parts[3]) != 0 { - return nil, fragmentError - } - - k, err := strconv.Atoi(string(parts[0])) - if err != nil { - return nil, fragmentError - } - - n, err := strconv.Atoi(string(parts[1])) - if err != nil { - return nil, fragmentError - } - - if k < 1 || n < 1 || k > n { - return nil, fragmentError - } - - if k == 1 { - c.frag = append(c.frag[:0], parts[2]...) - c.k, c.n = k, n - } else if n == c.n && k == c.k+1 { - c.frag = append(c.frag, parts[2]...) - c.k++ - } else { - c.frag = c.frag[:0] - c.n, c.k = 0, 0 - } - - if c.n > 0 && c.k == c.n { - c.n, c.k = 0, 0 - return c.frag, nil - } - - return nil, nil -} - -func (c *Conversation) generateDHCommit() []byte { - _, err := io.ReadFull(c.rand(), c.r[:]) - if err != nil { - panic("otr: short read from random source") - } - - var xBytes [dhPrivateBytes]byte - c.x = c.randMPI(xBytes[:]) - c.gx = new(big.Int).Exp(g, c.x, p) - c.gy = nil - c.gxBytes = appendMPI(nil, c.gx) - - h := sha256.New() - h.Write(c.gxBytes) - h.Sum(c.digest[:0]) - - aesCipher, err := aes.NewCipher(c.r[:]) - if err != nil { - panic(err.Error()) - } - - var iv [aes.BlockSize]byte - ctr := cipher.NewCTR(aesCipher, iv[:]) - ctr.XORKeyStream(c.gxBytes, c.gxBytes) - - return c.serializeDHCommit() -} - -func (c *Conversation) serializeDHCommit() []byte { - var ret []byte - ret = appendU16(ret, 2) // protocol version - ret = append(ret, msgTypeDHCommit) - ret = appendData(ret, c.gxBytes) - ret = appendData(ret, c.digest[:]) - return ret -} - -func (c *Conversation) processDHCommit(in []byte) error { - var ok1, ok2 bool - c.gxBytes, in, ok1 = getData(in) - digest, in, ok2 := getData(in) - if !ok1 || !ok2 || len(in) > 0 { - return errors.New("otr: corrupt DH commit message") - } - copy(c.digest[:], digest) - return nil -} - -func (c *Conversation) compareToDHCommit(in []byte) (int, error) { - _, in, ok1 := getData(in) - digest, in, ok2 := getData(in) - if !ok1 || !ok2 || len(in) > 0 { - return 0, errors.New("otr: corrupt DH commit message") - } - return bytes.Compare(c.digest[:], digest), nil -} - -func (c *Conversation) generateDHKey() []byte { - var yBytes [dhPrivateBytes]byte - c.y = c.randMPI(yBytes[:]) - c.gy = new(big.Int).Exp(g, c.y, p) - return c.serializeDHKey() -} - -func (c *Conversation) serializeDHKey() []byte { - var ret []byte - ret = appendU16(ret, 2) // protocol version - ret = append(ret, msgTypeDHKey) - ret = appendMPI(ret, c.gy) - return ret -} - -func (c *Conversation) processDHKey(in []byte) (isSame bool, err error) { - gy, in, ok := getMPI(in) - if !ok { - err = errors.New("otr: corrupt DH key message") - return - } - if gy.Cmp(g) < 0 || gy.Cmp(pMinus2) > 0 { - err = errors.New("otr: DH value out of range") - return - } - if c.gy != nil { - isSame = c.gy.Cmp(gy) == 0 - return - } - c.gy = gy - return -} - -func (c *Conversation) generateEncryptedSignature(keys *akeKeys, xFirst bool) ([]byte, []byte) { - var xb []byte - xb = c.PrivateKey.PublicKey.Serialize(xb) - - var verifyData []byte - if xFirst { - verifyData = appendMPI(verifyData, c.gx) - verifyData = appendMPI(verifyData, c.gy) - } else { - verifyData = appendMPI(verifyData, c.gy) - verifyData = appendMPI(verifyData, c.gx) - } - verifyData = append(verifyData, xb...) - verifyData = appendU32(verifyData, c.myKeyId) - - mac := hmac.New(sha256.New, keys.m1[:]) - mac.Write(verifyData) - mb := mac.Sum(nil) - - xb = appendU32(xb, c.myKeyId) - xb = append(xb, c.PrivateKey.Sign(c.rand(), mb)...) - - aesCipher, err := aes.NewCipher(keys.c[:]) - if err != nil { - panic(err.Error()) - } - var iv [aes.BlockSize]byte - ctr := cipher.NewCTR(aesCipher, iv[:]) - ctr.XORKeyStream(xb, xb) - - mac = hmac.New(sha256.New, keys.m2[:]) - encryptedSig := appendData(nil, xb) - mac.Write(encryptedSig) - - return encryptedSig, mac.Sum(nil) -} - -func (c *Conversation) generateRevealSig() []byte { - s := new(big.Int).Exp(c.gy, c.x, p) - c.calcAKEKeys(s) - c.myKeyId++ - - encryptedSig, mac := c.generateEncryptedSignature(&c.revealKeys, true /* gx comes first */) - - c.myCurrentDHPub = c.gx - c.myCurrentDHPriv = c.x - c.rotateDHKeys() - incCounter(&c.myCounter) - - var ret []byte - ret = appendU16(ret, 2) - ret = append(ret, msgTypeRevealSig) - ret = appendData(ret, c.r[:]) - ret = append(ret, encryptedSig...) - ret = append(ret, mac[:20]...) - return ret -} - -func (c *Conversation) processEncryptedSig(encryptedSig, theirMAC []byte, keys *akeKeys, xFirst bool) error { - mac := hmac.New(sha256.New, keys.m2[:]) - mac.Write(appendData(nil, encryptedSig)) - myMAC := mac.Sum(nil)[:20] - - if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 { - return errors.New("bad signature MAC in encrypted signature") - } - - aesCipher, err := aes.NewCipher(keys.c[:]) - if err != nil { - panic(err.Error()) - } - var iv [aes.BlockSize]byte - ctr := cipher.NewCTR(aesCipher, iv[:]) - ctr.XORKeyStream(encryptedSig, encryptedSig) - - sig := encryptedSig - sig, ok1 := c.TheirPublicKey.Parse(sig) - keyId, sig, ok2 := getU32(sig) - if !ok1 || !ok2 { - return errors.New("otr: corrupt encrypted signature") - } - - var verifyData []byte - if xFirst { - verifyData = appendMPI(verifyData, c.gx) - verifyData = appendMPI(verifyData, c.gy) - } else { - verifyData = appendMPI(verifyData, c.gy) - verifyData = appendMPI(verifyData, c.gx) - } - verifyData = c.TheirPublicKey.Serialize(verifyData) - verifyData = appendU32(verifyData, keyId) - - mac = hmac.New(sha256.New, keys.m1[:]) - mac.Write(verifyData) - mb := mac.Sum(nil) - - sig, ok1 = c.TheirPublicKey.Verify(mb, sig) - if !ok1 { - return errors.New("bad signature in encrypted signature") - } - if len(sig) > 0 { - return errors.New("corrupt encrypted signature") - } - - c.theirKeyId = keyId - zero(c.theirLastCtr[:]) - return nil -} - -func (c *Conversation) processRevealSig(in []byte) error { - r, in, ok1 := getData(in) - encryptedSig, in, ok2 := getData(in) - theirMAC := in - if !ok1 || !ok2 || len(theirMAC) != 20 { - return errors.New("otr: corrupt reveal signature message") - } - - aesCipher, err := aes.NewCipher(r) - if err != nil { - return errors.New("otr: cannot create AES cipher from reveal signature message: " + err.Error()) - } - var iv [aes.BlockSize]byte - ctr := cipher.NewCTR(aesCipher, iv[:]) - ctr.XORKeyStream(c.gxBytes, c.gxBytes) - h := sha256.New() - h.Write(c.gxBytes) - digest := h.Sum(nil) - if len(digest) != len(c.digest) || subtle.ConstantTimeCompare(digest, c.digest[:]) == 0 { - return errors.New("otr: bad commit MAC in reveal signature message") - } - var rest []byte - c.gx, rest, ok1 = getMPI(c.gxBytes) - if !ok1 || len(rest) > 0 { - return errors.New("otr: gx corrupt after decryption") - } - if c.gx.Cmp(g) < 0 || c.gx.Cmp(pMinus2) > 0 { - return errors.New("otr: DH value out of range") - } - s := new(big.Int).Exp(c.gx, c.y, p) - c.calcAKEKeys(s) - - if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.revealKeys, true /* gx comes first */); err != nil { - return errors.New("otr: in reveal signature message: " + err.Error()) - } - - c.theirCurrentDHPub = c.gx - c.theirLastDHPub = nil - - return nil -} - -func (c *Conversation) generateSig() []byte { - c.myKeyId++ - - encryptedSig, mac := c.generateEncryptedSignature(&c.sigKeys, false /* gy comes first */) - - c.myCurrentDHPub = c.gy - c.myCurrentDHPriv = c.y - c.rotateDHKeys() - incCounter(&c.myCounter) - - var ret []byte - ret = appendU16(ret, 2) - ret = append(ret, msgTypeSig) - ret = append(ret, encryptedSig...) - ret = append(ret, mac[:macPrefixBytes]...) - return ret -} - -func (c *Conversation) processSig(in []byte) error { - encryptedSig, in, ok1 := getData(in) - theirMAC := in - if !ok1 || len(theirMAC) != macPrefixBytes { - return errors.New("otr: corrupt signature message") - } - - if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.sigKeys, false /* gy comes first */); err != nil { - return errors.New("otr: in signature message: " + err.Error()) - } - - c.theirCurrentDHPub = c.gy - c.theirLastDHPub = nil - - return nil -} - -func (c *Conversation) rotateDHKeys() { - // evict slots using our retired key id - for i := range c.keySlots { - slot := &c.keySlots[i] - if slot.used && slot.myKeyId == c.myKeyId-1 { - slot.used = false - c.oldMACs = append(c.oldMACs, slot.recvMACKey...) - } - } - - c.myLastDHPriv = c.myCurrentDHPriv - c.myLastDHPub = c.myCurrentDHPub - - var xBytes [dhPrivateBytes]byte - c.myCurrentDHPriv = c.randMPI(xBytes[:]) - c.myCurrentDHPub = new(big.Int).Exp(g, c.myCurrentDHPriv, p) - c.myKeyId++ -} - -func (c *Conversation) processData(in []byte) (out []byte, tlvs []tlv, err error) { - origIn := in - flags, in, ok1 := getU8(in) - theirKeyId, in, ok2 := getU32(in) - myKeyId, in, ok3 := getU32(in) - y, in, ok4 := getMPI(in) - counter, in, ok5 := getNBytes(in, 8) - encrypted, in, ok6 := getData(in) - macedData := origIn[:len(origIn)-len(in)] - theirMAC, in, ok7 := getNBytes(in, macPrefixBytes) - _, in, ok8 := getData(in) - if !ok1 || !ok2 || !ok3 || !ok4 || !ok5 || !ok6 || !ok7 || !ok8 || len(in) > 0 { - err = errors.New("otr: corrupt data message") - return - } - - ignoreErrors := flags&1 != 0 - - slot, err := c.calcDataKeys(myKeyId, theirKeyId) - if err != nil { - if ignoreErrors { - err = nil - } - return - } - - mac := hmac.New(sha1.New, slot.recvMACKey) - mac.Write([]byte{0, 2, 3}) - mac.Write(macedData) - myMAC := mac.Sum(nil) - if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 { - if !ignoreErrors { - err = errors.New("otr: bad MAC on data message") - } - return - } - - if bytes.Compare(counter, slot.theirLastCtr[:]) <= 0 { - err = errors.New("otr: counter regressed") - return - } - copy(slot.theirLastCtr[:], counter) - - var iv [aes.BlockSize]byte - copy(iv[:], counter) - aesCipher, err := aes.NewCipher(slot.recvAESKey) - if err != nil { - panic(err.Error()) - } - ctr := cipher.NewCTR(aesCipher, iv[:]) - ctr.XORKeyStream(encrypted, encrypted) - decrypted := encrypted - - if myKeyId == c.myKeyId { - c.rotateDHKeys() - } - if theirKeyId == c.theirKeyId { - // evict slots using their retired key id - for i := range c.keySlots { - slot := &c.keySlots[i] - if slot.used && slot.theirKeyId == theirKeyId-1 { - slot.used = false - c.oldMACs = append(c.oldMACs, slot.recvMACKey...) - } - } - - c.theirLastDHPub = c.theirCurrentDHPub - c.theirKeyId++ - c.theirCurrentDHPub = y - } - - if nulPos := bytes.IndexByte(decrypted, 0); nulPos >= 0 { - out = decrypted[:nulPos] - tlvData := decrypted[nulPos+1:] - for len(tlvData) > 0 { - var t tlv - var ok1, ok2, ok3 bool - - t.typ, tlvData, ok1 = getU16(tlvData) - t.length, tlvData, ok2 = getU16(tlvData) - t.data, tlvData, ok3 = getNBytes(tlvData, int(t.length)) - if !ok1 || !ok2 || !ok3 { - err = errors.New("otr: corrupt tlv data") - return - } - tlvs = append(tlvs, t) - } - } else { - out = decrypted - } - - return -} - -func (c *Conversation) generateData(msg []byte, extra *tlv) []byte { - slot, err := c.calcDataKeys(c.myKeyId-1, c.theirKeyId) - if err != nil { - panic("otr: failed to generate sending keys: " + err.Error()) - } - - var plaintext []byte - plaintext = append(plaintext, msg...) - plaintext = append(plaintext, 0) - - padding := paddingGranularity - ((len(plaintext) + 4) % paddingGranularity) - plaintext = appendU16(plaintext, tlvTypePadding) - plaintext = appendU16(plaintext, uint16(padding)) - for i := 0; i < padding; i++ { - plaintext = append(plaintext, 0) - } - - if extra != nil { - plaintext = appendU16(plaintext, extra.typ) - plaintext = appendU16(plaintext, uint16(len(extra.data))) - plaintext = append(plaintext, extra.data...) - } - - encrypted := make([]byte, len(plaintext)) - - var iv [aes.BlockSize]byte - copy(iv[:], c.myCounter[:]) - aesCipher, err := aes.NewCipher(slot.sendAESKey) - if err != nil { - panic(err.Error()) - } - ctr := cipher.NewCTR(aesCipher, iv[:]) - ctr.XORKeyStream(encrypted, plaintext) - - var ret []byte - ret = appendU16(ret, 2) - ret = append(ret, msgTypeData) - ret = append(ret, 0 /* flags */) - ret = appendU32(ret, c.myKeyId-1) - ret = appendU32(ret, c.theirKeyId) - ret = appendMPI(ret, c.myCurrentDHPub) - ret = append(ret, c.myCounter[:]...) - ret = appendData(ret, encrypted) - - mac := hmac.New(sha1.New, slot.sendMACKey) - mac.Write(ret) - ret = append(ret, mac.Sum(nil)[:macPrefixBytes]...) - ret = appendData(ret, c.oldMACs) - c.oldMACs = nil - incCounter(&c.myCounter) - - return ret -} - -func incCounter(counter *[8]byte) { - for i := 7; i >= 0; i-- { - counter[i]++ - if counter[i] > 0 { - break - } - } -} - -// calcDataKeys computes the keys used to encrypt a data message given the key -// IDs. -func (c *Conversation) calcDataKeys(myKeyId, theirKeyId uint32) (slot *keySlot, err error) { - // Check for a cache hit. - for i := range c.keySlots { - slot = &c.keySlots[i] - if slot.used && slot.theirKeyId == theirKeyId && slot.myKeyId == myKeyId { - return - } - } - - // Find an empty slot to write into. - slot = nil - for i := range c.keySlots { - if !c.keySlots[i].used { - slot = &c.keySlots[i] - break - } - } - if slot == nil { - return nil, errors.New("otr: internal error: no more key slots") - } - - var myPriv, myPub, theirPub *big.Int - - if myKeyId == c.myKeyId { - myPriv = c.myCurrentDHPriv - myPub = c.myCurrentDHPub - } else if myKeyId == c.myKeyId-1 { - myPriv = c.myLastDHPriv - myPub = c.myLastDHPub - } else { - err = errors.New("otr: peer requested keyid " + strconv.FormatUint(uint64(myKeyId), 10) + " when I'm on " + strconv.FormatUint(uint64(c.myKeyId), 10)) - return - } - - if theirKeyId == c.theirKeyId { - theirPub = c.theirCurrentDHPub - } else if theirKeyId == c.theirKeyId-1 && c.theirLastDHPub != nil { - theirPub = c.theirLastDHPub - } else { - err = errors.New("otr: peer requested keyid " + strconv.FormatUint(uint64(myKeyId), 10) + " when they're on " + strconv.FormatUint(uint64(c.myKeyId), 10)) - return - } - - var sendPrefixByte, recvPrefixByte [1]byte - - if myPub.Cmp(theirPub) > 0 { - // we're the high end - sendPrefixByte[0], recvPrefixByte[0] = 1, 2 - } else { - // we're the low end - sendPrefixByte[0], recvPrefixByte[0] = 2, 1 - } - - s := new(big.Int).Exp(theirPub, myPriv, p) - sBytes := appendMPI(nil, s) - - h := sha1.New() - h.Write(sendPrefixByte[:]) - h.Write(sBytes) - slot.sendAESKey = h.Sum(slot.sendAESKey[:0])[:16] - - h.Reset() - h.Write(slot.sendAESKey) - slot.sendMACKey = h.Sum(slot.sendMACKey[:0]) - - h.Reset() - h.Write(recvPrefixByte[:]) - h.Write(sBytes) - slot.recvAESKey = h.Sum(slot.recvAESKey[:0])[:16] - - h.Reset() - h.Write(slot.recvAESKey) - slot.recvMACKey = h.Sum(slot.recvMACKey[:0]) - - slot.theirKeyId = theirKeyId - slot.myKeyId = myKeyId - slot.used = true - - zero(slot.theirLastCtr[:]) - return -} - -func (c *Conversation) calcAKEKeys(s *big.Int) { - mpi := appendMPI(nil, s) - h := sha256.New() - - var cBytes [32]byte - hashWithPrefix(c.SSID[:], 0, mpi, h) - - hashWithPrefix(cBytes[:], 1, mpi, h) - copy(c.revealKeys.c[:], cBytes[:16]) - copy(c.sigKeys.c[:], cBytes[16:]) - - hashWithPrefix(c.revealKeys.m1[:], 2, mpi, h) - hashWithPrefix(c.revealKeys.m2[:], 3, mpi, h) - hashWithPrefix(c.sigKeys.m1[:], 4, mpi, h) - hashWithPrefix(c.sigKeys.m2[:], 5, mpi, h) -} - -func hashWithPrefix(out []byte, prefix byte, in []byte, h hash.Hash) { - h.Reset() - var p [1]byte - p[0] = prefix - h.Write(p[:]) - h.Write(in) - if len(out) == h.Size() { - h.Sum(out[:0]) - } else { - digest := h.Sum(nil) - copy(out, digest) - } -} - -func (c *Conversation) encode(msg []byte) [][]byte { - b64 := make([]byte, base64.StdEncoding.EncodedLen(len(msg))+len(msgPrefix)+1) - base64.StdEncoding.Encode(b64[len(msgPrefix):], msg) - copy(b64, msgPrefix) - b64[len(b64)-1] = '.' - - if c.FragmentSize < minFragmentSize || len(b64) <= c.FragmentSize { - // We can encode this in a single fragment. - return [][]byte{b64} - } - - // We have to fragment this message. - var ret [][]byte - bytesPerFragment := c.FragmentSize - minFragmentSize - numFragments := (len(b64) + bytesPerFragment) / bytesPerFragment - - for i := 0; i < numFragments; i++ { - frag := []byte("?OTR," + strconv.Itoa(i+1) + "," + strconv.Itoa(numFragments) + ",") - todo := bytesPerFragment - if todo > len(b64) { - todo = len(b64) - } - frag = append(frag, b64[:todo]...) - b64 = b64[todo:] - frag = append(frag, ',') - ret = append(ret, frag) - } - - return ret -} - -func (c *Conversation) reset() { - c.myKeyId = 0 - - for i := range c.keySlots { - c.keySlots[i].used = false - } -} - -type PublicKey struct { - dsa.PublicKey -} - -func (pk *PublicKey) Parse(in []byte) ([]byte, bool) { - var ok bool - var pubKeyType uint16 - - if pubKeyType, in, ok = getU16(in); !ok || pubKeyType != 0 { - return nil, false - } - if pk.P, in, ok = getMPI(in); !ok { - return nil, false - } - if pk.Q, in, ok = getMPI(in); !ok { - return nil, false - } - if pk.G, in, ok = getMPI(in); !ok { - return nil, false - } - if pk.Y, in, ok = getMPI(in); !ok { - return nil, false - } - - return in, true -} - -func (pk *PublicKey) Serialize(in []byte) []byte { - in = appendU16(in, 0) - in = appendMPI(in, pk.P) - in = appendMPI(in, pk.Q) - in = appendMPI(in, pk.G) - in = appendMPI(in, pk.Y) - return in -} - -// Fingerprint returns the 20-byte, binary fingerprint of the PublicKey. -func (pk *PublicKey) Fingerprint() []byte { - b := pk.Serialize(nil) - h := sha1.New() - h.Write(b[2:]) - return h.Sum(nil) -} - -func (pk *PublicKey) Verify(hashed, sig []byte) ([]byte, bool) { - if len(sig) != 2*dsaSubgroupBytes { - return nil, false - } - r := new(big.Int).SetBytes(sig[:dsaSubgroupBytes]) - s := new(big.Int).SetBytes(sig[dsaSubgroupBytes:]) - ok := dsa.Verify(&pk.PublicKey, hashed, r, s) - return sig[dsaSubgroupBytes*2:], ok -} - -type PrivateKey struct { - PublicKey - dsa.PrivateKey -} - -func (priv *PrivateKey) Sign(rand io.Reader, hashed []byte) []byte { - r, s, err := dsa.Sign(rand, &priv.PrivateKey, hashed) - if err != nil { - panic(err.Error()) - } - rBytes := r.Bytes() - sBytes := s.Bytes() - if len(rBytes) > dsaSubgroupBytes || len(sBytes) > dsaSubgroupBytes { - panic("DSA signature too large") - } - - out := make([]byte, 2*dsaSubgroupBytes) - copy(out[dsaSubgroupBytes-len(rBytes):], rBytes) - copy(out[len(out)-len(sBytes):], sBytes) - return out -} - -func (priv *PrivateKey) Serialize(in []byte) []byte { - in = priv.PublicKey.Serialize(in) - in = appendMPI(in, priv.PrivateKey.X) - return in -} - -func (priv *PrivateKey) Parse(in []byte) ([]byte, bool) { - in, ok := priv.PublicKey.Parse(in) - if !ok { - return in, ok - } - priv.PrivateKey.PublicKey = priv.PublicKey.PublicKey - priv.PrivateKey.X, in, ok = getMPI(in) - return in, ok -} - -func (priv *PrivateKey) Generate(rand io.Reader) { - if err := dsa.GenerateParameters(&priv.PrivateKey.PublicKey.Parameters, rand, dsa.L1024N160); err != nil { - panic(err.Error()) - } - if err := dsa.GenerateKey(&priv.PrivateKey, rand); err != nil { - panic(err.Error()) - } - priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey -} - -func notHex(r rune) bool { - if r >= '0' && r <= '9' || - r >= 'a' && r <= 'f' || - r >= 'A' && r <= 'F' { - return false - } - - return true -} - -// Import parses the contents of a libotr private key file. -func (priv *PrivateKey) Import(in []byte) bool { - mpiStart := []byte(" #") - - mpis := make([]*big.Int, 5) - - for i := 0; i < len(mpis); i++ { - start := bytes.Index(in, mpiStart) - if start == -1 { - return false - } - in = in[start+len(mpiStart):] - end := bytes.IndexFunc(in, notHex) - if end == -1 { - return false - } - hexBytes := in[:end] - in = in[end:] - - if len(hexBytes)&1 != 0 { - return false - } - - mpiBytes := make([]byte, len(hexBytes)/2) - if _, err := hex.Decode(mpiBytes, hexBytes); err != nil { - return false - } - - mpis[i] = new(big.Int).SetBytes(mpiBytes) - } - - for _, mpi := range mpis { - if mpi.Sign() <= 0 { - return false - } - } - - priv.PrivateKey.P = mpis[0] - priv.PrivateKey.Q = mpis[1] - priv.PrivateKey.G = mpis[2] - priv.PrivateKey.Y = mpis[3] - priv.PrivateKey.X = mpis[4] - priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey - - a := new(big.Int).Exp(priv.PrivateKey.G, priv.PrivateKey.X, priv.PrivateKey.P) - return a.Cmp(priv.PrivateKey.Y) == 0 -} - -func getU8(in []byte) (uint8, []byte, bool) { - if len(in) < 1 { - return 0, in, false - } - return in[0], in[1:], true -} - -func getU16(in []byte) (uint16, []byte, bool) { - if len(in) < 2 { - return 0, in, false - } - r := uint16(in[0])<<8 | uint16(in[1]) - return r, in[2:], true -} - -func getU32(in []byte) (uint32, []byte, bool) { - if len(in) < 4 { - return 0, in, false - } - r := uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3]) - return r, in[4:], true -} - -func getMPI(in []byte) (*big.Int, []byte, bool) { - l, in, ok := getU32(in) - if !ok || uint32(len(in)) < l { - return nil, in, false - } - r := new(big.Int).SetBytes(in[:l]) - return r, in[l:], true -} - -func getData(in []byte) ([]byte, []byte, bool) { - l, in, ok := getU32(in) - if !ok || uint32(len(in)) < l { - return nil, in, false - } - return in[:l], in[l:], true -} - -func getNBytes(in []byte, n int) ([]byte, []byte, bool) { - if len(in) < n { - return nil, in, false - } - return in[:n], in[n:], true -} - -func appendU16(out []byte, v uint16) []byte { - out = append(out, byte(v>>8), byte(v)) - return out -} - -func appendU32(out []byte, v uint32) []byte { - out = append(out, byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) - return out -} - -func appendData(out, v []byte) []byte { - out = appendU32(out, uint32(len(v))) - out = append(out, v...) - return out -} - -func appendMPI(out []byte, v *big.Int) []byte { - vBytes := v.Bytes() - out = appendU32(out, uint32(len(vBytes))) - out = append(out, vBytes...) - return out -} - -func appendMPIs(out []byte, mpis ...*big.Int) []byte { - for _, mpi := range mpis { - out = appendMPI(out, mpi) - } - return out -} - -func zero(b []byte) { - for i := range b { - b[i] = 0 - } -} diff --git a/libnetwork/vendor/golang.org/x/crypto/otr/smp.go b/libnetwork/vendor/golang.org/x/crypto/otr/smp.go deleted file mode 100644 index dc6de4ee0e..0000000000 --- a/libnetwork/vendor/golang.org/x/crypto/otr/smp.go +++ /dev/null @@ -1,572 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements the Socialist Millionaires Protocol as described in -// http://www.cypherpunks.ca/otr/Protocol-v2-3.1.0.html. The protocol -// specification is required in order to understand this code and, where -// possible, the variable names in the code match up with the spec. - -package otr - -import ( - "bytes" - "crypto/sha256" - "errors" - "hash" - "math/big" -) - -type smpFailure string - -func (s smpFailure) Error() string { - return string(s) -} - -var smpFailureError = smpFailure("otr: SMP protocol failed") -var smpSecretMissingError = smpFailure("otr: mutual secret needed") - -const smpVersion = 1 - -const ( - smpState1 = iota - smpState2 - smpState3 - smpState4 -) - -type smpState struct { - state int - a2, a3, b2, b3, pb, qb *big.Int - g2a, g3a *big.Int - g2, g3 *big.Int - g3b, papb, qaqb, ra *big.Int - saved *tlv - secret *big.Int - question string -} - -func (c *Conversation) startSMP(question string) (tlvs []tlv) { - if c.smp.state != smpState1 { - tlvs = append(tlvs, c.generateSMPAbort()) - } - tlvs = append(tlvs, c.generateSMP1(question)) - c.smp.question = "" - c.smp.state = smpState2 - return -} - -func (c *Conversation) resetSMP() { - c.smp.state = smpState1 - c.smp.secret = nil - c.smp.question = "" -} - -func (c *Conversation) processSMP(in tlv) (out tlv, complete bool, err error) { - data := in.data - - switch in.typ { - case tlvTypeSMPAbort: - if c.smp.state != smpState1 { - err = smpFailureError - } - c.resetSMP() - return - case tlvTypeSMP1WithQuestion: - // We preprocess this into a SMP1 message. - nulPos := bytes.IndexByte(data, 0) - if nulPos == -1 { - err = errors.New("otr: SMP message with question didn't contain a NUL byte") - return - } - c.smp.question = string(data[:nulPos]) - data = data[nulPos+1:] - } - - numMPIs, data, ok := getU32(data) - if !ok || numMPIs > 20 { - err = errors.New("otr: corrupt SMP message") - return - } - - mpis := make([]*big.Int, numMPIs) - for i := range mpis { - var ok bool - mpis[i], data, ok = getMPI(data) - if !ok { - err = errors.New("otr: corrupt SMP message") - return - } - } - - switch in.typ { - case tlvTypeSMP1, tlvTypeSMP1WithQuestion: - if c.smp.state != smpState1 { - c.resetSMP() - out = c.generateSMPAbort() - return - } - if c.smp.secret == nil { - err = smpSecretMissingError - return - } - if err = c.processSMP1(mpis); err != nil { - return - } - c.smp.state = smpState3 - out = c.generateSMP2() - case tlvTypeSMP2: - if c.smp.state != smpState2 { - c.resetSMP() - out = c.generateSMPAbort() - return - } - if out, err = c.processSMP2(mpis); err != nil { - out = c.generateSMPAbort() - return - } - c.smp.state = smpState4 - case tlvTypeSMP3: - if c.smp.state != smpState3 { - c.resetSMP() - out = c.generateSMPAbort() - return - } - if out, err = c.processSMP3(mpis); err != nil { - return - } - c.smp.state = smpState1 - c.smp.secret = nil - complete = true - case tlvTypeSMP4: - if c.smp.state != smpState4 { - c.resetSMP() - out = c.generateSMPAbort() - return - } - if err = c.processSMP4(mpis); err != nil { - out = c.generateSMPAbort() - return - } - c.smp.state = smpState1 - c.smp.secret = nil - complete = true - default: - panic("unknown SMP message") - } - - return -} - -func (c *Conversation) calcSMPSecret(mutualSecret []byte, weStarted bool) { - h := sha256.New() - h.Write([]byte{smpVersion}) - if weStarted { - h.Write(c.PrivateKey.PublicKey.Fingerprint()) - h.Write(c.TheirPublicKey.Fingerprint()) - } else { - h.Write(c.TheirPublicKey.Fingerprint()) - h.Write(c.PrivateKey.PublicKey.Fingerprint()) - } - h.Write(c.SSID[:]) - h.Write(mutualSecret) - c.smp.secret = new(big.Int).SetBytes(h.Sum(nil)) -} - -func (c *Conversation) generateSMP1(question string) tlv { - var randBuf [16]byte - c.smp.a2 = c.randMPI(randBuf[:]) - c.smp.a3 = c.randMPI(randBuf[:]) - g2a := new(big.Int).Exp(g, c.smp.a2, p) - g3a := new(big.Int).Exp(g, c.smp.a3, p) - h := sha256.New() - - r2 := c.randMPI(randBuf[:]) - r := new(big.Int).Exp(g, r2, p) - c2 := new(big.Int).SetBytes(hashMPIs(h, 1, r)) - d2 := new(big.Int).Mul(c.smp.a2, c2) - d2.Sub(r2, d2) - d2.Mod(d2, q) - if d2.Sign() < 0 { - d2.Add(d2, q) - } - - r3 := c.randMPI(randBuf[:]) - r.Exp(g, r3, p) - c3 := new(big.Int).SetBytes(hashMPIs(h, 2, r)) - d3 := new(big.Int).Mul(c.smp.a3, c3) - d3.Sub(r3, d3) - d3.Mod(d3, q) - if d3.Sign() < 0 { - d3.Add(d3, q) - } - - var ret tlv - if len(question) > 0 { - ret.typ = tlvTypeSMP1WithQuestion - ret.data = append(ret.data, question...) - ret.data = append(ret.data, 0) - } else { - ret.typ = tlvTypeSMP1 - } - ret.data = appendU32(ret.data, 6) - ret.data = appendMPIs(ret.data, g2a, c2, d2, g3a, c3, d3) - return ret -} - -func (c *Conversation) processSMP1(mpis []*big.Int) error { - if len(mpis) != 6 { - return errors.New("otr: incorrect number of arguments in SMP1 message") - } - g2a := mpis[0] - c2 := mpis[1] - d2 := mpis[2] - g3a := mpis[3] - c3 := mpis[4] - d3 := mpis[5] - h := sha256.New() - - r := new(big.Int).Exp(g, d2, p) - s := new(big.Int).Exp(g2a, c2, p) - r.Mul(r, s) - r.Mod(r, p) - t := new(big.Int).SetBytes(hashMPIs(h, 1, r)) - if c2.Cmp(t) != 0 { - return errors.New("otr: ZKP c2 incorrect in SMP1 message") - } - r.Exp(g, d3, p) - s.Exp(g3a, c3, p) - r.Mul(r, s) - r.Mod(r, p) - t.SetBytes(hashMPIs(h, 2, r)) - if c3.Cmp(t) != 0 { - return errors.New("otr: ZKP c3 incorrect in SMP1 message") - } - - c.smp.g2a = g2a - c.smp.g3a = g3a - return nil -} - -func (c *Conversation) generateSMP2() tlv { - var randBuf [16]byte - b2 := c.randMPI(randBuf[:]) - c.smp.b3 = c.randMPI(randBuf[:]) - r2 := c.randMPI(randBuf[:]) - r3 := c.randMPI(randBuf[:]) - r4 := c.randMPI(randBuf[:]) - r5 := c.randMPI(randBuf[:]) - r6 := c.randMPI(randBuf[:]) - - g2b := new(big.Int).Exp(g, b2, p) - g3b := new(big.Int).Exp(g, c.smp.b3, p) - - r := new(big.Int).Exp(g, r2, p) - h := sha256.New() - c2 := new(big.Int).SetBytes(hashMPIs(h, 3, r)) - d2 := new(big.Int).Mul(b2, c2) - d2.Sub(r2, d2) - d2.Mod(d2, q) - if d2.Sign() < 0 { - d2.Add(d2, q) - } - - r.Exp(g, r3, p) - c3 := new(big.Int).SetBytes(hashMPIs(h, 4, r)) - d3 := new(big.Int).Mul(c.smp.b3, c3) - d3.Sub(r3, d3) - d3.Mod(d3, q) - if d3.Sign() < 0 { - d3.Add(d3, q) - } - - c.smp.g2 = new(big.Int).Exp(c.smp.g2a, b2, p) - c.smp.g3 = new(big.Int).Exp(c.smp.g3a, c.smp.b3, p) - c.smp.pb = new(big.Int).Exp(c.smp.g3, r4, p) - c.smp.qb = new(big.Int).Exp(g, r4, p) - r.Exp(c.smp.g2, c.smp.secret, p) - c.smp.qb.Mul(c.smp.qb, r) - c.smp.qb.Mod(c.smp.qb, p) - - s := new(big.Int) - s.Exp(c.smp.g2, r6, p) - r.Exp(g, r5, p) - s.Mul(r, s) - s.Mod(s, p) - r.Exp(c.smp.g3, r5, p) - cp := new(big.Int).SetBytes(hashMPIs(h, 5, r, s)) - - // D5 = r5 - r4 cP mod q and D6 = r6 - y cP mod q - - s.Mul(r4, cp) - r.Sub(r5, s) - d5 := new(big.Int).Mod(r, q) - if d5.Sign() < 0 { - d5.Add(d5, q) - } - - s.Mul(c.smp.secret, cp) - r.Sub(r6, s) - d6 := new(big.Int).Mod(r, q) - if d6.Sign() < 0 { - d6.Add(d6, q) - } - - var ret tlv - ret.typ = tlvTypeSMP2 - ret.data = appendU32(ret.data, 11) - ret.data = appendMPIs(ret.data, g2b, c2, d2, g3b, c3, d3, c.smp.pb, c.smp.qb, cp, d5, d6) - return ret -} - -func (c *Conversation) processSMP2(mpis []*big.Int) (out tlv, err error) { - if len(mpis) != 11 { - err = errors.New("otr: incorrect number of arguments in SMP2 message") - return - } - g2b := mpis[0] - c2 := mpis[1] - d2 := mpis[2] - g3b := mpis[3] - c3 := mpis[4] - d3 := mpis[5] - pb := mpis[6] - qb := mpis[7] - cp := mpis[8] - d5 := mpis[9] - d6 := mpis[10] - h := sha256.New() - - r := new(big.Int).Exp(g, d2, p) - s := new(big.Int).Exp(g2b, c2, p) - r.Mul(r, s) - r.Mod(r, p) - s.SetBytes(hashMPIs(h, 3, r)) - if c2.Cmp(s) != 0 { - err = errors.New("otr: ZKP c2 failed in SMP2 message") - return - } - - r.Exp(g, d3, p) - s.Exp(g3b, c3, p) - r.Mul(r, s) - r.Mod(r, p) - s.SetBytes(hashMPIs(h, 4, r)) - if c3.Cmp(s) != 0 { - err = errors.New("otr: ZKP c3 failed in SMP2 message") - return - } - - c.smp.g2 = new(big.Int).Exp(g2b, c.smp.a2, p) - c.smp.g3 = new(big.Int).Exp(g3b, c.smp.a3, p) - - r.Exp(g, d5, p) - s.Exp(c.smp.g2, d6, p) - r.Mul(r, s) - s.Exp(qb, cp, p) - r.Mul(r, s) - r.Mod(r, p) - - s.Exp(c.smp.g3, d5, p) - t := new(big.Int).Exp(pb, cp, p) - s.Mul(s, t) - s.Mod(s, p) - t.SetBytes(hashMPIs(h, 5, s, r)) - if cp.Cmp(t) != 0 { - err = errors.New("otr: ZKP cP failed in SMP2 message") - return - } - - var randBuf [16]byte - r4 := c.randMPI(randBuf[:]) - r5 := c.randMPI(randBuf[:]) - r6 := c.randMPI(randBuf[:]) - r7 := c.randMPI(randBuf[:]) - - pa := new(big.Int).Exp(c.smp.g3, r4, p) - r.Exp(c.smp.g2, c.smp.secret, p) - qa := new(big.Int).Exp(g, r4, p) - qa.Mul(qa, r) - qa.Mod(qa, p) - - r.Exp(g, r5, p) - s.Exp(c.smp.g2, r6, p) - r.Mul(r, s) - r.Mod(r, p) - - s.Exp(c.smp.g3, r5, p) - cp.SetBytes(hashMPIs(h, 6, s, r)) - - r.Mul(r4, cp) - d5 = new(big.Int).Sub(r5, r) - d5.Mod(d5, q) - if d5.Sign() < 0 { - d5.Add(d5, q) - } - - r.Mul(c.smp.secret, cp) - d6 = new(big.Int).Sub(r6, r) - d6.Mod(d6, q) - if d6.Sign() < 0 { - d6.Add(d6, q) - } - - r.ModInverse(qb, p) - qaqb := new(big.Int).Mul(qa, r) - qaqb.Mod(qaqb, p) - - ra := new(big.Int).Exp(qaqb, c.smp.a3, p) - r.Exp(qaqb, r7, p) - s.Exp(g, r7, p) - cr := new(big.Int).SetBytes(hashMPIs(h, 7, s, r)) - - r.Mul(c.smp.a3, cr) - d7 := new(big.Int).Sub(r7, r) - d7.Mod(d7, q) - if d7.Sign() < 0 { - d7.Add(d7, q) - } - - c.smp.g3b = g3b - c.smp.qaqb = qaqb - - r.ModInverse(pb, p) - c.smp.papb = new(big.Int).Mul(pa, r) - c.smp.papb.Mod(c.smp.papb, p) - c.smp.ra = ra - - out.typ = tlvTypeSMP3 - out.data = appendU32(out.data, 8) - out.data = appendMPIs(out.data, pa, qa, cp, d5, d6, ra, cr, d7) - return -} - -func (c *Conversation) processSMP3(mpis []*big.Int) (out tlv, err error) { - if len(mpis) != 8 { - err = errors.New("otr: incorrect number of arguments in SMP3 message") - return - } - pa := mpis[0] - qa := mpis[1] - cp := mpis[2] - d5 := mpis[3] - d6 := mpis[4] - ra := mpis[5] - cr := mpis[6] - d7 := mpis[7] - h := sha256.New() - - r := new(big.Int).Exp(g, d5, p) - s := new(big.Int).Exp(c.smp.g2, d6, p) - r.Mul(r, s) - s.Exp(qa, cp, p) - r.Mul(r, s) - r.Mod(r, p) - - s.Exp(c.smp.g3, d5, p) - t := new(big.Int).Exp(pa, cp, p) - s.Mul(s, t) - s.Mod(s, p) - t.SetBytes(hashMPIs(h, 6, s, r)) - if t.Cmp(cp) != 0 { - err = errors.New("otr: ZKP cP failed in SMP3 message") - return - } - - r.ModInverse(c.smp.qb, p) - qaqb := new(big.Int).Mul(qa, r) - qaqb.Mod(qaqb, p) - - r.Exp(qaqb, d7, p) - s.Exp(ra, cr, p) - r.Mul(r, s) - r.Mod(r, p) - - s.Exp(g, d7, p) - t.Exp(c.smp.g3a, cr, p) - s.Mul(s, t) - s.Mod(s, p) - t.SetBytes(hashMPIs(h, 7, s, r)) - if t.Cmp(cr) != 0 { - err = errors.New("otr: ZKP cR failed in SMP3 message") - return - } - - var randBuf [16]byte - r7 := c.randMPI(randBuf[:]) - rb := new(big.Int).Exp(qaqb, c.smp.b3, p) - - r.Exp(qaqb, r7, p) - s.Exp(g, r7, p) - cr = new(big.Int).SetBytes(hashMPIs(h, 8, s, r)) - - r.Mul(c.smp.b3, cr) - d7 = new(big.Int).Sub(r7, r) - d7.Mod(d7, q) - if d7.Sign() < 0 { - d7.Add(d7, q) - } - - out.typ = tlvTypeSMP4 - out.data = appendU32(out.data, 3) - out.data = appendMPIs(out.data, rb, cr, d7) - - r.ModInverse(c.smp.pb, p) - r.Mul(pa, r) - r.Mod(r, p) - s.Exp(ra, c.smp.b3, p) - if r.Cmp(s) != 0 { - err = smpFailureError - } - - return -} - -func (c *Conversation) processSMP4(mpis []*big.Int) error { - if len(mpis) != 3 { - return errors.New("otr: incorrect number of arguments in SMP4 message") - } - rb := mpis[0] - cr := mpis[1] - d7 := mpis[2] - h := sha256.New() - - r := new(big.Int).Exp(c.smp.qaqb, d7, p) - s := new(big.Int).Exp(rb, cr, p) - r.Mul(r, s) - r.Mod(r, p) - - s.Exp(g, d7, p) - t := new(big.Int).Exp(c.smp.g3b, cr, p) - s.Mul(s, t) - s.Mod(s, p) - t.SetBytes(hashMPIs(h, 8, s, r)) - if t.Cmp(cr) != 0 { - return errors.New("otr: ZKP cR failed in SMP4 message") - } - - r.Exp(rb, c.smp.a3, p) - if r.Cmp(c.smp.papb) != 0 { - return smpFailureError - } - - return nil -} - -func (c *Conversation) generateSMPAbort() tlv { - return tlv{typ: tlvTypeSMPAbort} -} - -func hashMPIs(h hash.Hash, magic byte, mpis ...*big.Int) []byte { - if h != nil { - h.Reset() - } else { - h = sha256.New() - } - - h.Write([]byte{magic}) - for _, mpi := range mpis { - h.Write(appendMPI(nil, mpi)) - } - return h.Sum(nil) -} diff --git a/libnetwork/vendor/golang.org/x/crypto/ssh/test/doc.go b/libnetwork/vendor/golang.org/x/crypto/ssh/test/doc.go deleted file mode 100644 index 198f0ca1e2..0000000000 --- a/libnetwork/vendor/golang.org/x/crypto/ssh/test/doc.go +++ /dev/null @@ -1,7 +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 test contains integration tests for the -// golang.org/x/crypto/ssh package. -package test // import "golang.org/x/crypto/ssh/test" diff --git a/libnetwork/vendor/golang.org/x/crypto/ssh/test/sshd_test_pw.c b/libnetwork/vendor/golang.org/x/crypto/ssh/test/sshd_test_pw.c deleted file mode 100644 index 2794a563a4..0000000000 --- a/libnetwork/vendor/golang.org/x/crypto/ssh/test/sshd_test_pw.c +++ /dev/null @@ -1,173 +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. - -// sshd_test_pw.c -// Wrapper to inject test password data for sshd PAM authentication -// -// This wrapper implements custom versions of getpwnam, getpwnam_r, -// getspnam and getspnam_r. These functions first call their real -// libc versions, then check if the requested user matches test user -// specified in env variable TEST_USER and if so replace the password -// with crypted() value of TEST_PASSWD env variable. -// -// Compile: -// gcc -Wall -shared -o sshd_test_pw.so -fPIC sshd_test_pw.c -// -// Compile with debug: -// gcc -DVERBOSE -Wall -shared -o sshd_test_pw.so -fPIC sshd_test_pw.c -// -// Run sshd: -// LD_PRELOAD="sshd_test_pw.so" TEST_USER="..." TEST_PASSWD="..." sshd ... - -// +build ignore - -#define _GNU_SOURCE -#include -#include -#include -#include -#include -#include -#include - -#ifdef VERBOSE -#define DEBUG(X...) fprintf(stderr, X) -#else -#define DEBUG(X...) while (0) { } -#endif - -/* crypt() password */ -static char * -pwhash(char *passwd) { - return strdup(crypt(passwd, "$6$")); -} - -/* Pointers to real functions in libc */ -static struct passwd * (*real_getpwnam)(const char *) = NULL; -static int (*real_getpwnam_r)(const char *, struct passwd *, char *, size_t, struct passwd **) = NULL; -static struct spwd * (*real_getspnam)(const char *) = NULL; -static int (*real_getspnam_r)(const char *, struct spwd *, char *, size_t, struct spwd **) = NULL; - -/* Cached test user and test password */ -static char *test_user = NULL; -static char *test_passwd_hash = NULL; - -static void -init(void) { - /* Fetch real libc function pointers */ - real_getpwnam = dlsym(RTLD_NEXT, "getpwnam"); - real_getpwnam_r = dlsym(RTLD_NEXT, "getpwnam_r"); - real_getspnam = dlsym(RTLD_NEXT, "getspnam"); - real_getspnam_r = dlsym(RTLD_NEXT, "getspnam_r"); - - /* abort if env variables are not defined */ - if (getenv("TEST_USER") == NULL || getenv("TEST_PASSWD") == NULL) { - fprintf(stderr, "env variables TEST_USER and TEST_PASSWD are missing\n"); - abort(); - } - - /* Fetch test user and test password from env */ - test_user = strdup(getenv("TEST_USER")); - test_passwd_hash = pwhash(getenv("TEST_PASSWD")); - - DEBUG("sshd_test_pw init():\n"); - DEBUG("\treal_getpwnam: %p\n", real_getpwnam); - DEBUG("\treal_getpwnam_r: %p\n", real_getpwnam_r); - DEBUG("\treal_getspnam: %p\n", real_getspnam); - DEBUG("\treal_getspnam_r: %p\n", real_getspnam_r); - DEBUG("\tTEST_USER: '%s'\n", test_user); - DEBUG("\tTEST_PASSWD: '%s'\n", getenv("TEST_PASSWD")); - DEBUG("\tTEST_PASSWD_HASH: '%s'\n", test_passwd_hash); -} - -static int -is_test_user(const char *name) { - if (test_user != NULL && strcmp(test_user, name) == 0) - return 1; - return 0; -} - -/* getpwnam */ - -struct passwd * -getpwnam(const char *name) { - struct passwd *pw; - - DEBUG("sshd_test_pw getpwnam(%s)\n", name); - - if (real_getpwnam == NULL) - init(); - if ((pw = real_getpwnam(name)) == NULL) - return NULL; - - if (is_test_user(name)) - pw->pw_passwd = strdup(test_passwd_hash); - - return pw; -} - -/* getpwnam_r */ - -int -getpwnam_r(const char *name, - struct passwd *pwd, - char *buf, - size_t buflen, - struct passwd **result) { - int r; - - DEBUG("sshd_test_pw getpwnam_r(%s)\n", name); - - if (real_getpwnam_r == NULL) - init(); - if ((r = real_getpwnam_r(name, pwd, buf, buflen, result)) != 0 || *result == NULL) - return r; - - if (is_test_user(name)) - pwd->pw_passwd = strdup(test_passwd_hash); - - return 0; -} - -/* getspnam */ - -struct spwd * -getspnam(const char *name) { - struct spwd *sp; - - DEBUG("sshd_test_pw getspnam(%s)\n", name); - - if (real_getspnam == NULL) - init(); - if ((sp = real_getspnam(name)) == NULL) - return NULL; - - if (is_test_user(name)) - sp->sp_pwdp = strdup(test_passwd_hash); - - return sp; -} - -/* getspnam_r */ - -int -getspnam_r(const char *name, - struct spwd *spbuf, - char *buf, - size_t buflen, - struct spwd **spbufp) { - int r; - - DEBUG("sshd_test_pw getspnam_r(%s)\n", name); - - if (real_getspnam_r == NULL) - init(); - if ((r = real_getspnam_r(name, spbuf, buf, buflen, spbufp)) != 0) - return r; - - if (is_test_user(name)) - spbuf->sp_pwdp = strdup(test_passwd_hash); - - return r; -} diff --git a/libnetwork/vendor/golang.org/x/net/internal/socket/sys_linux_386.s b/libnetwork/vendor/golang.org/x/net/internal/socket/sys_linux_386.s new file mode 100644 index 0000000000..93e7d75ec0 --- /dev/null +++ b/libnetwork/vendor/golang.org/x/net/internal/socket/sys_linux_386.s @@ -0,0 +1,11 @@ +// 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. + +#include "textflag.h" + +TEXT ·socketcall(SB),NOSPLIT,$0-36 + JMP syscall·socketcall(SB) + +TEXT ·rawsocketcall(SB),NOSPLIT,$0-36 + JMP syscall·rawsocketcall(SB) diff --git a/libnetwork/vendor/golang.org/x/sys/windows/svc/event.go b/libnetwork/vendor/golang.org/x/sys/windows/svc/event.go deleted file mode 100644 index 0508e22881..0000000000 --- a/libnetwork/vendor/golang.org/x/sys/windows/svc/event.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package svc - -import ( - "errors" - - "golang.org/x/sys/windows" -) - -// event represents auto-reset, initially non-signaled Windows event. -// It is used to communicate between go and asm parts of this package. -type event struct { - h windows.Handle -} - -func newEvent() (*event, error) { - h, err := windows.CreateEvent(nil, 0, 0, nil) - if err != nil { - return nil, err - } - return &event{h: h}, nil -} - -func (e *event) Close() error { - return windows.CloseHandle(e.h) -} - -func (e *event) Set() error { - return windows.SetEvent(e.h) -} - -func (e *event) Wait() error { - s, err := windows.WaitForSingleObject(e.h, windows.INFINITE) - switch s { - case windows.WAIT_OBJECT_0: - break - case windows.WAIT_FAILED: - return err - default: - return errors.New("unexpected result from WaitForSingleObject") - } - return nil -} diff --git a/libnetwork/vendor/golang.org/x/sys/windows/svc/go12.c b/libnetwork/vendor/golang.org/x/sys/windows/svc/go12.c deleted file mode 100644 index 6f1be1fa3b..0000000000 --- a/libnetwork/vendor/golang.org/x/sys/windows/svc/go12.c +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows -// +build !go1.3 - -// copied from pkg/runtime -typedef unsigned int uint32; -typedef unsigned long long int uint64; -#ifdef _64BIT -typedef uint64 uintptr; -#else -typedef uint32 uintptr; -#endif - -// from sys_386.s or sys_amd64.s -void ·servicemain(void); - -void -·getServiceMain(uintptr *r) -{ - *r = (uintptr)·servicemain; -} diff --git a/libnetwork/vendor/golang.org/x/sys/windows/svc/go12.go b/libnetwork/vendor/golang.org/x/sys/windows/svc/go12.go deleted file mode 100644 index 6f0a924eaf..0000000000 --- a/libnetwork/vendor/golang.org/x/sys/windows/svc/go12.go +++ /dev/null @@ -1,11 +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 windows -// +build !go1.3 - -package svc - -// from go12.c -func getServiceMain(r *uintptr) diff --git a/libnetwork/vendor/golang.org/x/sys/windows/svc/go13.go b/libnetwork/vendor/golang.org/x/sys/windows/svc/go13.go deleted file mode 100644 index 432a9e796a..0000000000 --- a/libnetwork/vendor/golang.org/x/sys/windows/svc/go13.go +++ /dev/null @@ -1,31 +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 windows -// +build go1.3 - -package svc - -import "unsafe" - -const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const - -// Should be a built-in for unsafe.Pointer? -func add(p unsafe.Pointer, x uintptr) unsafe.Pointer { - return unsafe.Pointer(uintptr(p) + x) -} - -// funcPC returns the entry PC of the function f. -// It assumes that f is a func value. Otherwise the behavior is undefined. -func funcPC(f interface{}) uintptr { - return **(**uintptr)(add(unsafe.Pointer(&f), ptrSize)) -} - -// from sys_386.s and sys_amd64.s -func servicectlhandler(ctl uint32) uintptr -func servicemain(argc uint32, argv **uint16) - -func getServiceMain(r *uintptr) { - *r = funcPC(servicemain) -} diff --git a/libnetwork/vendor/golang.org/x/sys/windows/svc/security.go b/libnetwork/vendor/golang.org/x/sys/windows/svc/security.go deleted file mode 100644 index 6fbc9236ed..0000000000 --- a/libnetwork/vendor/golang.org/x/sys/windows/svc/security.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package svc - -import ( - "unsafe" - - "golang.org/x/sys/windows" -) - -func allocSid(subAuth0 uint32) (*windows.SID, error) { - var sid *windows.SID - err := windows.AllocateAndInitializeSid(&windows.SECURITY_NT_AUTHORITY, - 1, subAuth0, 0, 0, 0, 0, 0, 0, 0, &sid) - if err != nil { - return nil, err - } - return sid, nil -} - -// IsAnInteractiveSession determines if calling process is running interactively. -// It queries the process token for membership in the Interactive group. -// http://stackoverflow.com/questions/2668851/how-do-i-detect-that-my-application-is-running-as-service-or-in-an-interactive-s -func IsAnInteractiveSession() (bool, error) { - interSid, err := allocSid(windows.SECURITY_INTERACTIVE_RID) - if err != nil { - return false, err - } - defer windows.FreeSid(interSid) - - serviceSid, err := allocSid(windows.SECURITY_SERVICE_RID) - if err != nil { - return false, err - } - defer windows.FreeSid(serviceSid) - - t, err := windows.OpenCurrentProcessToken() - if err != nil { - return false, err - } - defer t.Close() - - gs, err := t.GetTokenGroups() - if err != nil { - return false, err - } - p := unsafe.Pointer(&gs.Groups[0]) - groups := (*[2 << 20]windows.SIDAndAttributes)(p)[:gs.GroupCount] - for _, g := range groups { - if windows.EqualSid(g.Sid, interSid) { - return true, nil - } - if windows.EqualSid(g.Sid, serviceSid) { - return false, nil - } - } - return false, nil -} diff --git a/libnetwork/vendor/golang.org/x/sys/windows/svc/service.go b/libnetwork/vendor/golang.org/x/sys/windows/svc/service.go deleted file mode 100644 index 903cba3f12..0000000000 --- a/libnetwork/vendor/golang.org/x/sys/windows/svc/service.go +++ /dev/null @@ -1,363 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// Package svc provides everything required to build Windows service. -// -package svc - -import ( - "errors" - "runtime" - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -// State describes service execution state (Stopped, Running and so on). -type State uint32 - -const ( - Stopped = State(windows.SERVICE_STOPPED) - StartPending = State(windows.SERVICE_START_PENDING) - StopPending = State(windows.SERVICE_STOP_PENDING) - Running = State(windows.SERVICE_RUNNING) - ContinuePending = State(windows.SERVICE_CONTINUE_PENDING) - PausePending = State(windows.SERVICE_PAUSE_PENDING) - Paused = State(windows.SERVICE_PAUSED) -) - -// Cmd represents service state change request. It is sent to a service -// by the service manager, and should be actioned upon by the service. -type Cmd uint32 - -const ( - Stop = Cmd(windows.SERVICE_CONTROL_STOP) - Pause = Cmd(windows.SERVICE_CONTROL_PAUSE) - Continue = Cmd(windows.SERVICE_CONTROL_CONTINUE) - Interrogate = Cmd(windows.SERVICE_CONTROL_INTERROGATE) - Shutdown = Cmd(windows.SERVICE_CONTROL_SHUTDOWN) - ParamChange = Cmd(windows.SERVICE_CONTROL_PARAMCHANGE) - NetBindAdd = Cmd(windows.SERVICE_CONTROL_NETBINDADD) - NetBindRemove = Cmd(windows.SERVICE_CONTROL_NETBINDREMOVE) - NetBindEnable = Cmd(windows.SERVICE_CONTROL_NETBINDENABLE) - NetBindDisable = Cmd(windows.SERVICE_CONTROL_NETBINDDISABLE) - DeviceEvent = Cmd(windows.SERVICE_CONTROL_DEVICEEVENT) - HardwareProfileChange = Cmd(windows.SERVICE_CONTROL_HARDWAREPROFILECHANGE) - PowerEvent = Cmd(windows.SERVICE_CONTROL_POWEREVENT) - SessionChange = Cmd(windows.SERVICE_CONTROL_SESSIONCHANGE) -) - -// Accepted is used to describe commands accepted by the service. -// Note that Interrogate is always accepted. -type Accepted uint32 - -const ( - AcceptStop = Accepted(windows.SERVICE_ACCEPT_STOP) - AcceptShutdown = Accepted(windows.SERVICE_ACCEPT_SHUTDOWN) - AcceptPauseAndContinue = Accepted(windows.SERVICE_ACCEPT_PAUSE_CONTINUE) - AcceptParamChange = Accepted(windows.SERVICE_ACCEPT_PARAMCHANGE) - AcceptNetBindChange = Accepted(windows.SERVICE_ACCEPT_NETBINDCHANGE) - AcceptHardwareProfileChange = Accepted(windows.SERVICE_ACCEPT_HARDWAREPROFILECHANGE) - AcceptPowerEvent = Accepted(windows.SERVICE_ACCEPT_POWEREVENT) - AcceptSessionChange = Accepted(windows.SERVICE_ACCEPT_SESSIONCHANGE) -) - -// Status combines State and Accepted commands to fully describe running service. -type Status struct { - State State - Accepts Accepted - CheckPoint uint32 // used to report progress during a lengthy operation - WaitHint uint32 // estimated time required for a pending operation, in milliseconds -} - -// ChangeRequest is sent to the service Handler to request service status change. -type ChangeRequest struct { - Cmd Cmd - EventType uint32 - EventData uintptr - CurrentStatus Status -} - -// Handler is the interface that must be implemented to build Windows service. -type Handler interface { - - // Execute will be called by the package code at the start of - // the service, and the service will exit once Execute completes. - // Inside Execute you must read service change requests from r and - // act accordingly. You must keep service control manager up to date - // about state of your service by writing into s as required. - // args contains service name followed by argument strings passed - // to the service. - // You can provide service exit code in exitCode return parameter, - // with 0 being "no error". You can also indicate if exit code, - // if any, is service specific or not by using svcSpecificEC - // parameter. - Execute(args []string, r <-chan ChangeRequest, s chan<- Status) (svcSpecificEC bool, exitCode uint32) -} - -var ( - // These are used by asm code. - goWaitsH uintptr - cWaitsH uintptr - ssHandle uintptr - sName *uint16 - sArgc uintptr - sArgv **uint16 - ctlHandlerExProc uintptr - cSetEvent uintptr - cWaitForSingleObject uintptr - cRegisterServiceCtrlHandlerExW uintptr -) - -func init() { - k := syscall.MustLoadDLL("kernel32.dll") - cSetEvent = k.MustFindProc("SetEvent").Addr() - cWaitForSingleObject = k.MustFindProc("WaitForSingleObject").Addr() - a := syscall.MustLoadDLL("advapi32.dll") - cRegisterServiceCtrlHandlerExW = a.MustFindProc("RegisterServiceCtrlHandlerExW").Addr() -} - -// The HandlerEx prototype also has a context pointer but since we don't use -// it at start-up time we don't have to pass it over either. -type ctlEvent struct { - cmd Cmd - eventType uint32 - eventData uintptr - errno uint32 -} - -// service provides access to windows service api. -type service struct { - name string - h windows.Handle - cWaits *event - goWaits *event - c chan ctlEvent - handler Handler -} - -func newService(name string, handler Handler) (*service, error) { - var s service - var err error - s.name = name - s.c = make(chan ctlEvent) - s.handler = handler - s.cWaits, err = newEvent() - if err != nil { - return nil, err - } - s.goWaits, err = newEvent() - if err != nil { - s.cWaits.Close() - return nil, err - } - return &s, nil -} - -func (s *service) close() error { - s.cWaits.Close() - s.goWaits.Close() - return nil -} - -type exitCode struct { - isSvcSpecific bool - errno uint32 -} - -func (s *service) updateStatus(status *Status, ec *exitCode) error { - if s.h == 0 { - return errors.New("updateStatus with no service status handle") - } - var t windows.SERVICE_STATUS - t.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS - t.CurrentState = uint32(status.State) - if status.Accepts&AcceptStop != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_STOP - } - if status.Accepts&AcceptShutdown != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_SHUTDOWN - } - if status.Accepts&AcceptPauseAndContinue != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_PAUSE_CONTINUE - } - if status.Accepts&AcceptParamChange != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_PARAMCHANGE - } - if status.Accepts&AcceptNetBindChange != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_NETBINDCHANGE - } - if status.Accepts&AcceptHardwareProfileChange != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_HARDWAREPROFILECHANGE - } - if status.Accepts&AcceptPowerEvent != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_POWEREVENT - } - if status.Accepts&AcceptSessionChange != 0 { - t.ControlsAccepted |= windows.SERVICE_ACCEPT_SESSIONCHANGE - } - if ec.errno == 0 { - t.Win32ExitCode = windows.NO_ERROR - t.ServiceSpecificExitCode = windows.NO_ERROR - } else if ec.isSvcSpecific { - t.Win32ExitCode = uint32(windows.ERROR_SERVICE_SPECIFIC_ERROR) - t.ServiceSpecificExitCode = ec.errno - } else { - t.Win32ExitCode = ec.errno - t.ServiceSpecificExitCode = windows.NO_ERROR - } - t.CheckPoint = status.CheckPoint - t.WaitHint = status.WaitHint - return windows.SetServiceStatus(s.h, &t) -} - -const ( - sysErrSetServiceStatusFailed = uint32(syscall.APPLICATION_ERROR) + iota - sysErrNewThreadInCallback -) - -func (s *service) run() { - s.goWaits.Wait() - s.h = windows.Handle(ssHandle) - argv := (*[100]*int16)(unsafe.Pointer(sArgv))[:sArgc] - args := make([]string, len(argv)) - for i, a := range argv { - args[i] = syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(a))[:]) - } - - cmdsToHandler := make(chan ChangeRequest) - changesFromHandler := make(chan Status) - exitFromHandler := make(chan exitCode) - - go func() { - ss, errno := s.handler.Execute(args, cmdsToHandler, changesFromHandler) - exitFromHandler <- exitCode{ss, errno} - }() - - status := Status{State: Stopped} - ec := exitCode{isSvcSpecific: true, errno: 0} - var outch chan ChangeRequest - inch := s.c - var cmd Cmd - var evtype uint32 - var evdata uintptr -loop: - for { - select { - case r := <-inch: - if r.errno != 0 { - ec.errno = r.errno - break loop - } - inch = nil - outch = cmdsToHandler - cmd = r.cmd - evtype = r.eventType - evdata = r.eventData - case outch <- ChangeRequest{cmd, evtype, evdata, status}: - inch = s.c - outch = nil - case c := <-changesFromHandler: - err := s.updateStatus(&c, &ec) - if err != nil { - // best suitable error number - ec.errno = sysErrSetServiceStatusFailed - if err2, ok := err.(syscall.Errno); ok { - ec.errno = uint32(err2) - } - break loop - } - status = c - case ec = <-exitFromHandler: - break loop - } - } - - s.updateStatus(&Status{State: Stopped}, &ec) - s.cWaits.Set() -} - -func newCallback(fn interface{}) (cb uintptr, err error) { - defer func() { - r := recover() - if r == nil { - return - } - cb = 0 - switch v := r.(type) { - case string: - err = errors.New(v) - case error: - err = v - default: - err = errors.New("unexpected panic in syscall.NewCallback") - } - }() - return syscall.NewCallback(fn), nil -} - -// BUG(brainman): There is no mechanism to run multiple services -// inside one single executable. Perhaps, it can be overcome by -// using RegisterServiceCtrlHandlerEx Windows api. - -// Run executes service name by calling appropriate handler function. -func Run(name string, handler Handler) error { - runtime.LockOSThread() - - tid := windows.GetCurrentThreadId() - - s, err := newService(name, handler) - if err != nil { - return err - } - - ctlHandler := func(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr { - e := ctlEvent{cmd: Cmd(ctl), eventType: evtype, eventData: evdata} - // We assume that this callback function is running on - // the same thread as Run. Nowhere in MS documentation - // I could find statement to guarantee that. So putting - // check here to verify, otherwise things will go bad - // quickly, if ignored. - i := windows.GetCurrentThreadId() - if i != tid { - e.errno = sysErrNewThreadInCallback - } - s.c <- e - // Always return NO_ERROR (0) for now. - return 0 - } - - var svcmain uintptr - getServiceMain(&svcmain) - t := []windows.SERVICE_TABLE_ENTRY{ - {syscall.StringToUTF16Ptr(s.name), svcmain}, - {nil, 0}, - } - - goWaitsH = uintptr(s.goWaits.h) - cWaitsH = uintptr(s.cWaits.h) - sName = t[0].ServiceName - ctlHandlerExProc, err = newCallback(ctlHandler) - if err != nil { - return err - } - - go s.run() - - err = windows.StartServiceCtrlDispatcher(&t[0]) - if err != nil { - return err - } - return nil -} - -// StatusHandle returns service status handle. It is safe to call this function -// from inside the Handler.Execute because then it is guaranteed to be set. -// This code will have to change once multiple services are possible per process. -func StatusHandle() windows.Handle { - return windows.Handle(ssHandle) -} diff --git a/libnetwork/vendor/golang.org/x/sys/windows/svc/sys_386.s b/libnetwork/vendor/golang.org/x/sys/windows/svc/sys_386.s deleted file mode 100644 index 2c82a9d91d..0000000000 --- a/libnetwork/vendor/golang.org/x/sys/windows/svc/sys_386.s +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// func servicemain(argc uint32, argv **uint16) -TEXT ·servicemain(SB),7,$0 - MOVL argc+0(FP), AX - MOVL AX, ·sArgc(SB) - MOVL argv+4(FP), AX - MOVL AX, ·sArgv(SB) - - PUSHL BP - PUSHL BX - PUSHL SI - PUSHL DI - - SUBL $12, SP - - MOVL ·sName(SB), AX - MOVL AX, (SP) - MOVL $·servicectlhandler(SB), AX - MOVL AX, 4(SP) - MOVL $0, 8(SP) - MOVL ·cRegisterServiceCtrlHandlerExW(SB), AX - MOVL SP, BP - CALL AX - MOVL BP, SP - CMPL AX, $0 - JE exit - MOVL AX, ·ssHandle(SB) - - MOVL ·goWaitsH(SB), AX - MOVL AX, (SP) - MOVL ·cSetEvent(SB), AX - MOVL SP, BP - CALL AX - MOVL BP, SP - - MOVL ·cWaitsH(SB), AX - MOVL AX, (SP) - MOVL $-1, AX - MOVL AX, 4(SP) - MOVL ·cWaitForSingleObject(SB), AX - MOVL SP, BP - CALL AX - MOVL BP, SP - -exit: - ADDL $12, SP - - POPL DI - POPL SI - POPL BX - POPL BP - - MOVL 0(SP), CX - ADDL $12, SP - JMP CX - -// I do not know why, but this seems to be the only way to call -// ctlHandlerProc on Windows 7. - -// func servicectlhandler(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr { -TEXT ·servicectlhandler(SB),7,$0 - MOVL ·ctlHandlerExProc(SB), CX - JMP CX diff --git a/libnetwork/vendor/golang.org/x/sys/windows/svc/sys_amd64.s b/libnetwork/vendor/golang.org/x/sys/windows/svc/sys_amd64.s deleted file mode 100644 index 06b425900d..0000000000 --- a/libnetwork/vendor/golang.org/x/sys/windows/svc/sys_amd64.s +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -// func servicemain(argc uint32, argv **uint16) -TEXT ·servicemain(SB),7,$0 - MOVL CX, ·sArgc(SB) - MOVL DX, ·sArgv(SB) - - SUBQ $32, SP // stack for the first 4 syscall params - - MOVQ ·sName(SB), CX - MOVQ $·servicectlhandler(SB), DX - // BUG(pastarmovj): Figure out a way to pass in context in R8. - MOVQ ·cRegisterServiceCtrlHandlerExW(SB), AX - CALL AX - CMPQ AX, $0 - JE exit - MOVQ AX, ·ssHandle(SB) - - MOVQ ·goWaitsH(SB), CX - MOVQ ·cSetEvent(SB), AX - CALL AX - - MOVQ ·cWaitsH(SB), CX - MOVQ $4294967295, DX - MOVQ ·cWaitForSingleObject(SB), AX - CALL AX - -exit: - ADDQ $32, SP - RET - -// I do not know why, but this seems to be the only way to call -// ctlHandlerProc on Windows 7. - -// func ·servicectlhandler(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr { -TEXT ·servicectlhandler(SB),7,$0 - MOVQ ·ctlHandlerExProc(SB), AX - JMP AX