commit 78687d3c509db28dedcbbf93a69fd3aaaa1a7fce Author: crusader Date: Tue Oct 24 11:57:54 2017 +0900 project is created. diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..2ca2b1d --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,32 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Debug", + "type": "go", + "request": "launch", + "mode": "debug", + "remotePath": "", + "port": 2345, + "host": "127.0.0.1", + "program": "${workspaceRoot}/main.go", + "env": {}, + "args": [], + "showLog": true + }, + { + "name": "File Debug", + "type": "go", + "request": "launch", + "mode": "debug", + "remotePath": "", + "port": 2345, + "host": "127.0.0.1", + "program": "${fileDirname}", + "env": {}, + "args": [], + "showLog": true + } + + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..20af2f6 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +// Place your settings in this file to overwrite default and user settings. +{ +} \ No newline at end of file diff --git a/glide.lock b/glide.lock new file mode 100644 index 0000000..05706ef --- /dev/null +++ b/glide.lock @@ -0,0 +1,6 @@ +hash: b1a11c3dea7e9ea474b94d7002d7121aac95030762ffd0bcecc1135b1e1ac489 +updated: 2017-10-24T11:48:19.568186433+09:00 +imports: +- name: gopkg.in/natefinch/npipe.v2 + version: c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6 +testImports: [] diff --git a/glide.yaml b/glide.yaml new file mode 100644 index 0000000..2850db5 --- /dev/null +++ b/glide.yaml @@ -0,0 +1,3 @@ +package: git.loafle.net/commons_go/local_socket +import: +- package: gopkg.in/natefinch/npipe.v2 diff --git a/server.go b/server.go new file mode 100644 index 0000000..b5b1fb9 --- /dev/null +++ b/server.go @@ -0,0 +1,16 @@ +package local_socket + +import ( + "errors" + "net" +) + +var StoppedError = errors.New("Listener stopped") + +func (s *LocalServer) SetOnConnectionCallback(callback func(net.Conn)) { + s.callback = callback +} + +func (s *LocalServer) Path() string { + return s.path +} diff --git a/server_unix.go b/server_unix.go new file mode 100644 index 0000000..069a8bd --- /dev/null +++ b/server_unix.go @@ -0,0 +1,119 @@ +package local_socket + +import ( + "errors" + "fmt" + "net" + "os" + "path/filepath" + "sync" + "time" +) + +type LocalServer struct { + path string + callback func(socket net.Conn) + stop chan int + wg sync.WaitGroup +} + +func NewLocalServer(pathName string) *LocalServer { + path := filepath.Join(os.TempDir(), pathName) + os.Remove(path) + return &LocalServer{ + path: path, + } +} + +func (s *LocalServer) ListenAndServe() error { + if s.callback == nil { + return errors.New("no callback specified") + } + listener, err := net.ListenUnix("unix", &net.UnixAddr{s.path, "unix"}) + if err != nil { + return err + } + defer listener.Close() + s.stop = make(chan int) + s.wg.Add(1) + for { + listener.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(1000))) + conn, err := listener.AcceptUnix() + // check channel is still opening + select { + case <-s.stop: + s.wg.Done() + return StoppedError + default: + // opening + } + if err == nil { + s.wg.Add(1) + go func() { + s.callback(newLocalSocket(conn)) + s.wg.Done() + }() + continue + } + netErr, ok := err.(net.Error) + if ok && netErr.Timeout() && netErr.Temporary() { + continue + } + println(err.Error()) + s.wg.Done() + return err + } +} + +func (s *LocalServer) Listen() error { + if s.callback == nil { + return errors.New("no callback specified") + } + listener, err := net.ListenUnix("unix", &net.UnixAddr{s.path, "unix"}) + if err != nil { + return err + } + s.stop = make(chan int) + s.wg.Add(1) + go func() { + defer func() { + s.wg.Done() + err := listener.Close() + fmt.Println(err) + }() + for { + listener.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(333))) + conn, err := listener.AcceptUnix() + // check channel is still opening + select { + case <-s.stop: + return + default: + // opening + } + if err == nil { + s.wg.Add(1) + go func() { + s.callback(newLocalSocket(conn)) + s.wg.Done() + }() + continue + } + netErr, ok := err.(net.Error) + if ok && netErr.Timeout() && netErr.Temporary() { + continue + } + println("error") + panic(err) + } + }() + return nil +} + +func (s *LocalServer) Close() { + if s.stop != nil { + close(s.stop) + s.wg.Wait() + s.stop = nil + } +} diff --git a/server_windows.go b/server_windows.go new file mode 100644 index 0000000..2ac5762 --- /dev/null +++ b/server_windows.go @@ -0,0 +1,100 @@ +package local_socket + +import ( + "errors" + "fmt" + "net" + "sync" + + "gopkg.in/natefinch/npipe.v2" +) + +type LocalServer struct { + path string + callback func(socket net.Conn) + listener *npipe.PipeListener + wg sync.WaitGroup +} + +func NewLocalServer(pathName string) *LocalServer { + return &LocalServer{ + path: `\\.\pipe\` + pathName, + } +} + +func (s *LocalServer) ListenAndServe() error { + if s.callback == nil { + return errors.New("no callback specified") + } + s.wg.Wait() + var err error + s.listener, err = npipe.Listen(s.path) + if err != nil { + return err + } + defer s.listener.Close() + s.wg.Add(1) + defer func() { + s.wg.Done() + s.listener.Close() + }() + for { + conn, err := s.listener.AcceptPipe() + if conn == nil { + return StoppedError + } + if err == nil { + s.wg.Add(1) + go func() { + s.callback(newLocalSocket(conn)) + s.wg.Done() + }() + continue + } + println(err.Error()) + s.wg.Done() + return err + } +} + +func (s *LocalServer) Listen() error { + s.wg.Wait() + if s.callback == nil { + return errors.New("no callback specified") + } + var err error + s.listener, err = npipe.Listen(s.path) + if err != nil { + return err + } + s.wg.Add(1) + go func() { + defer func() { + s.wg.Done() + err := s.listener.Close() + fmt.Println(err) + }() + for { + conn, err := s.listener.AcceptPipe() + // check channel is still opening + if conn == nil { + return + } + if err == nil { + s.wg.Add(1) + go func() { + s.callback(newLocalSocket(conn)) + s.wg.Done() + }() + continue + } + println("error") + panic(err) + } + }() + return nil +} + +func (s *LocalServer) Close() { + s.listener.Close() +} diff --git a/socket.go b/socket.go new file mode 100644 index 0000000..2065cb7 --- /dev/null +++ b/socket.go @@ -0,0 +1,50 @@ +package local_socket + +import ( + "net" + "time" +) + +// Read reads data from the connection. +func (s *LocalSocket) Read(data []byte) (int, error) { + return s.conn.Read(data) +} + +// Write writes data to the connection. +func (s *LocalSocket) Write(data []byte) (int, error) { + return s.conn.Write(data) +} + +// Close closes the connection. +func (s *LocalSocket) Close() error { + return s.conn.Close() +} + +// LocalAddr returns the local network address. +// The Addr returned is shared by all invocations of LocalAddr, so +// do not modify it. +func (s *LocalSocket) LocalAddr() net.Addr { + return s.conn.LocalAddr() +} + +// RemoteAddr returns the remote network address. +// The Addr returned is shared by all invocations of RemoteAddr, so +// do not modify it. +func (s *LocalSocket) RemoteAddr() net.Addr { + return s.conn.RemoteAddr() +} + +// SetDeadline implements the Conn SetDeadline method. +func (s *LocalSocket) SetDeadline(t time.Time) error { + return s.conn.SetDeadline(t) +} + +// SetReadDeadline implements the Conn SetReadDeadline method. +func (s *LocalSocket) SetReadDeadline(t time.Time) error { + return s.conn.SetReadDeadline(t) +} + +// SetWriteDeadline implements the Conn SetWriteDeadline method. +func (s *LocalSocket) SetWriteDeadline(t time.Time) error { + return s.conn.SetWriteDeadline(t) +} diff --git a/socket_unix.go b/socket_unix.go new file mode 100644 index 0000000..60bdbe7 --- /dev/null +++ b/socket_unix.go @@ -0,0 +1,29 @@ +package local_socket + +import ( + "net" + "os" + "path/filepath" +) + +// LocalSocket is a socket to communicate with other processes in the same box. +// LocalSocket satisfies io.Reader, io.Writer, net.Conn interfaces. +type LocalSocket struct { + conn *net.UnixConn +} + +// NewLocalSocket creates LocalSocket instance +func NewLocalSocket(pathName string) (*LocalSocket, error) { + socketType := "unix" // SOCK_STREAM + conn, err := net.DialUnix(socketType, nil, &net.UnixAddr{filepath.Join(os.TempDir(), pathName), socketType}) + if err != nil { + return nil, err + } + return newLocalSocket(conn), nil +} + +func newLocalSocket(conn *net.UnixConn) *LocalSocket { + return &LocalSocket{ + conn: conn, + } +} diff --git a/socket_windows.go b/socket_windows.go new file mode 100644 index 0000000..1db260c --- /dev/null +++ b/socket_windows.go @@ -0,0 +1,26 @@ +package local_socket + +mport ( + "gopkg.in/natefinch/npipe.v2" +) + +// LocalSocket is a socket to communicate with other processes in the same box. +// LocalSocket satisfies io.Reader, io.Writer, net.Conn interfaces. +type LocalSocket struct { + *npipe.PipeConn +} + +// NewLocalSocket creates LocalSocket instance +func NewLocalSocket(pathName string) (*LocalSocket, error) { + conn, err := npipe.Dial(`\\.\pipe\` + pathName) + if err != nil { + return nil, err + } + return newLocalSocket(conn), nil +} + +func newLocalSocket(conn *npipe.PipeConn) *LocalSocket { + return &LocalSocket{ + PipeConn: conn, + } +} diff --git a/vendor/gopkg.in/natefinch/npipe.v2/.gitignore b/vendor/gopkg.in/natefinch/npipe.v2/.gitignore new file mode 100644 index 0000000..0026861 --- /dev/null +++ b/vendor/gopkg.in/natefinch/npipe.v2/.gitignore @@ -0,0 +1,22 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe diff --git a/vendor/gopkg.in/natefinch/npipe.v2/LICENSE.txt b/vendor/gopkg.in/natefinch/npipe.v2/LICENSE.txt new file mode 100644 index 0000000..a4a1104 --- /dev/null +++ b/vendor/gopkg.in/natefinch/npipe.v2/LICENSE.txt @@ -0,0 +1,8 @@ +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. \ No newline at end of file diff --git a/vendor/gopkg.in/natefinch/npipe.v2/README.md b/vendor/gopkg.in/natefinch/npipe.v2/README.md new file mode 100644 index 0000000..420a4d1 --- /dev/null +++ b/vendor/gopkg.in/natefinch/npipe.v2/README.md @@ -0,0 +1,308 @@ +npipe [![Build status](https://ci.appveyor.com/api/projects/status/00vuepirsot29qwi)](https://ci.appveyor.com/project/natefinch/npipe) [![GoDoc](https://godoc.org/gopkg.in/natefinch/npipe.v2?status.svg)](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 { + + } + 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\ for local pipes and \\\pipe\ +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\ + +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. diff --git a/vendor/gopkg.in/natefinch/npipe.v2/doc.go b/vendor/gopkg.in/natefinch/npipe.v2/doc.go new file mode 100644 index 0000000..3445773 --- /dev/null +++ b/vendor/gopkg.in/natefinch/npipe.v2/doc.go @@ -0,0 +1,50 @@ +// 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 { +// +// } +// 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 diff --git a/vendor/gopkg.in/natefinch/npipe.v2/example_windows_test.go b/vendor/gopkg.in/natefinch/npipe.v2/example_windows_test.go new file mode 100644 index 0000000..cb3f93b --- /dev/null +++ b/vendor/gopkg.in/natefinch/npipe.v2/example_windows_test.go @@ -0,0 +1,53 @@ +package npipe_test + +import ( + "bufio" + "fmt" + "net" + + "gopkg.in/natefinch/npipe.v2" +) + +// Use Dial to connect to a server and read messages from it. +func ExampleDial() { + conn, err := npipe.Dial(`\\.\pipe\mypipe`) + if err != nil { + // handle error + } + if _, err := fmt.Fprintln(conn, "Hi server!"); err != nil { + // handle error + } + r := bufio.NewReader(conn) + msg, err := r.ReadString('\n') + if err != nil { + // handle eror + } + fmt.Println(msg) +} + +// Use Listen to start a server, and accept connections with Accept(). +func ExampleListen() { + ln, err := npipe.Listen(`\\.\pipe\mypipe`) + if err != nil { + // handle error + } + + for { + conn, err := ln.Accept() + if err != nil { + // handle error + continue + } + + // handle connection like any other net.Conn + go func(conn net.Conn) { + r := bufio.NewReader(conn) + msg, err := r.ReadString('\n') + if err != nil { + // handle error + return + } + fmt.Println(msg) + }(conn) + } +} diff --git a/vendor/gopkg.in/natefinch/npipe.v2/npipe_windows.go b/vendor/gopkg.in/natefinch/npipe.v2/npipe_windows.go new file mode 100755 index 0000000..5e7cf13 --- /dev/null +++ b/vendor/gopkg.in/natefinch/npipe.v2/npipe_windows.go @@ -0,0 +1,531 @@ +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\ for local pipes and \\\pipe\ +// 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\ +// +// 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} +} diff --git a/vendor/gopkg.in/natefinch/npipe.v2/npipe_windows_test.go b/vendor/gopkg.in/natefinch/npipe.v2/npipe_windows_test.go new file mode 100755 index 0000000..2a7da25 --- /dev/null +++ b/vendor/gopkg.in/natefinch/npipe.v2/npipe_windows_test.go @@ -0,0 +1,643 @@ +package npipe + +import ( + "bufio" + "crypto/rand" + "fmt" + "io" + "io/ioutil" + "net" + "net/rpc" + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +const ( + clientMsg = "Hi server!\n" + serverMsg = "Hi there, client!\n" + fileTemplate = "62DA0493-99A1-4327-B5A8-6C4E4466C3FC.txt" +) + +// TestBadDial tests that if you dial something other than a valid pipe path, that you get back a +// PipeError and that you don't accidently create a file on disk (since dial uses OpenFile) +func TestBadDial(t *testing.T) { + fn := filepath.Join("C:\\", fileTemplate) + ns := []string{fn, "http://www.google.com", "somethingbadhere"} + for _, n := range ns { + c, err := Dial(n) + if _, ok := err.(PipeError); !ok { + t.Errorf("Dialing '%s' did not result in correct error! Expected PipeError, got '%v'", + n, err) + } + if c != nil { + t.Errorf("Dialing '%s' returned non-nil connection", n) + } + if b, _ := exists(n); b { + t.Errorf("Dialing '%s' incorrectly created file on disk", n) + } + } +} + +// TestDialExistingFile tests that if you dial with the name of an existing file, +// that you don't accidentally open the file (since dial uses OpenFile) +func TestDialExistingFile(t *testing.T) { + tempdir := os.TempDir() + fn := filepath.Join(tempdir, fileTemplate) + if f, err := os.Create(fn); err != nil { + t.Fatalf("Unexpected error creating file '%s': '%v'", fn, err) + } else { + // we don't actually need to write to the file, just need it to exist + f.Close() + defer os.Remove(fn) + } + c, err := Dial(fn) + if _, ok := err.(PipeError); !ok { + t.Errorf("Dialing '%s' did not result in error! Expected PipeError, got '%v'", fn, err) + } + if c != nil { + t.Errorf("Dialing '%s' returned non-nil connection", fn) + } +} + +// TestBadListen tests that if you listen on a bad address, that we get back a PipeError +func TestBadListen(t *testing.T) { + addrs := []string{"not a valid pipe address", `\\127.0.0.1\pipe\TestBadListen`} + for _, address := range addrs { + ln, err := Listen(address) + if _, ok := err.(PipeError); !ok { + t.Errorf("Listening on '%s' did not result in correct error! Expected PipeError, got '%v'", + address, err) + } + if ln != nil { + t.Errorf("Listening on '%s' returned non-nil listener.", address) + } + } +} + +// TestDoubleListen makes sure we can't listen to the same address twice. +func TestDoubleListen(t *testing.T) { + address := `\\.\pipe\TestDoubleListen` + ln1, err := Listen(address) + if err != nil { + t.Fatalf("Listen(%q): %v", address, err) + } + defer ln1.Close() + + ln2, err := Listen(address) + if err == nil { + ln2.Close() + t.Fatalf("second Listen on %q succeeded.", address) + } +} + +// TestPipeConnected tests whether we correctly handle clients connecting +// and then closing the connection between creating and connecting the +// pipe on the server side. +func TestPipeConnected(t *testing.T) { + address := `\\.\pipe\TestPipeConnected` + ln, err := Listen(address) + if err != nil { + t.Fatalf("Listen(%q): %v", address, err) + } + defer ln.Close() + + // Create a client connection and close it immediately. + clientConn, err := Dial(address) + if err != nil { + t.Fatalf("Error from dial: %v", err) + } + clientConn.Close() + + content := "test" + go func() { + // Now create a real connection and send some data. + clientConn, err := Dial(address) + if err != nil { + t.Fatalf("Error from dial: %v", err) + } + if _, err := clientConn.Write([]byte(content)); err != nil { + t.Fatalf("Error writing to pipe: %v", err) + } + clientConn.Close() + }() + + serverConn, err := ln.Accept() + if err != nil { + t.Fatalf("Error from accept: %v", err) + } + result, err := ioutil.ReadAll(serverConn) + if err != nil { + t.Fatalf("Error from ReadAll: %v", err) + } + if string(result) != content { + t.Fatalf("Got %s, expected: %s", string(result), content) + } + serverConn.Close() +} + +// TestListenCloseListen tests whether Close() actually closes a named pipe properly. +func TestListenCloseListen(t *testing.T) { + address := `\\.\pipe\TestListenCloseListen` + ln1, err := Listen(address) + if err != nil { + t.Fatalf("Listen(%q): %v", address, err) + } + ln1.Close() + + ln2, err := Listen(address) + if err != nil { + t.Fatalf("second Listen on %q failed.", address) + } + ln2.Close() +} + +// TestCloseFileHandles tests that all PipeListener handles are actualy closed after +// calling Close() +func TestCloseFileHandles(t *testing.T) { + address := `\\.\pipe\TestCloseFileHandles` + ln, err := Listen(address) + if err != nil { + t.Fatalf("Error listening on %q: %v", address, err) + } + defer ln.Close() + server := rpc.NewServer() + service := &RPCService{} + server.Register(service) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + // Ignore errors produced by a closed listener. + if err != ErrClosed { + t.Errorf("ln.Accept(): %v", err.Error()) + } + break + } + go server.ServeConn(conn) + } + }() + conn, err := Dial(address) + if err != nil { + t.Fatalf("Error dialing %q: %v", address, err) + } + client := rpc.NewClient(conn) + defer client.Close() + req := "dummy" + resp := "" + if err = client.Call("RPCService.GetResponse", req, &resp); err != nil { + t.Fatalf("Error calling RPCService.GetResponse: %v", err) + } + if req != resp { + t.Fatalf("Unexpected result (expected: %q, got: %q)", req, resp) + } + ln.Close() + + if ln.acceptHandle != 0 { + t.Fatalf("Failed to close acceptHandle") + } + if ln.acceptOverlapped.HEvent != 0 { + t.Fatalf("Failed to close acceptOverlapped handle") + } +} + +// TestCancelListen tests whether Accept() can be cancelled by closing the listener. +func TestCancelAccept(t *testing.T) { + address := `\\.\pipe\TestCancelListener` + ln, err := Listen(address) + if err != nil { + t.Fatalf("Listen(%q): %v", address, err) + } + + cancelled := make(chan struct{}) + started := make(chan struct{}) + go func() { + close(started) + conn, _ := ln.Accept() + if conn != nil { + t.Fatalf("Unexpected incoming connection: %v", conn) + conn.Close() + } + cancelled <- struct{}{} + }() + <-started + // Close listener after 20ms. This should give the go routine enough time to be actually + // waiting for incoming connections inside ln.Accept(). + time.AfterFunc(20*time.Millisecond, func() { + if err := ln.Close(); err != nil { + t.Fatalf("Error closing listener: %v", err) + } + }) + // Any Close() should abort the ln.Accept() call within 100ms. + // We fail with a timeout otherwise, to avoid blocking forever on a failing test. + timeout := time.After(100 * time.Millisecond) + select { + case <-cancelled: + // This is what should happen. + case <-timeout: + t.Fatal("Timeout trying to cancel accept.") + } +} + +// Test that PipeConn's read deadline works correctly +func TestReadDeadline(t *testing.T) { + address := `\\.\pipe\TestReadDeadline` + var wg sync.WaitGroup + wg.Add(1) + + go listenAndWait(address, wg, t) + defer wg.Done() + + c, err := Dial(address) + if err != nil { + t.Fatalf("Error dialing into pipe: %v", err) + } + if c == nil { + t.Fatal("Unexpected nil connection from Dial") + } + defer c.Close() + deadline := time.Now().Add(time.Millisecond * 50) + c.SetReadDeadline(deadline) + msg, err := bufio.NewReader(c).ReadString('\n') + end := time.Now() + if msg != "" { + t.Errorf("Pipe read timeout returned a non-empty message: %s", msg) + } + if err == nil { + t.Error("Pipe read timeout returned nil error") + } else { + pe, ok := err.(PipeError) + if !ok { + t.Errorf("Got wrong error returned, expected PipeError, got '%t'", err) + } + if !pe.Timeout() { + t.Error("Pipe read timeout didn't return an error indicating the timeout") + } + } + checkDeadline(deadline, end, t) +} + +// listenAndWait simply sets up a pipe listener that does nothing and closes after the waitgroup +// is done. +func listenAndWait(address string, wg sync.WaitGroup, t *testing.T) { + ln, err := Listen(address) + if err != nil { + t.Fatalf("Error starting to listen on pipe: %v", err) + } + if ln == nil { + t.Fatal("Got unexpected nil listener") + } + conn, err := ln.Accept() + if err != nil { + t.Fatalf("Error accepting connection: %v", err) + } + if conn == nil { + t.Fatal("Got unexpected nil connection") + } + defer conn.Close() + // don't read or write anything + wg.Wait() +} + +// TestWriteDeadline tests that PipeConn's write deadline works correctly +func TestWriteDeadline(t *testing.T) { + address := `\\.\pipe\TestWriteDeadline` + var wg sync.WaitGroup + wg.Add(1) + + go listenAndWait(address, wg, t) + defer wg.Done() + c, err := Dial(address) + if err != nil { + t.Fatalf("Error dialing into pipe: %v", err) + } + if c == nil { + t.Fatal("Unexpected nil connection from Dial") + } + + // windows pipes have a buffer, so even if we don't read from the pipe, + // the write may succeed anyway, so we have to write a whole bunch to + // test the time out + deadline := time.Now().Add(time.Millisecond * 50) + c.SetWriteDeadline(deadline) + buffer := make([]byte, 1<<16) + if _, err = io.ReadFull(rand.Reader, buffer); err != nil { + t.Fatalf("Couldn't generate random buffer: %v", err) + } + _, err = c.Write(buffer) + + end := time.Now() + + if err == nil { + t.Error("Pipe write timeout returned nil error") + } else { + pe, ok := err.(PipeError) + if !ok { + t.Errorf("Got wrong error returned, expected PipeError, got '%t'", err) + } + if !pe.Timeout() { + t.Error("Pipe write timeout didn't return an error indicating the timeout") + } + } + checkDeadline(deadline, end, t) +} + +// TestDialTimeout tests that the DialTimeout function will actually timeout correctly +func TestDialTimeout(t *testing.T) { + timeout := time.Millisecond * 150 + deadline := time.Now().Add(timeout) + c, err := DialTimeout(`\\.\pipe\TestDialTimeout`, timeout) + end := time.Now() + if c != nil { + t.Errorf("DialTimeout returned non-nil connection: %v", c) + } + if err == nil { + t.Error("DialTimeout returned nil error after timeout") + } else { + pe, ok := err.(PipeError) + if !ok { + t.Errorf("Got wrong error returned, expected PipeError, got '%t'", err) + } + if !pe.Timeout() { + t.Error("Dial timeout didn't return an error indicating the timeout") + } + } + checkDeadline(deadline, end, t) +} + +// TestDialNoTimeout tests that the DialTimeout function will properly wait for the pipe and +// connect when it is available +func TestDialNoTimeout(t *testing.T) { + timeout := time.Millisecond * 500 + address := `\\.\pipe\TestDialNoTimeout` + go func() { + <-time.After(50 * time.Millisecond) + listenAndClose(address, t) + }() + + deadline := time.Now().Add(timeout) + c, err := DialTimeout(address, timeout) + end := time.Now() + + if c == nil { + t.Error("DialTimeout returned unexpected nil connection") + } + if err != nil { + t.Error("DialTimeout returned unexpected non-nil error: ", err) + } + if end.After(deadline) { + t.Fatalf("Ended %v after deadline", end.Sub(deadline)) + } +} + +// TestDial tests that you can dial before a pipe is available, +// and that it'll pick up the pipe once it's ready +func TestDial(t *testing.T) { + address := `\\.\pipe\TestDial` + var wg sync.WaitGroup + wg.Add(1) + go func() { + wg.Done() + conn, err := Dial(address) + if err != nil { + t.Fatalf("Got unexpected error from Dial: %v", err) + } + if conn == nil { + t.Fatal("Got unexpected nil connection from Dial") + } + if err := conn.Close(); err != nil { + t.Fatalf("Got unexpected error from conection.Close(): %v", err) + } + }() + + wg.Wait() + <-time.After(50 * time.Millisecond) + listenAndClose(address, t) +} + +type RPCService struct{} + +func (s *RPCService) GetResponse(request string, response *string) error { + *response = request + return nil +} + +// TestGoRPC tests that you can run go RPC over the pipe, +// and that overlapping bi-directional communication is working +// (write while a blocking read is in progress). +func TestGoRPC(t *testing.T) { + address := `\\.\pipe\TestRPC` + ln, err := Listen(address) + if err != nil { + t.Fatalf("Error listening on %q: %v", address, err) + } + waitExit := make(chan struct{}) + defer func() { + ln.Close() + <-waitExit + }() + + go func() { + server := rpc.NewServer() + server.Register(&RPCService{}) + for { + conn, err := ln.Accept() + if err != nil { + // Ignore errors produced by a closed listener. + if err != ErrClosed { + t.Errorf("ln.Accept(): %v", err.Error()) + } + break + } + go server.ServeConn(conn) + } + close(waitExit) + }() + conn, err := Dial(address) + if err != nil { + t.Fatalf("Error dialing %q: %v", address, err) + } + client := rpc.NewClient(conn) + defer client.Close() + req := "dummy" + var resp string + if err = client.Call("RPCService.GetResponse", req, &resp); err != nil { + t.Fatalf("Error calling RPCService.GetResponse: %v", err) + } + if req != resp { + t.Fatalf("Unexpected result (expected: %q, got: %q)", req, resp) + } +} + +// listenAndClose is a helper method to just listen on a pipe and close as soon as someone connects. +func listenAndClose(address string, t *testing.T) { + ln, err := Listen(address) + if err != nil { + t.Fatalf("Got unexpected error from Listen: %v", err) + } + if ln == nil { + t.Fatal("Got unexpected nil listener from Listen") + } + conn, err := ln.Accept() + if err != nil { + t.Fatalf("Got unexpected error from Accept: %v", err) + } + if conn == nil { + t.Fatal("Got unexpected nil connection from Accept") + } + if err := conn.Close(); err != nil { + t.Fatalf("Got unexpected error from conection.Close(): %v", err) + } +} + +// TestCommonUseCase is a full run-through of the most common use case, where you create a listener +// and then dial into it with several clients in succession +func TestCommonUseCase(t *testing.T) { + addrs := []string{`\\.\pipe\TestCommonUseCase`, `\\127.0.0.1\pipe\TestCommonUseCase`} + // always listen on the . version, since IP won't work for listening + ln, err := Listen(addrs[0]) + if err != nil { + t.Fatalf("Listen(%q) failed: %v", addrs[0], err) + } + defer ln.Close() + + for _, address := range addrs { + convos := 5 + clients := 10 + + wg := sync.WaitGroup{} + + for x := 0; x < clients; x++ { + wg.Add(1) + go startClient(address, &wg, convos, t) + } + + go startServer(ln, convos, t) + + select { + case <-wait(&wg): + // good! + case <-time.After(time.Second): + t.Fatal("Failed to finish after a reasonable timeout") + } + } +} + +// wait simply waits on the waitgroup and closes the returned channel when done. +func wait(wg *sync.WaitGroup) <-chan struct{} { + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + return done +} + +// startServer accepts connections and spawns goroutines to handle them +func startServer(ln *PipeListener, iter int, t *testing.T) { + for { + conn, err := ln.Accept() + if err == ErrClosed { + return + } + if err != nil { + t.Fatalf("Error accepting connection: %v", err) + } + go handleConnection(conn, iter, t) + } +} + +// handleConnection is the goroutine that handles connections on the server side +// it expects to read a message and then write a message, convos times, before exiting. +func handleConnection(conn net.Conn, convos int, t *testing.T) { + r := bufio.NewReader(conn) + for x := 0; x < convos; x++ { + msg, err := r.ReadString('\n') + if err != nil { + t.Fatalf("Error reading from server connection: %v", err) + } + if msg != clientMsg { + t.Fatalf("Read incorrect message from client. Expected '%s', got '%s'", clientMsg, msg) + } + + if _, err := fmt.Fprint(conn, serverMsg); err != nil { + t.Fatalf("Error on server writing to pipe: %v", err) + } + } + if err := conn.Close(); err != nil { + t.Fatalf("Error closing server side of connection: %v", err) + } +} + +// startClient waits on a pipe at the given address. It expects to write a message and then +// read a message from the pipe, convos times, and then sends a message on the done +// channel +func startClient(address string, wg *sync.WaitGroup, convos int, t *testing.T) { + defer wg.Done() + c := make(chan *PipeConn) + go asyncdial(address, c, t) + + var conn *PipeConn + select { + case conn = <-c: + case <-time.After(time.Second): + // Yes this is a long timeout, but sometimes it really does take a long time. + t.Fatalf("Client timed out waiting for dial to resolve") + } + r := bufio.NewReader(conn) + for x := 0; x < convos; x++ { + if _, err := fmt.Fprint(conn, clientMsg); err != nil { + t.Fatalf("Error on client writing to pipe: %v", err) + } + + msg, err := r.ReadString('\n') + if err != nil { + t.Fatalf("Error reading from client connection: %v", err) + } + if msg != serverMsg { + t.Fatalf("Read incorrect message from server. Expected '%s', got '%s'", serverMsg, msg) + } + } + + if err := conn.Close(); err != nil { + t.Fatalf("Error closing client side of pipe %v", err) + } +} + +// asyncdial is a helper that dials and returns the connection on the given channel. +// this is useful for being able to give dial a timeout +func asyncdial(address string, c chan *PipeConn, t *testing.T) { + conn, err := Dial(address) + if err != nil { + t.Fatalf("Error from dial: %v", err) + } + c <- conn +} + +// exists is a simple helper function to detect if a file exists on disk +func exists(path string) (bool, error) { + _, err := os.Stat(path) + if err == nil { + return true, nil + } + if os.IsNotExist(err) { + return false, nil + } + return false, err +} + +func checkDeadline(deadline, end time.Time, t *testing.T) { + if end.Before(deadline) { + t.Fatalf("Ended %v before deadline", deadline.Sub(end)) + } + diff := end.Sub(deadline) + + // we need a huge fudge factor here because Windows has really poor + // resolution for timeouts, and in practice, the timeout can be 400ms or + // more after the expected timeout. + if diff > 500*time.Millisecond { + t.Fatalf("Ended significantly (%v) after deadline", diff) + } +} diff --git a/vendor/gopkg.in/natefinch/npipe.v2/znpipe_windows_386.go b/vendor/gopkg.in/natefinch/npipe.v2/znpipe_windows_386.go new file mode 100644 index 0000000..c283e6c --- /dev/null +++ b/vendor/gopkg.in/natefinch/npipe.v2/znpipe_windows_386.go @@ -0,0 +1,124 @@ +// +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 +} diff --git a/vendor/gopkg.in/natefinch/npipe.v2/znpipe_windows_amd64.go b/vendor/gopkg.in/natefinch/npipe.v2/znpipe_windows_amd64.go new file mode 100644 index 0000000..c283e6c --- /dev/null +++ b/vendor/gopkg.in/natefinch/npipe.v2/znpipe_windows_amd64.go @@ -0,0 +1,124 @@ +// +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 +}