mirror of https://github.com/knative/func.git
Improvements for podman on Windows and macOS (#1230)
* fix: pack docker socket mounting with npipe Signed-off-by: Matej Vasek <mvasek@redhat.com> * feat: trust ssh connection by podman machine Signed-off-by: Matej Vasek <mvasek@redhat.com> * fix: socket mount on macOS with podman machine The `podman machine start` outputs recipe for DOCKER_HOST setting, following the recipe it was causing troubles, since path in host OS and in the podman VM is different. Signed-off-by: Matej Vasek <mvasek@redhat.com> * chore: use go-winio library for handling npipes Replacing unmaintained an buggy library. Signed-off-by: Matej Vasek <mvasek@redhat.com> * test: added test for podman machine auto connect Signed-off-by: Matej Vasek <mvasek@redhat.com> Signed-off-by: Matej Vasek <mvasek@redhat.com>
This commit is contained in:
parent
b9e3d243bc
commit
1f5a95a4a7
|
@ -17,8 +17,9 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/docker/docker/client"
|
||||
"golang.org/x/crypto/ssh"
|
||||
|
||||
"knative.dev/kn-plugin-func/ssh"
|
||||
fnssh "knative.dev/kn-plugin-func/ssh"
|
||||
)
|
||||
|
||||
var ErrNoDocker = errors.New("docker/podman API not available")
|
||||
|
@ -36,6 +37,7 @@ func NewClient(defaultHost string) (dockerClient client.CommonAPIClient, dockerH
|
|||
|
||||
dockerHost := os.Getenv("DOCKER_HOST")
|
||||
dockerHostSSHIdentity := os.Getenv("DOCKER_HOST_SSH_IDENTITY")
|
||||
hostKeyCallback := fnssh.NewHostKeyCbk()
|
||||
|
||||
if dockerHost == "" {
|
||||
_url, err = url.Parse(defaultHost)
|
||||
|
@ -59,6 +61,9 @@ func NewClient(defaultHost string) (dockerClient client.CommonAPIClient, dockerH
|
|||
dh, dhid := tryGetPodmanRemoteConn()
|
||||
if dh != "" {
|
||||
dockerHost, dockerHostSSHIdentity = dh, dhid
|
||||
hostKeyCallback = func(hostPort string, pubKey ssh.PublicKey) error {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -73,28 +78,36 @@ func NewClient(defaultHost string) (dockerClient client.CommonAPIClient, dockerH
|
|||
_url, err = url.Parse(dockerHost)
|
||||
isSSH := err == nil && _url.Scheme == "ssh"
|
||||
isTCP := err == nil && _url.Scheme == "tcp"
|
||||
isNPipe := err == nil && _url.Scheme == "npipe"
|
||||
isUnix := err == nil && _url.Scheme == "unix"
|
||||
|
||||
if isTCP {
|
||||
// With TCP, it's difficult to determine how to expose the daemon socket to lifecycle containers,
|
||||
if isTCP || isNPipe {
|
||||
// With TCP or npipe, it's difficult to determine how to expose the daemon socket to lifecycle containers,
|
||||
// so we are defaulting to standard docker location by returning empty string.
|
||||
// This should work well most of the time.
|
||||
dockerHostInRemote = ""
|
||||
}
|
||||
|
||||
if isUnix && runtime.GOOS == "darwin" {
|
||||
// A unix socket on macOS is most likely tunneled from VM,
|
||||
// so it cannot be mounted under that path.
|
||||
dockerHostInRemote = ""
|
||||
}
|
||||
|
||||
if !isSSH {
|
||||
dockerClient, err = client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation(), client.WithHost(dockerHost))
|
||||
dockerClient = &closeGuardingClient{pimpl: dockerClient}
|
||||
return
|
||||
}
|
||||
|
||||
credentialsConfig := ssh.Config{
|
||||
credentialsConfig := fnssh.Config{
|
||||
Identity: dockerHostSSHIdentity,
|
||||
PassPhrase: os.Getenv("DOCKER_HOST_SSH_IDENTITY_PASSPHRASE"),
|
||||
PasswordCallback: ssh.NewPasswordCbk(),
|
||||
PassPhraseCallback: ssh.NewPassPhraseCbk(),
|
||||
HostKeyCallback: ssh.NewHostKeyCbk(),
|
||||
PasswordCallback: fnssh.NewPasswordCbk(),
|
||||
PassPhraseCallback: fnssh.NewPassPhraseCbk(),
|
||||
HostKeyCallback: hostKeyCallback,
|
||||
}
|
||||
contextDialer, dockerHostInRemote, err := ssh.NewDialContext(_url, credentialsConfig)
|
||||
contextDialer, dockerHostInRemote, err := fnssh.NewDialContext(_url, credentialsConfig)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
|
|
@ -20,11 +20,14 @@ func TestNewDockerClientWithAutomaticPodmanSuccess(t *testing.T) {
|
|||
defer WithExecutable(t, "podman", mockPodmanSrc)()
|
||||
defer WithEnvVar(t, "DOCKER_HOST", "")()
|
||||
|
||||
dockerClient, _, err := docker.NewClient("unix:///var/run/nonexistent.sock")
|
||||
dockerClient, dockerHostToMount, err := docker.NewClient("unix:///var/run/nonexistent.sock")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer dockerClient.Close()
|
||||
if !strings.Contains(dockerHostToMount, "func-podman") {
|
||||
t.Error("got bad socket to mount")
|
||||
}
|
||||
|
||||
_, err = dockerClient.Ping(ctx)
|
||||
if err != nil {
|
||||
|
|
|
@ -0,0 +1,100 @@
|
|||
//go:build !linux
|
||||
// +build !linux
|
||||
|
||||
package docker_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
|
||||
"knative.dev/kn-plugin-func/docker"
|
||||
. "knative.dev/kn-plugin-func/testing"
|
||||
)
|
||||
|
||||
func TestNewDockerClientWithPodmanMachine(t *testing.T) {
|
||||
defer withCleanHome(t)()
|
||||
|
||||
publicKey, privateKeyPath := prepareKeys(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*1)
|
||||
defer cancel()
|
||||
|
||||
sshConf, stopSSH := startSSH(t, publicKey)
|
||||
defer stopSSH()
|
||||
_ = sshConf
|
||||
|
||||
uri := fmt.Sprintf("ssh://user@%s%s", sshConf.address, sshDockerSocket)
|
||||
out := fmt.Sprintf(`[{"Name":"podman-machine-default","URI":%q,"Identity":%q,"Default":true}]`, uri, privateKeyPath)
|
||||
|
||||
goSrc := fmt.Sprintf("package main; import \"fmt\"; func main() { fmt.Println(%q); }", out)
|
||||
|
||||
defer WithEnvVar(t, "DOCKER_HOST", "")()
|
||||
defer WithExecutable(t, "podman", goSrc)()
|
||||
|
||||
dockerClient, dockerHostInRemote, err := docker.NewClient("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer dockerClient.Close()
|
||||
|
||||
_ = dockerHostInRemote
|
||||
if dockerHostInRemote != `unix://`+sshDockerSocket {
|
||||
t.Errorf("bad remote DOCKER_HOST: expected %q but got %q", `unix://`+sshDockerSocket, dockerHostInRemote)
|
||||
}
|
||||
|
||||
_, err = dockerClient.Ping(ctx)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func prepareKeys(t *testing.T) (publicKey ssh.PublicKey, privateKeyPath string) {
|
||||
var err error
|
||||
|
||||
pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
publicKey, err = ssh.NewPublicKey(&pk.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
bs, err := x509.MarshalECPrivateKey(pk)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
blk := pem.Block{
|
||||
Type: "EC PRIVATE KEY",
|
||||
Headers: nil,
|
||||
Bytes: bs,
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
privateKeyPath = filepath.Join(tmpDir, "id")
|
||||
|
||||
f, err := os.OpenFile(privateKeyPath, os.O_CREATE|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
err = pem.Encode(f, &blk)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
package docker_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
|
@ -63,7 +64,7 @@ type sshConfig struct {
|
|||
}
|
||||
|
||||
// emulates remote machine with docker unix socket at "/some/path/docker.sock"
|
||||
func startSSH(t *testing.T) (settings sshConfig, stopSSH func()) {
|
||||
func startSSH(t *testing.T, authorizedKeys ...ssh.PublicKey) (settings sshConfig, stopSSH func()) {
|
||||
var err error
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
@ -77,6 +78,14 @@ func startSSH(t *testing.T) (settings sshConfig, stopSSH func()) {
|
|||
}
|
||||
return &ssh.Permissions{}, nil
|
||||
},
|
||||
PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
|
||||
for _, authKey := range authorizedKeys {
|
||||
if bytes.Equal(authKey.Marshal(), key.Marshal()) {
|
||||
return &ssh.Permissions{}, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("unknown public key")
|
||||
},
|
||||
}
|
||||
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
|
|
|
@ -29,17 +29,25 @@ func TestNewClient(t *testing.T) {
|
|||
|
||||
tmpDir := t.TempDir()
|
||||
sock := filepath.Join(tmpDir, "docker.sock")
|
||||
dockerHost := fmt.Sprintf("unix://%s", sock)
|
||||
|
||||
defer startMockDaemon(t, sock)()
|
||||
defer startMockDaemonUnix(t, sock)()
|
||||
|
||||
defer WithEnvVar(t, "DOCKER_HOST", fmt.Sprintf("unix://%s", sock))()
|
||||
defer WithEnvVar(t, "DOCKER_HOST", dockerHost)()
|
||||
|
||||
dockerClient, _, err := docker.NewClient(client.DefaultDockerHost)
|
||||
dockerClient, dockerHostInRemote, err := docker.NewClient(client.DefaultDockerHost)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer dockerClient.Close()
|
||||
|
||||
if runtime.GOOS == "linux" && dockerHostInRemote != dockerHost {
|
||||
t.Errorf("unexpected dockerHostInRemote: expected %q, but got %q", dockerHost, dockerHostInRemote)
|
||||
}
|
||||
if runtime.GOOS == "darwin" && dockerHostInRemote != "" {
|
||||
t.Errorf("unexpected dockerHostInRemote: expected empty string, but got %q", dockerHostInRemote)
|
||||
}
|
||||
|
||||
_, err = dockerClient.Ping(ctx)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
|
@ -50,17 +58,17 @@ func TestNewClient_DockerHost(t *testing.T) {
|
|||
tests := []struct {
|
||||
name string
|
||||
dockerHostEnvVar string
|
||||
expectedRemoteDockerHost string
|
||||
expectedRemoteDockerHost map[string]string
|
||||
}{
|
||||
{
|
||||
name: "tcp",
|
||||
dockerHostEnvVar: "tcp://10.0.0.1:1234",
|
||||
expectedRemoteDockerHost: "",
|
||||
expectedRemoteDockerHost: map[string]string{"darwin": "", "windows": "", "linux": ""},
|
||||
},
|
||||
{
|
||||
name: "unix",
|
||||
dockerHostEnvVar: "unix:///some/path/docker.sock",
|
||||
expectedRemoteDockerHost: "unix:///some/path/docker.sock",
|
||||
expectedRemoteDockerHost: map[string]string{"darwin": "", "windows": "", "linux": "unix:///some/path/docker.sock"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
|
@ -74,21 +82,17 @@ func TestNewClient_DockerHost(t *testing.T) {
|
|||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if host != tt.expectedRemoteDockerHost {
|
||||
t.Errorf("expected docker host %q, but got %q", tt.expectedRemoteDockerHost, host)
|
||||
expectedRemoteDockerHost := tt.expectedRemoteDockerHost[runtime.GOOS]
|
||||
if host != expectedRemoteDockerHost {
|
||||
t.Errorf("expected docker host %q, but got %q", expectedRemoteDockerHost, host)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func startMockDaemon(t *testing.T, sock string) func() {
|
||||
|
||||
func startMockDaemon(t *testing.T, listener net.Listener) func() {
|
||||
server := http.Server{}
|
||||
listener, err := net.Listen("unix", sock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// mimics /_ping endpoint
|
||||
server.Handler = http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.Header().Add("Content-Type", "text/plain")
|
||||
|
@ -111,3 +115,11 @@ func startMockDaemon(t *testing.T, sock string) func() {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func startMockDaemonUnix(t *testing.T, sock string) func() {
|
||||
l, err := net.Listen("unix", sock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return startMockDaemon(t, l)
|
||||
}
|
||||
|
|
|
@ -0,0 +1,48 @@
|
|||
package docker_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
winio "github.com/Microsoft/go-winio"
|
||||
"github.com/docker/docker/client"
|
||||
"knative.dev/kn-plugin-func/docker"
|
||||
|
||||
. "knative.dev/kn-plugin-func/testing"
|
||||
)
|
||||
|
||||
func TestNewClientWinPipe(t *testing.T) {
|
||||
|
||||
const testNPipe = "test-npipe"
|
||||
|
||||
defer startMockDaemonWinPipe(t, testNPipe)()
|
||||
defer WithEnvVar(t, "DOCKER_HOST", fmt.Sprintf("npipe:////./pipe/%s", testNPipe))()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*1)
|
||||
defer cancel()
|
||||
|
||||
dockerClient, dockerHostToMount, err := docker.NewClient(client.DefaultDockerHost)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer dockerClient.Close()
|
||||
|
||||
if dockerHostToMount != "" {
|
||||
t.Error("dockerHostToMount should be empty for npipe")
|
||||
}
|
||||
|
||||
_, err = dockerClient.Ping(ctx)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func startMockDaemonWinPipe(t *testing.T, pipeName string) func() {
|
||||
p, err := winio.ListenPipe(`\\.\pipe\`+pipeName, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return startMockDaemon(t, p)
|
||||
}
|
3
go.mod
3
go.mod
|
@ -5,6 +5,7 @@ go 1.17
|
|||
require (
|
||||
github.com/AlecAivazis/survey/v2 v2.3.2
|
||||
github.com/Masterminds/semver v1.5.0
|
||||
github.com/Microsoft/go-winio v0.5.2
|
||||
github.com/Netflix/go-expect v0.0.0-20210722184520-ef0bf57d82b3
|
||||
github.com/alecthomas/jsonschema v0.0.0-20210526225647-edb03dcab7bc
|
||||
github.com/buildpacks/pack v0.24.0
|
||||
|
@ -37,7 +38,6 @@ require (
|
|||
github.com/whilp/git-urls v1.0.0
|
||||
golang.org/x/crypto v0.0.0-20220214200702-86341886e292
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211
|
||||
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
k8s.io/api v0.23.5
|
||||
k8s.io/apimachinery v0.23.5
|
||||
|
@ -62,7 +62,6 @@ require (
|
|||
github.com/Azure/go-autorest/logger v0.2.1 // indirect
|
||||
github.com/Azure/go-autorest/tracing v0.6.0 // indirect
|
||||
github.com/BurntSushi/toml v1.0.0 // indirect
|
||||
github.com/Microsoft/go-winio v0.5.2 // indirect
|
||||
github.com/Microsoft/hcsshim v0.9.3 // indirect
|
||||
github.com/ProtonMail/go-crypto v0.0.0-20211112122917-428f8eabeeb3 // indirect
|
||||
github.com/PuerkitoBio/purell v1.1.1 // indirect
|
||||
|
|
1
go.sum
1
go.sum
|
@ -3706,7 +3706,6 @@ gopkg.in/jcmturner/gokrb5.v7 v7.2.3/go.mod h1:l8VISx+WGYp+Fp7KRbsiUuXTTOnxIc3Tuv
|
|||
gopkg.in/jcmturner/gokrb5.v7 v7.3.0/go.mod h1:l8VISx+WGYp+Fp7KRbsiUuXTTOnxIc3Tuvyavf11/WM=
|
||||
gopkg.in/jcmturner/rpc.v1 v1.1.0/go.mod h1:YIdkC4XfD6GXbzje11McwsDuOlZQSb9W4vfLvuNnlv8=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
|
||||
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU=
|
||||
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c=
|
||||
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
|
||||
gopkg.in/square/go-jose.v2 v2.2.2/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI=
|
||||
|
|
|
@ -4,12 +4,12 @@ import (
|
|||
"net"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/natefinch/npipe.v2"
|
||||
"github.com/Microsoft/go-winio"
|
||||
)
|
||||
|
||||
func dialSSHAgentConnection(sock string) (agentConn net.Conn, error error) {
|
||||
if strings.Contains(sock, "\\pipe\\") {
|
||||
agentConn, error = npipe.Dial(sock)
|
||||
agentConn, error = winio.DialPipe(sock, nil)
|
||||
} else {
|
||||
agentConn, error = net.Dial("unix", sock)
|
||||
}
|
||||
|
|
|
@ -1,22 +0,0 @@
|
|||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
|
@ -1,8 +0,0 @@
|
|||
The MIT License (MIT)
|
||||
Copyright (c) 2013 npipe authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -1,308 +0,0 @@
|
|||
npipe [](https://ci.appveyor.com/project/natefinch/npipe) [](https://godoc.org/gopkg.in/natefinch/npipe.v2)
|
||||
=====
|
||||
Package npipe provides a pure Go wrapper around Windows named pipes.
|
||||
|
||||
Windows named pipe documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365780
|
||||
|
||||
Note that the code lives at https://github.com/natefinch/npipe (v2 branch)
|
||||
but should be imported as gopkg.in/natefinch/npipe.v2 (the package name is
|
||||
still npipe).
|
||||
|
||||
npipe provides an interface based on stdlib's net package, with Dial, Listen,
|
||||
and Accept functions, as well as associated implementations of net.Conn and
|
||||
net.Listener. It supports rpc over the connection.
|
||||
|
||||
### Notes
|
||||
* Deadlines for reading/writing to the connection are only functional in Windows Vista/Server 2008 and above, due to limitations with the Windows API.
|
||||
|
||||
* The pipes support byte mode only (no support for message mode)
|
||||
|
||||
### Examples
|
||||
The Dial function connects a client to a named pipe:
|
||||
|
||||
|
||||
conn, err := npipe.Dial(`\\.\pipe\mypipename`)
|
||||
if err != nil {
|
||||
<handle error>
|
||||
}
|
||||
fmt.Fprintf(conn, "Hi server!\n")
|
||||
msg, err := bufio.NewReader(conn).ReadString('\n')
|
||||
...
|
||||
|
||||
The Listen function creates servers:
|
||||
|
||||
|
||||
ln, err := npipe.Listen(`\\.\pipe\mypipename`)
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
// handle error
|
||||
continue
|
||||
}
|
||||
go handleConnection(conn)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Variables
|
||||
``` go
|
||||
var ErrClosed = PipeError{"Pipe has been closed.", false}
|
||||
```
|
||||
ErrClosed is the error returned by PipeListener.Accept when Close is called
|
||||
on the PipeListener.
|
||||
|
||||
|
||||
|
||||
## type PipeAddr
|
||||
``` go
|
||||
type PipeAddr string
|
||||
```
|
||||
PipeAddr represents the address of a named pipe.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
### func (PipeAddr) Network
|
||||
``` go
|
||||
func (a PipeAddr) Network() string
|
||||
```
|
||||
Network returns the address's network name, "pipe".
|
||||
|
||||
|
||||
|
||||
### func (PipeAddr) String
|
||||
``` go
|
||||
func (a PipeAddr) String() string
|
||||
```
|
||||
String returns the address of the pipe
|
||||
|
||||
|
||||
|
||||
## type PipeConn
|
||||
``` go
|
||||
type PipeConn struct {
|
||||
// contains filtered or unexported fields
|
||||
}
|
||||
```
|
||||
PipeConn is the implementation of the net.Conn interface for named pipe connections.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
### func Dial
|
||||
``` go
|
||||
func Dial(address string) (*PipeConn, error)
|
||||
```
|
||||
Dial connects to a named pipe with the given address. If the specified pipe is not available,
|
||||
it will wait indefinitely for the pipe to become available.
|
||||
|
||||
The address must be of the form \\.\\pipe\<name> for local pipes and \\<computer>\pipe\<name>
|
||||
for remote pipes.
|
||||
|
||||
Dial will return a PipeError if you pass in a badly formatted pipe name.
|
||||
|
||||
Examples:
|
||||
|
||||
|
||||
// local pipe
|
||||
conn, err := Dial(`\\.\pipe\mypipename`)
|
||||
|
||||
// remote pipe
|
||||
conn, err := Dial(`\\othercomp\pipe\mypipename`)
|
||||
|
||||
|
||||
### func DialTimeout
|
||||
``` go
|
||||
func DialTimeout(address string, timeout time.Duration) (*PipeConn, error)
|
||||
```
|
||||
DialTimeout acts like Dial, but will time out after the duration of timeout
|
||||
|
||||
|
||||
|
||||
|
||||
### func (\*PipeConn) Close
|
||||
``` go
|
||||
func (c *PipeConn) Close() error
|
||||
```
|
||||
Close closes the connection.
|
||||
|
||||
|
||||
|
||||
### func (\*PipeConn) LocalAddr
|
||||
``` go
|
||||
func (c *PipeConn) LocalAddr() net.Addr
|
||||
```
|
||||
LocalAddr returns the local network address.
|
||||
|
||||
|
||||
|
||||
### func (\*PipeConn) Read
|
||||
``` go
|
||||
func (c *PipeConn) Read(b []byte) (int, error)
|
||||
```
|
||||
Read implements the net.Conn Read method.
|
||||
|
||||
|
||||
|
||||
### func (\*PipeConn) RemoteAddr
|
||||
``` go
|
||||
func (c *PipeConn) RemoteAddr() net.Addr
|
||||
```
|
||||
RemoteAddr returns the remote network address.
|
||||
|
||||
|
||||
|
||||
### func (\*PipeConn) SetDeadline
|
||||
``` go
|
||||
func (c *PipeConn) SetDeadline(t time.Time) error
|
||||
```
|
||||
SetDeadline implements the net.Conn SetDeadline method.
|
||||
Note that timeouts are only supported on Windows Vista/Server 2008 and above
|
||||
|
||||
|
||||
|
||||
### func (\*PipeConn) SetReadDeadline
|
||||
``` go
|
||||
func (c *PipeConn) SetReadDeadline(t time.Time) error
|
||||
```
|
||||
SetReadDeadline implements the net.Conn SetReadDeadline method.
|
||||
Note that timeouts are only supported on Windows Vista/Server 2008 and above
|
||||
|
||||
|
||||
|
||||
### func (\*PipeConn) SetWriteDeadline
|
||||
``` go
|
||||
func (c *PipeConn) SetWriteDeadline(t time.Time) error
|
||||
```
|
||||
SetWriteDeadline implements the net.Conn SetWriteDeadline method.
|
||||
Note that timeouts are only supported on Windows Vista/Server 2008 and above
|
||||
|
||||
|
||||
|
||||
### func (\*PipeConn) Write
|
||||
``` go
|
||||
func (c *PipeConn) Write(b []byte) (int, error)
|
||||
```
|
||||
Write implements the net.Conn Write method.
|
||||
|
||||
|
||||
|
||||
## type PipeError
|
||||
``` go
|
||||
type PipeError struct {
|
||||
// contains filtered or unexported fields
|
||||
}
|
||||
```
|
||||
PipeError is an error related to a call to a pipe
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
### func (PipeError) Error
|
||||
``` go
|
||||
func (e PipeError) Error() string
|
||||
```
|
||||
Error implements the error interface
|
||||
|
||||
|
||||
|
||||
### func (PipeError) Temporary
|
||||
``` go
|
||||
func (e PipeError) Temporary() bool
|
||||
```
|
||||
Temporary implements net.AddrError.Temporary()
|
||||
|
||||
|
||||
|
||||
### func (PipeError) Timeout
|
||||
``` go
|
||||
func (e PipeError) Timeout() bool
|
||||
```
|
||||
Timeout implements net.AddrError.Timeout()
|
||||
|
||||
|
||||
|
||||
## type PipeListener
|
||||
``` go
|
||||
type PipeListener struct {
|
||||
// contains filtered or unexported fields
|
||||
}
|
||||
```
|
||||
PipeListener is a named pipe listener. Clients should typically
|
||||
use variables of type net.Listener instead of assuming named pipe.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
### func Listen
|
||||
``` go
|
||||
func Listen(address string) (*PipeListener, error)
|
||||
```
|
||||
Listen returns a new PipeListener that will listen on a pipe with the given
|
||||
address. The address must be of the form \\.\pipe\<name>
|
||||
|
||||
Listen will return a PipeError for an incorrectly formatted pipe name.
|
||||
|
||||
|
||||
|
||||
|
||||
### func (\*PipeListener) Accept
|
||||
``` go
|
||||
func (l *PipeListener) Accept() (net.Conn, error)
|
||||
```
|
||||
Accept implements the Accept method in the net.Listener interface; it
|
||||
waits for the next call and returns a generic net.Conn.
|
||||
|
||||
|
||||
|
||||
### func (\*PipeListener) AcceptPipe
|
||||
``` go
|
||||
func (l *PipeListener) AcceptPipe() (*PipeConn, error)
|
||||
```
|
||||
AcceptPipe accepts the next incoming call and returns the new connection.
|
||||
|
||||
|
||||
|
||||
### func (\*PipeListener) Addr
|
||||
``` go
|
||||
func (l *PipeListener) Addr() net.Addr
|
||||
```
|
||||
Addr returns the listener's network address, a PipeAddr.
|
||||
|
||||
|
||||
|
||||
### func (\*PipeListener) Close
|
||||
``` go
|
||||
func (l *PipeListener) Close() error
|
||||
```
|
||||
Close stops listening on the address.
|
||||
Already Accepted connections are not closed.
|
|
@ -1,50 +0,0 @@
|
|||
// Copyright 2013 Nate Finch. All rights reserved.
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package npipe provides a pure Go wrapper around Windows named pipes.
|
||||
//
|
||||
// !! Note, this package is Windows-only. There is no code to compile on linux.
|
||||
//
|
||||
// Windows named pipe documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365780
|
||||
//
|
||||
// Note that the code lives at https://github.com/natefinch/npipe (v2 branch)
|
||||
// but should be imported as gopkg.in/natefinch/npipe.v2 (the package name is
|
||||
// still npipe).
|
||||
//
|
||||
// npipe provides an interface based on stdlib's net package, with Dial, Listen,
|
||||
// and Accept functions, as well as associated implementations of net.Conn and
|
||||
// net.Listener. It supports rpc over the connection.
|
||||
//
|
||||
// Notes
|
||||
//
|
||||
// * Deadlines for reading/writing to the connection are only functional in Windows Vista/Server 2008 and above, due to limitations with the Windows API.
|
||||
//
|
||||
// * The pipes support byte mode only (no support for message mode)
|
||||
//
|
||||
// Examples
|
||||
//
|
||||
// The Dial function connects a client to a named pipe:
|
||||
// conn, err := npipe.Dial(`\\.\pipe\mypipename`)
|
||||
// if err != nil {
|
||||
// <handle error>
|
||||
// }
|
||||
// fmt.Fprintf(conn, "Hi server!\n")
|
||||
// msg, err := bufio.NewReader(conn).ReadString('\n')
|
||||
// ...
|
||||
//
|
||||
// The Listen function creates servers:
|
||||
//
|
||||
// ln, err := npipe.Listen(`\\.\pipe\mypipename`)
|
||||
// if err != nil {
|
||||
// // handle error
|
||||
// }
|
||||
// for {
|
||||
// conn, err := ln.Accept()
|
||||
// if err != nil {
|
||||
// // handle error
|
||||
// continue
|
||||
// }
|
||||
// go handleConnection(conn)
|
||||
// }
|
||||
package npipe
|
|
@ -1,531 +0,0 @@
|
|||
package npipe
|
||||
|
||||
//sys createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW
|
||||
//sys connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) = ConnectNamedPipe
|
||||
//sys disconnectNamedPipe(handle syscall.Handle) (err error) = DisconnectNamedPipe
|
||||
//sys waitNamedPipe(name *uint16, timeout uint32) (err error) = WaitNamedPipeW
|
||||
//sys createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateEventW
|
||||
//sys getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) = GetOverlappedResult
|
||||
//sys cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) = CancelIoEx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// openMode
|
||||
pipe_access_duplex = 0x3
|
||||
pipe_access_inbound = 0x1
|
||||
pipe_access_outbound = 0x2
|
||||
|
||||
// openMode write flags
|
||||
file_flag_first_pipe_instance = 0x00080000
|
||||
file_flag_write_through = 0x80000000
|
||||
file_flag_overlapped = 0x40000000
|
||||
|
||||
// openMode ACL flags
|
||||
write_dac = 0x00040000
|
||||
write_owner = 0x00080000
|
||||
access_system_security = 0x01000000
|
||||
|
||||
// pipeMode
|
||||
pipe_type_byte = 0x0
|
||||
pipe_type_message = 0x4
|
||||
|
||||
// pipeMode read mode flags
|
||||
pipe_readmode_byte = 0x0
|
||||
pipe_readmode_message = 0x2
|
||||
|
||||
// pipeMode wait mode flags
|
||||
pipe_wait = 0x0
|
||||
pipe_nowait = 0x1
|
||||
|
||||
// pipeMode remote-client mode flags
|
||||
pipe_accept_remote_clients = 0x0
|
||||
pipe_reject_remote_clients = 0x8
|
||||
|
||||
pipe_unlimited_instances = 255
|
||||
|
||||
nmpwait_wait_forever = 0xFFFFFFFF
|
||||
|
||||
// the two not-an-errors below occur if a client connects to the pipe between
|
||||
// the server's CreateNamedPipe and ConnectNamedPipe calls.
|
||||
error_no_data syscall.Errno = 0xE8
|
||||
error_pipe_connected syscall.Errno = 0x217
|
||||
error_pipe_busy syscall.Errno = 0xE7
|
||||
error_sem_timeout syscall.Errno = 0x79
|
||||
|
||||
error_bad_pathname syscall.Errno = 0xA1
|
||||
error_invalid_name syscall.Errno = 0x7B
|
||||
|
||||
error_io_incomplete syscall.Errno = 0x3e4
|
||||
)
|
||||
|
||||
var _ net.Conn = (*PipeConn)(nil)
|
||||
var _ net.Listener = (*PipeListener)(nil)
|
||||
|
||||
// ErrClosed is the error returned by PipeListener.Accept when Close is called
|
||||
// on the PipeListener.
|
||||
var ErrClosed = PipeError{"Pipe has been closed.", false}
|
||||
|
||||
// PipeError is an error related to a call to a pipe
|
||||
type PipeError struct {
|
||||
msg string
|
||||
timeout bool
|
||||
}
|
||||
|
||||
// Error implements the error interface
|
||||
func (e PipeError) Error() string {
|
||||
return e.msg
|
||||
}
|
||||
|
||||
// Timeout implements net.AddrError.Timeout()
|
||||
func (e PipeError) Timeout() bool {
|
||||
return e.timeout
|
||||
}
|
||||
|
||||
// Temporary implements net.AddrError.Temporary()
|
||||
func (e PipeError) Temporary() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Dial connects to a named pipe with the given address. If the specified pipe is not available,
|
||||
// it will wait indefinitely for the pipe to become available.
|
||||
//
|
||||
// The address must be of the form \\.\\pipe\<name> for local pipes and \\<computer>\pipe\<name>
|
||||
// for remote pipes.
|
||||
//
|
||||
// Dial will return a PipeError if you pass in a badly formatted pipe name.
|
||||
//
|
||||
// Examples:
|
||||
// // local pipe
|
||||
// conn, err := Dial(`\\.\pipe\mypipename`)
|
||||
//
|
||||
// // remote pipe
|
||||
// conn, err := Dial(`\\othercomp\pipe\mypipename`)
|
||||
func Dial(address string) (*PipeConn, error) {
|
||||
for {
|
||||
conn, err := dial(address, nmpwait_wait_forever)
|
||||
if err == nil {
|
||||
return conn, nil
|
||||
}
|
||||
if isPipeNotReady(err) {
|
||||
<-time.After(100 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// DialTimeout acts like Dial, but will time out after the duration of timeout
|
||||
func DialTimeout(address string, timeout time.Duration) (*PipeConn, error) {
|
||||
deadline := time.Now().Add(timeout)
|
||||
|
||||
now := time.Now()
|
||||
for now.Before(deadline) {
|
||||
millis := uint32(deadline.Sub(now) / time.Millisecond)
|
||||
conn, err := dial(address, millis)
|
||||
if err == nil {
|
||||
return conn, nil
|
||||
}
|
||||
if err == error_sem_timeout {
|
||||
// This is WaitNamedPipe's timeout error, so we know we're done
|
||||
return nil, PipeError{fmt.Sprintf(
|
||||
"Timed out waiting for pipe '%s' to come available", address), true}
|
||||
}
|
||||
if isPipeNotReady(err) {
|
||||
left := deadline.Sub(time.Now())
|
||||
retry := 100 * time.Millisecond
|
||||
if left > retry {
|
||||
<-time.After(retry)
|
||||
} else {
|
||||
<-time.After(left - time.Millisecond)
|
||||
}
|
||||
now = time.Now()
|
||||
continue
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return nil, PipeError{fmt.Sprintf(
|
||||
"Timed out waiting for pipe '%s' to come available", address), true}
|
||||
}
|
||||
|
||||
// isPipeNotReady checks the error to see if it indicates the pipe is not ready
|
||||
func isPipeNotReady(err error) bool {
|
||||
// Pipe Busy means another client just grabbed the open pipe end,
|
||||
// and the server hasn't made a new one yet.
|
||||
// File Not Found means the server hasn't created the pipe yet.
|
||||
// Neither is a fatal error.
|
||||
|
||||
return err == syscall.ERROR_FILE_NOT_FOUND || err == error_pipe_busy
|
||||
}
|
||||
|
||||
// newOverlapped creates a structure used to track asynchronous
|
||||
// I/O requests that have been issued.
|
||||
func newOverlapped() (*syscall.Overlapped, error) {
|
||||
event, err := createEvent(nil, true, true, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &syscall.Overlapped{HEvent: event}, nil
|
||||
}
|
||||
|
||||
// waitForCompletion waits for an asynchronous I/O request referred to by overlapped to complete.
|
||||
// This function returns the number of bytes transferred by the operation and an error code if
|
||||
// applicable (nil otherwise).
|
||||
func waitForCompletion(handle syscall.Handle, overlapped *syscall.Overlapped) (uint32, error) {
|
||||
_, err := syscall.WaitForSingleObject(overlapped.HEvent, syscall.INFINITE)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var transferred uint32
|
||||
err = getOverlappedResult(handle, overlapped, &transferred, true)
|
||||
return transferred, err
|
||||
}
|
||||
|
||||
// dial is a helper to initiate a connection to a named pipe that has been started by a server.
|
||||
// The timeout is only enforced if the pipe server has already created the pipe, otherwise
|
||||
// this function will return immediately.
|
||||
func dial(address string, timeout uint32) (*PipeConn, error) {
|
||||
name, err := syscall.UTF16PtrFromString(string(address))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// If at least one instance of the pipe has been created, this function
|
||||
// will wait timeout milliseconds for it to become available.
|
||||
// It will return immediately regardless of timeout, if no instances
|
||||
// of the named pipe have been created yet.
|
||||
// If this returns with no error, there is a pipe available.
|
||||
if err := waitNamedPipe(name, timeout); err != nil {
|
||||
if err == error_bad_pathname {
|
||||
// badly formatted pipe name
|
||||
return nil, badAddr(address)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
pathp, err := syscall.UTF16PtrFromString(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handle, err := syscall.CreateFile(pathp, syscall.GENERIC_READ|syscall.GENERIC_WRITE,
|
||||
uint32(syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE), nil, syscall.OPEN_EXISTING,
|
||||
syscall.FILE_FLAG_OVERLAPPED, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &PipeConn{handle: handle, addr: PipeAddr(address)}, nil
|
||||
}
|
||||
|
||||
// Listen returns a new PipeListener that will listen on a pipe with the given
|
||||
// address. The address must be of the form \\.\pipe\<name>
|
||||
//
|
||||
// Listen will return a PipeError for an incorrectly formatted pipe name.
|
||||
func Listen(address string) (*PipeListener, error) {
|
||||
handle, err := createPipe(address, true)
|
||||
if err == error_invalid_name {
|
||||
return nil, badAddr(address)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &PipeListener{
|
||||
addr: PipeAddr(address),
|
||||
handle: handle,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// PipeListener is a named pipe listener. Clients should typically
|
||||
// use variables of type net.Listener instead of assuming named pipe.
|
||||
type PipeListener struct {
|
||||
mu sync.Mutex
|
||||
|
||||
addr PipeAddr
|
||||
handle syscall.Handle
|
||||
closed bool
|
||||
|
||||
// acceptHandle contains the current handle waiting for
|
||||
// an incoming connection or nil.
|
||||
acceptHandle syscall.Handle
|
||||
// acceptOverlapped is set before waiting on a connection.
|
||||
// If not waiting, it is nil.
|
||||
acceptOverlapped *syscall.Overlapped
|
||||
}
|
||||
|
||||
// Accept implements the Accept method in the net.Listener interface; it
|
||||
// waits for the next call and returns a generic net.Conn.
|
||||
func (l *PipeListener) Accept() (net.Conn, error) {
|
||||
c, err := l.AcceptPipe()
|
||||
for err == error_no_data {
|
||||
// Ignore clients that connect and immediately disconnect.
|
||||
c, err = l.AcceptPipe()
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// AcceptPipe accepts the next incoming call and returns the new connection.
|
||||
// It might return an error if a client connected and immediately cancelled
|
||||
// the connection.
|
||||
func (l *PipeListener) AcceptPipe() (*PipeConn, error) {
|
||||
if l == nil {
|
||||
return nil, syscall.EINVAL
|
||||
}
|
||||
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
if l.addr == "" || l.closed {
|
||||
return nil, syscall.EINVAL
|
||||
}
|
||||
|
||||
// the first time we call accept, the handle will have been created by the Listen
|
||||
// call. This is to prevent race conditions where the client thinks the server
|
||||
// isn't listening because it hasn't actually called create yet. After the first time, we'll
|
||||
// have to create a new handle each time
|
||||
handle := l.handle
|
||||
if handle == 0 {
|
||||
var err error
|
||||
handle, err = createPipe(string(l.addr), false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
l.handle = 0
|
||||
}
|
||||
|
||||
overlapped, err := newOverlapped()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer syscall.CloseHandle(overlapped.HEvent)
|
||||
err = connectNamedPipe(handle, overlapped)
|
||||
if err == nil || err == error_pipe_connected {
|
||||
return &PipeConn{handle: handle, addr: l.addr}, nil
|
||||
}
|
||||
|
||||
if err == error_io_incomplete || err == syscall.ERROR_IO_PENDING {
|
||||
l.acceptOverlapped = overlapped
|
||||
l.acceptHandle = handle
|
||||
// unlock here so close can function correctly while we wait (we'll
|
||||
// get relocked via the defer below, before the original defer
|
||||
// unlock happens.)
|
||||
l.mu.Unlock()
|
||||
defer func() {
|
||||
l.mu.Lock()
|
||||
l.acceptOverlapped = nil
|
||||
l.acceptHandle = 0
|
||||
// unlock is via defer above.
|
||||
}()
|
||||
_, err = waitForCompletion(handle, overlapped)
|
||||
}
|
||||
if err == syscall.ERROR_OPERATION_ABORTED {
|
||||
// Return error compatible to net.Listener.Accept() in case the
|
||||
// listener was closed.
|
||||
return nil, ErrClosed
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &PipeConn{handle: handle, addr: l.addr}, nil
|
||||
}
|
||||
|
||||
// Close stops listening on the address.
|
||||
// Already Accepted connections are not closed.
|
||||
func (l *PipeListener) Close() error {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
if l.closed {
|
||||
return nil
|
||||
}
|
||||
l.closed = true
|
||||
if l.handle != 0 {
|
||||
err := disconnectNamedPipe(l.handle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = syscall.CloseHandle(l.handle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.handle = 0
|
||||
}
|
||||
if l.acceptOverlapped != nil && l.acceptHandle != 0 {
|
||||
// Cancel the pending IO. This call does not block, so it is safe
|
||||
// to hold onto the mutex above.
|
||||
if err := cancelIoEx(l.acceptHandle, l.acceptOverlapped); err != nil {
|
||||
return err
|
||||
}
|
||||
err := syscall.CloseHandle(l.acceptOverlapped.HEvent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.acceptOverlapped.HEvent = 0
|
||||
err = syscall.CloseHandle(l.acceptHandle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.acceptHandle = 0
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Addr returns the listener's network address, a PipeAddr.
|
||||
func (l *PipeListener) Addr() net.Addr { return l.addr }
|
||||
|
||||
// PipeConn is the implementation of the net.Conn interface for named pipe connections.
|
||||
type PipeConn struct {
|
||||
handle syscall.Handle
|
||||
addr PipeAddr
|
||||
|
||||
// these aren't actually used yet
|
||||
readDeadline *time.Time
|
||||
writeDeadline *time.Time
|
||||
}
|
||||
|
||||
type iodata struct {
|
||||
n uint32
|
||||
err error
|
||||
}
|
||||
|
||||
// completeRequest looks at iodata to see if a request is pending. If so, it waits for it to either complete or to
|
||||
// abort due to hitting the specified deadline. Deadline may be set to nil to wait forever. If no request is pending,
|
||||
// the content of iodata is returned.
|
||||
func (c *PipeConn) completeRequest(data iodata, deadline *time.Time, overlapped *syscall.Overlapped) (int, error) {
|
||||
if data.err == error_io_incomplete || data.err == syscall.ERROR_IO_PENDING {
|
||||
var timer <-chan time.Time
|
||||
if deadline != nil {
|
||||
if timeDiff := deadline.Sub(time.Now()); timeDiff > 0 {
|
||||
timer = time.After(timeDiff)
|
||||
}
|
||||
}
|
||||
done := make(chan iodata)
|
||||
go func() {
|
||||
n, err := waitForCompletion(c.handle, overlapped)
|
||||
done <- iodata{n, err}
|
||||
}()
|
||||
select {
|
||||
case data = <-done:
|
||||
case <-timer:
|
||||
syscall.CancelIoEx(c.handle, overlapped)
|
||||
data = iodata{0, timeout(c.addr.String())}
|
||||
}
|
||||
}
|
||||
// Windows will produce ERROR_BROKEN_PIPE upon closing
|
||||
// a handle on the other end of a connection. Go RPC
|
||||
// expects an io.EOF error in this case.
|
||||
if data.err == syscall.ERROR_BROKEN_PIPE {
|
||||
data.err = io.EOF
|
||||
}
|
||||
return int(data.n), data.err
|
||||
}
|
||||
|
||||
// Read implements the net.Conn Read method.
|
||||
func (c *PipeConn) Read(b []byte) (int, error) {
|
||||
// Use ReadFile() rather than Read() because the latter
|
||||
// contains a workaround that eats ERROR_BROKEN_PIPE.
|
||||
overlapped, err := newOverlapped()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer syscall.CloseHandle(overlapped.HEvent)
|
||||
var n uint32
|
||||
err = syscall.ReadFile(c.handle, b, &n, overlapped)
|
||||
return c.completeRequest(iodata{n, err}, c.readDeadline, overlapped)
|
||||
}
|
||||
|
||||
// Write implements the net.Conn Write method.
|
||||
func (c *PipeConn) Write(b []byte) (int, error) {
|
||||
overlapped, err := newOverlapped()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer syscall.CloseHandle(overlapped.HEvent)
|
||||
var n uint32
|
||||
err = syscall.WriteFile(c.handle, b, &n, overlapped)
|
||||
return c.completeRequest(iodata{n, err}, c.writeDeadline, overlapped)
|
||||
}
|
||||
|
||||
// Close closes the connection.
|
||||
func (c *PipeConn) Close() error {
|
||||
return syscall.CloseHandle(c.handle)
|
||||
}
|
||||
|
||||
// LocalAddr returns the local network address.
|
||||
func (c *PipeConn) LocalAddr() net.Addr {
|
||||
return c.addr
|
||||
}
|
||||
|
||||
// RemoteAddr returns the remote network address.
|
||||
func (c *PipeConn) RemoteAddr() net.Addr {
|
||||
// not sure what to do here, we don't have remote addr....
|
||||
return c.addr
|
||||
}
|
||||
|
||||
// SetDeadline implements the net.Conn SetDeadline method.
|
||||
// Note that timeouts are only supported on Windows Vista/Server 2008 and above
|
||||
func (c *PipeConn) SetDeadline(t time.Time) error {
|
||||
c.SetReadDeadline(t)
|
||||
c.SetWriteDeadline(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetReadDeadline implements the net.Conn SetReadDeadline method.
|
||||
// Note that timeouts are only supported on Windows Vista/Server 2008 and above
|
||||
func (c *PipeConn) SetReadDeadline(t time.Time) error {
|
||||
c.readDeadline = &t
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetWriteDeadline implements the net.Conn SetWriteDeadline method.
|
||||
// Note that timeouts are only supported on Windows Vista/Server 2008 and above
|
||||
func (c *PipeConn) SetWriteDeadline(t time.Time) error {
|
||||
c.writeDeadline = &t
|
||||
return nil
|
||||
}
|
||||
|
||||
// PipeAddr represents the address of a named pipe.
|
||||
type PipeAddr string
|
||||
|
||||
// Network returns the address's network name, "pipe".
|
||||
func (a PipeAddr) Network() string { return "pipe" }
|
||||
|
||||
// String returns the address of the pipe
|
||||
func (a PipeAddr) String() string {
|
||||
return string(a)
|
||||
}
|
||||
|
||||
// createPipe is a helper function to make sure we always create pipes
|
||||
// with the same arguments, since subsequent calls to create pipe need
|
||||
// to use the same arguments as the first one. If first is set, fail
|
||||
// if the pipe already exists.
|
||||
func createPipe(address string, first bool) (syscall.Handle, error) {
|
||||
n, err := syscall.UTF16PtrFromString(address)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
mode := uint32(pipe_access_duplex | syscall.FILE_FLAG_OVERLAPPED)
|
||||
if first {
|
||||
mode |= file_flag_first_pipe_instance
|
||||
}
|
||||
return createNamedPipe(n,
|
||||
mode,
|
||||
pipe_type_byte,
|
||||
pipe_unlimited_instances,
|
||||
512, 512, 0, nil)
|
||||
}
|
||||
|
||||
func badAddr(addr string) PipeError {
|
||||
return PipeError{fmt.Sprintf("Invalid pipe address '%s'.", addr), false}
|
||||
}
|
||||
func timeout(addr string) PipeError {
|
||||
return PipeError{fmt.Sprintf("Pipe IO timed out waiting for '%s'", addr), true}
|
||||
}
|
|
@ -1,124 +0,0 @@
|
|||
// +build windows
|
||||
// go build mksyscall_windows.go && ./mksyscall_windows npipe_windows.go
|
||||
// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
|
||||
|
||||
package npipe
|
||||
|
||||
import "unsafe"
|
||||
import "syscall"
|
||||
|
||||
var (
|
||||
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
|
||||
procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW")
|
||||
procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe")
|
||||
procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe")
|
||||
procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW")
|
||||
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||
procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult")
|
||||
procCancelIoEx = modkernel32.NewProc("CancelIoEx")
|
||||
)
|
||||
|
||||
func createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) {
|
||||
r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(openMode), uintptr(pipeMode), uintptr(maxInstances), uintptr(outBufSize), uintptr(inBufSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0)
|
||||
handle = syscall.Handle(r0)
|
||||
if handle == syscall.InvalidHandle {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func disconnectNamedPipe(handle syscall.Handle) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(handle), 0, 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func waitNamedPipe(name *uint16, timeout uint32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) {
|
||||
var _p0 uint32
|
||||
if manualReset {
|
||||
_p0 = 1
|
||||
} else {
|
||||
_p0 = 0
|
||||
}
|
||||
var _p1 uint32
|
||||
if initialState {
|
||||
_p1 = 1
|
||||
} else {
|
||||
_p1 = 0
|
||||
}
|
||||
r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(sa)), uintptr(_p0), uintptr(_p1), uintptr(unsafe.Pointer(name)), 0, 0)
|
||||
handle = syscall.Handle(r0)
|
||||
if handle == syscall.InvalidHandle {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) {
|
||||
var _p0 uint32
|
||||
if wait {
|
||||
_p0 = 1
|
||||
} else {
|
||||
_p0 = 0
|
||||
}
|
||||
r1, _, e1 := syscall.Syscall6(procGetOverlappedResult.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transferred)), uintptr(_p0), 0, 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
|
@ -1,124 +0,0 @@
|
|||
// +build windows
|
||||
// go build mksyscall_windows.go && ./mksyscall_windows npipe_windows.go
|
||||
// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
|
||||
|
||||
package npipe
|
||||
|
||||
import "unsafe"
|
||||
import "syscall"
|
||||
|
||||
var (
|
||||
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
|
||||
procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW")
|
||||
procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe")
|
||||
procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe")
|
||||
procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW")
|
||||
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||
procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult")
|
||||
procCancelIoEx = modkernel32.NewProc("CancelIoEx")
|
||||
)
|
||||
|
||||
func createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) {
|
||||
r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(openMode), uintptr(pipeMode), uintptr(maxInstances), uintptr(outBufSize), uintptr(inBufSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0)
|
||||
handle = syscall.Handle(r0)
|
||||
if handle == syscall.InvalidHandle {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func disconnectNamedPipe(handle syscall.Handle) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(handle), 0, 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func waitNamedPipe(name *uint16, timeout uint32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) {
|
||||
var _p0 uint32
|
||||
if manualReset {
|
||||
_p0 = 1
|
||||
} else {
|
||||
_p0 = 0
|
||||
}
|
||||
var _p1 uint32
|
||||
if initialState {
|
||||
_p1 = 1
|
||||
} else {
|
||||
_p1 = 0
|
||||
}
|
||||
r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(sa)), uintptr(_p0), uintptr(_p1), uintptr(unsafe.Pointer(name)), 0, 0)
|
||||
handle = syscall.Handle(r0)
|
||||
if handle == syscall.InvalidHandle {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) {
|
||||
var _p0 uint32
|
||||
if wait {
|
||||
_p0 = 1
|
||||
} else {
|
||||
_p0 = 0
|
||||
}
|
||||
r1, _, e1 := syscall.Syscall6(procGetOverlappedResult.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transferred)), uintptr(_p0), 0, 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = error(e1)
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
|
@ -1168,9 +1168,6 @@ gopkg.in/inf.v0
|
|||
# gopkg.in/ini.v1 v1.66.2
|
||||
## explicit
|
||||
gopkg.in/ini.v1
|
||||
# gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce
|
||||
## explicit
|
||||
gopkg.in/natefinch/npipe.v2
|
||||
# gopkg.in/src-d/go-billy.v4 v4.3.2
|
||||
## explicit
|
||||
gopkg.in/src-d/go-billy.v4
|
||||
|
|
Loading…
Reference in New Issue