├── .gitignore ├── LICENSE.txt ├── README.md ├── doc.go ├── example_windows_test.go ├── npipe_windows.go ├── npipe_windows_test.go ├── znpipe_windows_386.go └── znpipe_windows_amd64.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2013 npipe authors 3 | 4 | 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: 5 | 6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | 8 | 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 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) 2 | ===== 3 | Package npipe provides a pure Go wrapper around Windows named pipes. 4 | 5 | Windows named pipe documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365780 6 | 7 | Note that the code lives at https://github.com/natefinch/npipe (v2 branch) 8 | but should be imported as gopkg.in/natefinch/npipe.v2 (the package name is 9 | still npipe). 10 | 11 | npipe provides an interface based on stdlib's net package, with Dial, Listen, 12 | and Accept functions, as well as associated implementations of net.Conn and 13 | net.Listener. It supports rpc over the connection. 14 | 15 | ### Notes 16 | * Deadlines for reading/writing to the connection are only functional in Windows Vista/Server 2008 and above, due to limitations with the Windows API. 17 | 18 | * The pipes support byte mode only (no support for message mode) 19 | 20 | ### Examples 21 | The Dial function connects a client to a named pipe: 22 | 23 | 24 | conn, err := npipe.Dial(`\\.\pipe\mypipename`) 25 | if err != nil { 26 | 27 | } 28 | fmt.Fprintf(conn, "Hi server!\n") 29 | msg, err := bufio.NewReader(conn).ReadString('\n') 30 | ... 31 | 32 | The Listen function creates servers: 33 | 34 | 35 | ln, err := npipe.Listen(`\\.\pipe\mypipename`) 36 | if err != nil { 37 | // handle error 38 | } 39 | for { 40 | conn, err := ln.Accept() 41 | if err != nil { 42 | // handle error 43 | continue 44 | } 45 | go handleConnection(conn) 46 | } 47 | 48 | 49 | 50 | 51 | 52 | ## Variables 53 | ``` go 54 | var ErrClosed = PipeError{"Pipe has been closed.", false} 55 | ``` 56 | ErrClosed is the error returned by PipeListener.Accept when Close is called 57 | on the PipeListener. 58 | 59 | 60 | 61 | ## type PipeAddr 62 | ``` go 63 | type PipeAddr string 64 | ``` 65 | PipeAddr represents the address of a named pipe. 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | ### func (PipeAddr) Network 78 | ``` go 79 | func (a PipeAddr) Network() string 80 | ``` 81 | Network returns the address's network name, "pipe". 82 | 83 | 84 | 85 | ### func (PipeAddr) String 86 | ``` go 87 | func (a PipeAddr) String() string 88 | ``` 89 | String returns the address of the pipe 90 | 91 | 92 | 93 | ## type PipeConn 94 | ``` go 95 | type PipeConn struct { 96 | // contains filtered or unexported fields 97 | } 98 | ``` 99 | PipeConn is the implementation of the net.Conn interface for named pipe connections. 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | ### func Dial 110 | ``` go 111 | func Dial(address string) (*PipeConn, error) 112 | ``` 113 | Dial connects to a named pipe with the given address. If the specified pipe is not available, 114 | it will wait indefinitely for the pipe to become available. 115 | 116 | The address must be of the form \\.\\pipe\ for local pipes and \\\pipe\ 117 | for remote pipes. 118 | 119 | Dial will return a PipeError if you pass in a badly formatted pipe name. 120 | 121 | Examples: 122 | 123 | 124 | // local pipe 125 | conn, err := Dial(`\\.\pipe\mypipename`) 126 | 127 | // remote pipe 128 | conn, err := Dial(`\\othercomp\pipe\mypipename`) 129 | 130 | 131 | ### func DialTimeout 132 | ``` go 133 | func DialTimeout(address string, timeout time.Duration) (*PipeConn, error) 134 | ``` 135 | DialTimeout acts like Dial, but will time out after the duration of timeout 136 | 137 | 138 | 139 | 140 | ### func (\*PipeConn) Close 141 | ``` go 142 | func (c *PipeConn) Close() error 143 | ``` 144 | Close closes the connection. 145 | 146 | 147 | 148 | ### func (\*PipeConn) LocalAddr 149 | ``` go 150 | func (c *PipeConn) LocalAddr() net.Addr 151 | ``` 152 | LocalAddr returns the local network address. 153 | 154 | 155 | 156 | ### func (\*PipeConn) Read 157 | ``` go 158 | func (c *PipeConn) Read(b []byte) (int, error) 159 | ``` 160 | Read implements the net.Conn Read method. 161 | 162 | 163 | 164 | ### func (\*PipeConn) RemoteAddr 165 | ``` go 166 | func (c *PipeConn) RemoteAddr() net.Addr 167 | ``` 168 | RemoteAddr returns the remote network address. 169 | 170 | 171 | 172 | ### func (\*PipeConn) SetDeadline 173 | ``` go 174 | func (c *PipeConn) SetDeadline(t time.Time) error 175 | ``` 176 | SetDeadline implements the net.Conn SetDeadline method. 177 | Note that timeouts are only supported on Windows Vista/Server 2008 and above 178 | 179 | 180 | 181 | ### func (\*PipeConn) SetReadDeadline 182 | ``` go 183 | func (c *PipeConn) SetReadDeadline(t time.Time) error 184 | ``` 185 | SetReadDeadline implements the net.Conn SetReadDeadline method. 186 | Note that timeouts are only supported on Windows Vista/Server 2008 and above 187 | 188 | 189 | 190 | ### func (\*PipeConn) SetWriteDeadline 191 | ``` go 192 | func (c *PipeConn) SetWriteDeadline(t time.Time) error 193 | ``` 194 | SetWriteDeadline implements the net.Conn SetWriteDeadline method. 195 | Note that timeouts are only supported on Windows Vista/Server 2008 and above 196 | 197 | 198 | 199 | ### func (\*PipeConn) Write 200 | ``` go 201 | func (c *PipeConn) Write(b []byte) (int, error) 202 | ``` 203 | Write implements the net.Conn Write method. 204 | 205 | 206 | 207 | ## type PipeError 208 | ``` go 209 | type PipeError struct { 210 | // contains filtered or unexported fields 211 | } 212 | ``` 213 | PipeError is an error related to a call to a pipe 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | ### func (PipeError) Error 226 | ``` go 227 | func (e PipeError) Error() string 228 | ``` 229 | Error implements the error interface 230 | 231 | 232 | 233 | ### func (PipeError) Temporary 234 | ``` go 235 | func (e PipeError) Temporary() bool 236 | ``` 237 | Temporary implements net.AddrError.Temporary() 238 | 239 | 240 | 241 | ### func (PipeError) Timeout 242 | ``` go 243 | func (e PipeError) Timeout() bool 244 | ``` 245 | Timeout implements net.AddrError.Timeout() 246 | 247 | 248 | 249 | ## type PipeListener 250 | ``` go 251 | type PipeListener struct { 252 | // contains filtered or unexported fields 253 | } 254 | ``` 255 | PipeListener is a named pipe listener. Clients should typically 256 | use variables of type net.Listener instead of assuming named pipe. 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | ### func Listen 267 | ``` go 268 | func Listen(address string) (*PipeListener, error) 269 | ``` 270 | Listen returns a new PipeListener that will listen on a pipe with the given 271 | address. The address must be of the form \\.\pipe\ 272 | 273 | Listen will return a PipeError for an incorrectly formatted pipe name. 274 | 275 | 276 | 277 | 278 | ### func (\*PipeListener) Accept 279 | ``` go 280 | func (l *PipeListener) Accept() (net.Conn, error) 281 | ``` 282 | Accept implements the Accept method in the net.Listener interface; it 283 | waits for the next call and returns a generic net.Conn. 284 | 285 | 286 | 287 | ### func (\*PipeListener) AcceptPipe 288 | ``` go 289 | func (l *PipeListener) AcceptPipe() (*PipeConn, error) 290 | ``` 291 | AcceptPipe accepts the next incoming call and returns the new connection. 292 | 293 | 294 | 295 | ### func (\*PipeListener) Addr 296 | ``` go 297 | func (l *PipeListener) Addr() net.Addr 298 | ``` 299 | Addr returns the listener's network address, a PipeAddr. 300 | 301 | 302 | 303 | ### func (\*PipeListener) Close 304 | ``` go 305 | func (l *PipeListener) Close() error 306 | ``` 307 | Close stops listening on the address. 308 | Already Accepted connections are not closed. 309 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Nate Finch. All rights reserved. 2 | // Use of this source code is governed by an MIT-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package npipe provides a pure Go wrapper around Windows named pipes. 6 | // 7 | // !! Note, this package is Windows-only. There is no code to compile on linux. 8 | // 9 | // Windows named pipe documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365780 10 | // 11 | // Note that the code lives at https://github.com/natefinch/npipe (v2 branch) 12 | // but should be imported as gopkg.in/natefinch/npipe.v2 (the package name is 13 | // still npipe). 14 | // 15 | // npipe provides an interface based on stdlib's net package, with Dial, Listen, 16 | // and Accept functions, as well as associated implementations of net.Conn and 17 | // net.Listener. It supports rpc over the connection. 18 | // 19 | // Notes 20 | // 21 | // * Deadlines for reading/writing to the connection are only functional in Windows Vista/Server 2008 and above, due to limitations with the Windows API. 22 | // 23 | // * The pipes support byte mode only (no support for message mode) 24 | // 25 | // Examples 26 | // 27 | // The Dial function connects a client to a named pipe: 28 | // conn, err := npipe.Dial(`\\.\pipe\mypipename`) 29 | // if err != nil { 30 | // 31 | // } 32 | // fmt.Fprintf(conn, "Hi server!\n") 33 | // msg, err := bufio.NewReader(conn).ReadString('\n') 34 | // ... 35 | // 36 | // The Listen function creates servers: 37 | // 38 | // ln, err := npipe.Listen(`\\.\pipe\mypipename`) 39 | // if err != nil { 40 | // // handle error 41 | // } 42 | // for { 43 | // conn, err := ln.Accept() 44 | // if err != nil { 45 | // // handle error 46 | // continue 47 | // } 48 | // go handleConnection(conn) 49 | // } 50 | package npipe 51 | -------------------------------------------------------------------------------- /example_windows_test.go: -------------------------------------------------------------------------------- 1 | package npipe_test 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "net" 7 | 8 | "gopkg.in/natefinch/npipe.v2" 9 | ) 10 | 11 | // Use Dial to connect to a server and read messages from it. 12 | func ExampleDial() { 13 | conn, err := npipe.Dial(`\\.\pipe\mypipe`) 14 | if err != nil { 15 | // handle error 16 | } 17 | if _, err := fmt.Fprintln(conn, "Hi server!"); err != nil { 18 | // handle error 19 | } 20 | r := bufio.NewReader(conn) 21 | msg, err := r.ReadString('\n') 22 | if err != nil { 23 | // handle eror 24 | } 25 | fmt.Println(msg) 26 | } 27 | 28 | // Use Listen to start a server, and accept connections with Accept(). 29 | func ExampleListen() { 30 | ln, err := npipe.Listen(`\\.\pipe\mypipe`) 31 | if err != nil { 32 | // handle error 33 | } 34 | 35 | for { 36 | conn, err := ln.Accept() 37 | if err != nil { 38 | // handle error 39 | continue 40 | } 41 | 42 | // handle connection like any other net.Conn 43 | go func(conn net.Conn) { 44 | r := bufio.NewReader(conn) 45 | msg, err := r.ReadString('\n') 46 | if err != nil { 47 | // handle error 48 | return 49 | } 50 | fmt.Println(msg) 51 | }(conn) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /npipe_windows.go: -------------------------------------------------------------------------------- 1 | package npipe 2 | 3 | //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 4 | //sys connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) = ConnectNamedPipe 5 | //sys disconnectNamedPipe(handle syscall.Handle) (err error) = DisconnectNamedPipe 6 | //sys waitNamedPipe(name *uint16, timeout uint32) (err error) = WaitNamedPipeW 7 | //sys createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateEventW 8 | //sys getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) = GetOverlappedResult 9 | //sys cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) = CancelIoEx 10 | 11 | import ( 12 | "fmt" 13 | "io" 14 | "net" 15 | "sync" 16 | "syscall" 17 | "time" 18 | ) 19 | 20 | const ( 21 | // openMode 22 | pipe_access_duplex = 0x3 23 | pipe_access_inbound = 0x1 24 | pipe_access_outbound = 0x2 25 | 26 | // openMode write flags 27 | file_flag_first_pipe_instance = 0x00080000 28 | file_flag_write_through = 0x80000000 29 | file_flag_overlapped = 0x40000000 30 | 31 | // openMode ACL flags 32 | write_dac = 0x00040000 33 | write_owner = 0x00080000 34 | access_system_security = 0x01000000 35 | 36 | // pipeMode 37 | pipe_type_byte = 0x0 38 | pipe_type_message = 0x4 39 | 40 | // pipeMode read mode flags 41 | pipe_readmode_byte = 0x0 42 | pipe_readmode_message = 0x2 43 | 44 | // pipeMode wait mode flags 45 | pipe_wait = 0x0 46 | pipe_nowait = 0x1 47 | 48 | // pipeMode remote-client mode flags 49 | pipe_accept_remote_clients = 0x0 50 | pipe_reject_remote_clients = 0x8 51 | 52 | pipe_unlimited_instances = 255 53 | 54 | nmpwait_wait_forever = 0xFFFFFFFF 55 | 56 | // the two not-an-errors below occur if a client connects to the pipe between 57 | // the server's CreateNamedPipe and ConnectNamedPipe calls. 58 | error_no_data syscall.Errno = 0xE8 59 | error_pipe_connected syscall.Errno = 0x217 60 | error_pipe_busy syscall.Errno = 0xE7 61 | error_sem_timeout syscall.Errno = 0x79 62 | 63 | error_bad_pathname syscall.Errno = 0xA1 64 | error_invalid_name syscall.Errno = 0x7B 65 | 66 | error_io_incomplete syscall.Errno = 0x3e4 67 | ) 68 | 69 | var _ net.Conn = (*PipeConn)(nil) 70 | var _ net.Listener = (*PipeListener)(nil) 71 | 72 | // ErrClosed is the error returned by PipeListener.Accept when Close is called 73 | // on the PipeListener. 74 | var ErrClosed = PipeError{"Pipe has been closed.", false} 75 | 76 | // PipeError is an error related to a call to a pipe 77 | type PipeError struct { 78 | msg string 79 | timeout bool 80 | } 81 | 82 | // Error implements the error interface 83 | func (e PipeError) Error() string { 84 | return e.msg 85 | } 86 | 87 | // Timeout implements net.AddrError.Timeout() 88 | func (e PipeError) Timeout() bool { 89 | return e.timeout 90 | } 91 | 92 | // Temporary implements net.AddrError.Temporary() 93 | func (e PipeError) Temporary() bool { 94 | return false 95 | } 96 | 97 | // Dial connects to a named pipe with the given address. If the specified pipe is not available, 98 | // it will wait indefinitely for the pipe to become available. 99 | // 100 | // The address must be of the form \\.\\pipe\ for local pipes and \\\pipe\ 101 | // for remote pipes. 102 | // 103 | // Dial will return a PipeError if you pass in a badly formatted pipe name. 104 | // 105 | // Examples: 106 | // // local pipe 107 | // conn, err := Dial(`\\.\pipe\mypipename`) 108 | // 109 | // // remote pipe 110 | // conn, err := Dial(`\\othercomp\pipe\mypipename`) 111 | func Dial(address string) (*PipeConn, error) { 112 | for { 113 | conn, err := dial(address, nmpwait_wait_forever) 114 | if err == nil { 115 | return conn, nil 116 | } 117 | if isPipeNotReady(err) { 118 | <-time.After(100 * time.Millisecond) 119 | continue 120 | } 121 | return nil, err 122 | } 123 | } 124 | 125 | // DialTimeout acts like Dial, but will time out after the duration of timeout 126 | func DialTimeout(address string, timeout time.Duration) (*PipeConn, error) { 127 | deadline := time.Now().Add(timeout) 128 | 129 | now := time.Now() 130 | for now.Before(deadline) { 131 | millis := uint32(deadline.Sub(now) / time.Millisecond) 132 | conn, err := dial(address, millis) 133 | if err == nil { 134 | return conn, nil 135 | } 136 | if err == error_sem_timeout { 137 | // This is WaitNamedPipe's timeout error, so we know we're done 138 | return nil, PipeError{fmt.Sprintf( 139 | "Timed out waiting for pipe '%s' to come available", address), true} 140 | } 141 | if isPipeNotReady(err) { 142 | left := deadline.Sub(time.Now()) 143 | retry := 100 * time.Millisecond 144 | if left > retry { 145 | <-time.After(retry) 146 | } else { 147 | <-time.After(left - time.Millisecond) 148 | } 149 | now = time.Now() 150 | continue 151 | } 152 | return nil, err 153 | } 154 | return nil, PipeError{fmt.Sprintf( 155 | "Timed out waiting for pipe '%s' to come available", address), true} 156 | } 157 | 158 | // isPipeNotReady checks the error to see if it indicates the pipe is not ready 159 | func isPipeNotReady(err error) bool { 160 | // Pipe Busy means another client just grabbed the open pipe end, 161 | // and the server hasn't made a new one yet. 162 | // File Not Found means the server hasn't created the pipe yet. 163 | // Neither is a fatal error. 164 | 165 | return err == syscall.ERROR_FILE_NOT_FOUND || err == error_pipe_busy 166 | } 167 | 168 | // newOverlapped creates a structure used to track asynchronous 169 | // I/O requests that have been issued. 170 | func newOverlapped() (*syscall.Overlapped, error) { 171 | event, err := createEvent(nil, true, true, nil) 172 | if err != nil { 173 | return nil, err 174 | } 175 | return &syscall.Overlapped{HEvent: event}, nil 176 | } 177 | 178 | // waitForCompletion waits for an asynchronous I/O request referred to by overlapped to complete. 179 | // This function returns the number of bytes transferred by the operation and an error code if 180 | // applicable (nil otherwise). 181 | func waitForCompletion(handle syscall.Handle, overlapped *syscall.Overlapped) (uint32, error) { 182 | _, err := syscall.WaitForSingleObject(overlapped.HEvent, syscall.INFINITE) 183 | if err != nil { 184 | return 0, err 185 | } 186 | var transferred uint32 187 | err = getOverlappedResult(handle, overlapped, &transferred, true) 188 | return transferred, err 189 | } 190 | 191 | // dial is a helper to initiate a connection to a named pipe that has been started by a server. 192 | // The timeout is only enforced if the pipe server has already created the pipe, otherwise 193 | // this function will return immediately. 194 | func dial(address string, timeout uint32) (*PipeConn, error) { 195 | name, err := syscall.UTF16PtrFromString(string(address)) 196 | if err != nil { 197 | return nil, err 198 | } 199 | // If at least one instance of the pipe has been created, this function 200 | // will wait timeout milliseconds for it to become available. 201 | // It will return immediately regardless of timeout, if no instances 202 | // of the named pipe have been created yet. 203 | // If this returns with no error, there is a pipe available. 204 | if err := waitNamedPipe(name, timeout); err != nil { 205 | if err == error_bad_pathname { 206 | // badly formatted pipe name 207 | return nil, badAddr(address) 208 | } 209 | return nil, err 210 | } 211 | pathp, err := syscall.UTF16PtrFromString(address) 212 | if err != nil { 213 | return nil, err 214 | } 215 | handle, err := syscall.CreateFile(pathp, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 216 | uint32(syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE), nil, syscall.OPEN_EXISTING, 217 | syscall.FILE_FLAG_OVERLAPPED, 0) 218 | if err != nil { 219 | return nil, err 220 | } 221 | return &PipeConn{handle: handle, addr: PipeAddr(address)}, nil 222 | } 223 | 224 | // Listen returns a new PipeListener that will listen on a pipe with the given 225 | // address. The address must be of the form \\.\pipe\ 226 | // 227 | // Listen will return a PipeError for an incorrectly formatted pipe name. 228 | func Listen(address string) (*PipeListener, error) { 229 | handle, err := createPipe(address, true) 230 | if err == error_invalid_name { 231 | return nil, badAddr(address) 232 | } 233 | if err != nil { 234 | return nil, err 235 | } 236 | 237 | return &PipeListener{ 238 | addr: PipeAddr(address), 239 | handle: handle, 240 | }, nil 241 | } 242 | 243 | // PipeListener is a named pipe listener. Clients should typically 244 | // use variables of type net.Listener instead of assuming named pipe. 245 | type PipeListener struct { 246 | mu sync.Mutex 247 | 248 | addr PipeAddr 249 | handle syscall.Handle 250 | closed bool 251 | 252 | // acceptHandle contains the current handle waiting for 253 | // an incoming connection or nil. 254 | acceptHandle syscall.Handle 255 | // acceptOverlapped is set before waiting on a connection. 256 | // If not waiting, it is nil. 257 | acceptOverlapped *syscall.Overlapped 258 | } 259 | 260 | // Accept implements the Accept method in the net.Listener interface; it 261 | // waits for the next call and returns a generic net.Conn. 262 | func (l *PipeListener) Accept() (net.Conn, error) { 263 | c, err := l.AcceptPipe() 264 | for err == error_no_data { 265 | // Ignore clients that connect and immediately disconnect. 266 | c, err = l.AcceptPipe() 267 | } 268 | if err != nil { 269 | return nil, err 270 | } 271 | return c, nil 272 | } 273 | 274 | // AcceptPipe accepts the next incoming call and returns the new connection. 275 | // It might return an error if a client connected and immediately cancelled 276 | // the connection. 277 | func (l *PipeListener) AcceptPipe() (*PipeConn, error) { 278 | if l == nil { 279 | return nil, syscall.EINVAL 280 | } 281 | 282 | l.mu.Lock() 283 | defer l.mu.Unlock() 284 | 285 | if l.addr == "" || l.closed { 286 | return nil, syscall.EINVAL 287 | } 288 | 289 | // the first time we call accept, the handle will have been created by the Listen 290 | // call. This is to prevent race conditions where the client thinks the server 291 | // isn't listening because it hasn't actually called create yet. After the first time, we'll 292 | // have to create a new handle each time 293 | handle := l.handle 294 | if handle == 0 { 295 | var err error 296 | handle, err = createPipe(string(l.addr), false) 297 | if err != nil { 298 | return nil, err 299 | } 300 | } else { 301 | l.handle = 0 302 | } 303 | 304 | overlapped, err := newOverlapped() 305 | if err != nil { 306 | return nil, err 307 | } 308 | defer syscall.CloseHandle(overlapped.HEvent) 309 | err = connectNamedPipe(handle, overlapped) 310 | if err == nil || err == error_pipe_connected { 311 | return &PipeConn{handle: handle, addr: l.addr}, nil 312 | } 313 | 314 | if err == error_io_incomplete || err == syscall.ERROR_IO_PENDING { 315 | l.acceptOverlapped = overlapped 316 | l.acceptHandle = handle 317 | // unlock here so close can function correctly while we wait (we'll 318 | // get relocked via the defer below, before the original defer 319 | // unlock happens.) 320 | l.mu.Unlock() 321 | defer func() { 322 | l.mu.Lock() 323 | l.acceptOverlapped = nil 324 | l.acceptHandle = 0 325 | // unlock is via defer above. 326 | }() 327 | _, err = waitForCompletion(handle, overlapped) 328 | } 329 | if err == syscall.ERROR_OPERATION_ABORTED { 330 | // Return error compatible to net.Listener.Accept() in case the 331 | // listener was closed. 332 | return nil, ErrClosed 333 | } 334 | if err != nil { 335 | return nil, err 336 | } 337 | return &PipeConn{handle: handle, addr: l.addr}, nil 338 | } 339 | 340 | // Close stops listening on the address. 341 | // Already Accepted connections are not closed. 342 | func (l *PipeListener) Close() error { 343 | l.mu.Lock() 344 | defer l.mu.Unlock() 345 | 346 | if l.closed { 347 | return nil 348 | } 349 | l.closed = true 350 | if l.handle != 0 { 351 | err := disconnectNamedPipe(l.handle) 352 | if err != nil { 353 | return err 354 | } 355 | err = syscall.CloseHandle(l.handle) 356 | if err != nil { 357 | return err 358 | } 359 | l.handle = 0 360 | } 361 | if l.acceptOverlapped != nil && l.acceptHandle != 0 { 362 | // Cancel the pending IO. This call does not block, so it is safe 363 | // to hold onto the mutex above. 364 | if err := cancelIoEx(l.acceptHandle, l.acceptOverlapped); err != nil { 365 | return err 366 | } 367 | err := syscall.CloseHandle(l.acceptOverlapped.HEvent) 368 | if err != nil { 369 | return err 370 | } 371 | l.acceptOverlapped.HEvent = 0 372 | err = syscall.CloseHandle(l.acceptHandle) 373 | if err != nil { 374 | return err 375 | } 376 | l.acceptHandle = 0 377 | } 378 | return nil 379 | } 380 | 381 | // Addr returns the listener's network address, a PipeAddr. 382 | func (l *PipeListener) Addr() net.Addr { return l.addr } 383 | 384 | // PipeConn is the implementation of the net.Conn interface for named pipe connections. 385 | type PipeConn struct { 386 | handle syscall.Handle 387 | addr PipeAddr 388 | 389 | // these aren't actually used yet 390 | readDeadline *time.Time 391 | writeDeadline *time.Time 392 | } 393 | 394 | type iodata struct { 395 | n uint32 396 | err error 397 | } 398 | 399 | // completeRequest looks at iodata to see if a request is pending. If so, it waits for it to either complete or to 400 | // abort due to hitting the specified deadline. Deadline may be set to nil to wait forever. If no request is pending, 401 | // the content of iodata is returned. 402 | func (c *PipeConn) completeRequest(data iodata, deadline *time.Time, overlapped *syscall.Overlapped) (int, error) { 403 | if data.err == error_io_incomplete || data.err == syscall.ERROR_IO_PENDING { 404 | var timer <-chan time.Time 405 | if deadline != nil { 406 | if timeDiff := deadline.Sub(time.Now()); timeDiff > 0 { 407 | timer = time.After(timeDiff) 408 | } 409 | } 410 | done := make(chan iodata) 411 | go func() { 412 | n, err := waitForCompletion(c.handle, overlapped) 413 | done <- iodata{n, err} 414 | }() 415 | select { 416 | case data = <-done: 417 | case <-timer: 418 | syscall.CancelIoEx(c.handle, overlapped) 419 | data = iodata{0, timeout(c.addr.String())} 420 | } 421 | } 422 | // Windows will produce ERROR_BROKEN_PIPE upon closing 423 | // a handle on the other end of a connection. Go RPC 424 | // expects an io.EOF error in this case. 425 | if data.err == syscall.ERROR_BROKEN_PIPE { 426 | data.err = io.EOF 427 | } 428 | return int(data.n), data.err 429 | } 430 | 431 | // Read implements the net.Conn Read method. 432 | func (c *PipeConn) Read(b []byte) (int, error) { 433 | // Use ReadFile() rather than Read() because the latter 434 | // contains a workaround that eats ERROR_BROKEN_PIPE. 435 | overlapped, err := newOverlapped() 436 | if err != nil { 437 | return 0, err 438 | } 439 | defer syscall.CloseHandle(overlapped.HEvent) 440 | var n uint32 441 | err = syscall.ReadFile(c.handle, b, &n, overlapped) 442 | return c.completeRequest(iodata{n, err}, c.readDeadline, overlapped) 443 | } 444 | 445 | // Write implements the net.Conn Write method. 446 | func (c *PipeConn) Write(b []byte) (int, error) { 447 | overlapped, err := newOverlapped() 448 | if err != nil { 449 | return 0, err 450 | } 451 | defer syscall.CloseHandle(overlapped.HEvent) 452 | var n uint32 453 | err = syscall.WriteFile(c.handle, b, &n, overlapped) 454 | return c.completeRequest(iodata{n, err}, c.writeDeadline, overlapped) 455 | } 456 | 457 | // Close closes the connection. 458 | func (c *PipeConn) Close() error { 459 | return syscall.CloseHandle(c.handle) 460 | } 461 | 462 | // LocalAddr returns the local network address. 463 | func (c *PipeConn) LocalAddr() net.Addr { 464 | return c.addr 465 | } 466 | 467 | // RemoteAddr returns the remote network address. 468 | func (c *PipeConn) RemoteAddr() net.Addr { 469 | // not sure what to do here, we don't have remote addr.... 470 | return c.addr 471 | } 472 | 473 | // SetDeadline implements the net.Conn SetDeadline method. 474 | // Note that timeouts are only supported on Windows Vista/Server 2008 and above 475 | func (c *PipeConn) SetDeadline(t time.Time) error { 476 | c.SetReadDeadline(t) 477 | c.SetWriteDeadline(t) 478 | return nil 479 | } 480 | 481 | // SetReadDeadline implements the net.Conn SetReadDeadline method. 482 | // Note that timeouts are only supported on Windows Vista/Server 2008 and above 483 | func (c *PipeConn) SetReadDeadline(t time.Time) error { 484 | c.readDeadline = &t 485 | return nil 486 | } 487 | 488 | // SetWriteDeadline implements the net.Conn SetWriteDeadline method. 489 | // Note that timeouts are only supported on Windows Vista/Server 2008 and above 490 | func (c *PipeConn) SetWriteDeadline(t time.Time) error { 491 | c.writeDeadline = &t 492 | return nil 493 | } 494 | 495 | // PipeAddr represents the address of a named pipe. 496 | type PipeAddr string 497 | 498 | // Network returns the address's network name, "pipe". 499 | func (a PipeAddr) Network() string { return "pipe" } 500 | 501 | // String returns the address of the pipe 502 | func (a PipeAddr) String() string { 503 | return string(a) 504 | } 505 | 506 | // createPipe is a helper function to make sure we always create pipes 507 | // with the same arguments, since subsequent calls to create pipe need 508 | // to use the same arguments as the first one. If first is set, fail 509 | // if the pipe already exists. 510 | func createPipe(address string, first bool) (syscall.Handle, error) { 511 | n, err := syscall.UTF16PtrFromString(address) 512 | if err != nil { 513 | return 0, err 514 | } 515 | mode := uint32(pipe_access_duplex | syscall.FILE_FLAG_OVERLAPPED) 516 | if first { 517 | mode |= file_flag_first_pipe_instance 518 | } 519 | return createNamedPipe(n, 520 | mode, 521 | pipe_type_byte, 522 | pipe_unlimited_instances, 523 | 512, 512, 0, nil) 524 | } 525 | 526 | func badAddr(addr string) PipeError { 527 | return PipeError{fmt.Sprintf("Invalid pipe address '%s'.", addr), false} 528 | } 529 | func timeout(addr string) PipeError { 530 | return PipeError{fmt.Sprintf("Pipe IO timed out waiting for '%s'", addr), true} 531 | } 532 | -------------------------------------------------------------------------------- /npipe_windows_test.go: -------------------------------------------------------------------------------- 1 | package npipe 2 | 3 | import ( 4 | "bufio" 5 | "crypto/rand" 6 | "fmt" 7 | "io" 8 | "io/ioutil" 9 | "net" 10 | "net/rpc" 11 | "os" 12 | "path/filepath" 13 | "sync" 14 | "testing" 15 | "time" 16 | ) 17 | 18 | const ( 19 | clientMsg = "Hi server!\n" 20 | serverMsg = "Hi there, client!\n" 21 | fileTemplate = "62DA0493-99A1-4327-B5A8-6C4E4466C3FC.txt" 22 | ) 23 | 24 | // TestBadDial tests that if you dial something other than a valid pipe path, that you get back a 25 | // PipeError and that you don't accidently create a file on disk (since dial uses OpenFile) 26 | func TestBadDial(t *testing.T) { 27 | fn := filepath.Join("C:\\", fileTemplate) 28 | ns := []string{fn, "http://www.google.com", "somethingbadhere"} 29 | for _, n := range ns { 30 | c, err := Dial(n) 31 | if _, ok := err.(PipeError); !ok { 32 | t.Errorf("Dialing '%s' did not result in correct error! Expected PipeError, got '%v'", 33 | n, err) 34 | } 35 | if c != nil { 36 | t.Errorf("Dialing '%s' returned non-nil connection", n) 37 | } 38 | if b, _ := exists(n); b { 39 | t.Errorf("Dialing '%s' incorrectly created file on disk", n) 40 | } 41 | } 42 | } 43 | 44 | // TestDialExistingFile tests that if you dial with the name of an existing file, 45 | // that you don't accidentally open the file (since dial uses OpenFile) 46 | func TestDialExistingFile(t *testing.T) { 47 | tempdir := os.TempDir() 48 | fn := filepath.Join(tempdir, fileTemplate) 49 | if f, err := os.Create(fn); err != nil { 50 | t.Fatalf("Unexpected error creating file '%s': '%v'", fn, err) 51 | } else { 52 | // we don't actually need to write to the file, just need it to exist 53 | f.Close() 54 | defer os.Remove(fn) 55 | } 56 | c, err := Dial(fn) 57 | if _, ok := err.(PipeError); !ok { 58 | t.Errorf("Dialing '%s' did not result in error! Expected PipeError, got '%v'", fn, err) 59 | } 60 | if c != nil { 61 | t.Errorf("Dialing '%s' returned non-nil connection", fn) 62 | } 63 | } 64 | 65 | // TestBadListen tests that if you listen on a bad address, that we get back a PipeError 66 | func TestBadListen(t *testing.T) { 67 | addrs := []string{"not a valid pipe address", `\\127.0.0.1\pipe\TestBadListen`} 68 | for _, address := range addrs { 69 | ln, err := Listen(address) 70 | if _, ok := err.(PipeError); !ok { 71 | t.Errorf("Listening on '%s' did not result in correct error! Expected PipeError, got '%v'", 72 | address, err) 73 | } 74 | if ln != nil { 75 | t.Errorf("Listening on '%s' returned non-nil listener.", address) 76 | } 77 | } 78 | } 79 | 80 | // TestDoubleListen makes sure we can't listen to the same address twice. 81 | func TestDoubleListen(t *testing.T) { 82 | address := `\\.\pipe\TestDoubleListen` 83 | ln1, err := Listen(address) 84 | if err != nil { 85 | t.Fatalf("Listen(%q): %v", address, err) 86 | } 87 | defer ln1.Close() 88 | 89 | ln2, err := Listen(address) 90 | if err == nil { 91 | ln2.Close() 92 | t.Fatalf("second Listen on %q succeeded.", address) 93 | } 94 | } 95 | 96 | // TestPipeConnected tests whether we correctly handle clients connecting 97 | // and then closing the connection between creating and connecting the 98 | // pipe on the server side. 99 | func TestPipeConnected(t *testing.T) { 100 | address := `\\.\pipe\TestPipeConnected` 101 | ln, err := Listen(address) 102 | if err != nil { 103 | t.Fatalf("Listen(%q): %v", address, err) 104 | } 105 | defer ln.Close() 106 | 107 | // Create a client connection and close it immediately. 108 | clientConn, err := Dial(address) 109 | if err != nil { 110 | t.Fatalf("Error from dial: %v", err) 111 | } 112 | clientConn.Close() 113 | 114 | content := "test" 115 | go func() { 116 | // Now create a real connection and send some data. 117 | clientConn, err := Dial(address) 118 | if err != nil { 119 | t.Fatalf("Error from dial: %v", err) 120 | } 121 | if _, err := clientConn.Write([]byte(content)); err != nil { 122 | t.Fatalf("Error writing to pipe: %v", err) 123 | } 124 | clientConn.Close() 125 | }() 126 | 127 | serverConn, err := ln.Accept() 128 | if err != nil { 129 | t.Fatalf("Error from accept: %v", err) 130 | } 131 | result, err := ioutil.ReadAll(serverConn) 132 | if err != nil { 133 | t.Fatalf("Error from ReadAll: %v", err) 134 | } 135 | if string(result) != content { 136 | t.Fatalf("Got %s, expected: %s", string(result), content) 137 | } 138 | serverConn.Close() 139 | } 140 | 141 | // TestListenCloseListen tests whether Close() actually closes a named pipe properly. 142 | func TestListenCloseListen(t *testing.T) { 143 | address := `\\.\pipe\TestListenCloseListen` 144 | ln1, err := Listen(address) 145 | if err != nil { 146 | t.Fatalf("Listen(%q): %v", address, err) 147 | } 148 | ln1.Close() 149 | 150 | ln2, err := Listen(address) 151 | if err != nil { 152 | t.Fatalf("second Listen on %q failed.", address) 153 | } 154 | ln2.Close() 155 | } 156 | 157 | // TestCloseFileHandles tests that all PipeListener handles are actualy closed after 158 | // calling Close() 159 | func TestCloseFileHandles(t *testing.T) { 160 | address := `\\.\pipe\TestCloseFileHandles` 161 | ln, err := Listen(address) 162 | if err != nil { 163 | t.Fatalf("Error listening on %q: %v", address, err) 164 | } 165 | defer ln.Close() 166 | server := rpc.NewServer() 167 | service := &RPCService{} 168 | server.Register(service) 169 | go func() { 170 | for { 171 | conn, err := ln.Accept() 172 | if err != nil { 173 | // Ignore errors produced by a closed listener. 174 | if err != ErrClosed { 175 | t.Errorf("ln.Accept(): %v", err.Error()) 176 | } 177 | break 178 | } 179 | go server.ServeConn(conn) 180 | } 181 | }() 182 | conn, err := Dial(address) 183 | if err != nil { 184 | t.Fatalf("Error dialing %q: %v", address, err) 185 | } 186 | client := rpc.NewClient(conn) 187 | defer client.Close() 188 | req := "dummy" 189 | resp := "" 190 | if err = client.Call("RPCService.GetResponse", req, &resp); err != nil { 191 | t.Fatalf("Error calling RPCService.GetResponse: %v", err) 192 | } 193 | if req != resp { 194 | t.Fatalf("Unexpected result (expected: %q, got: %q)", req, resp) 195 | } 196 | ln.Close() 197 | 198 | if ln.acceptHandle != 0 { 199 | t.Fatalf("Failed to close acceptHandle") 200 | } 201 | if ln.acceptOverlapped.HEvent != 0 { 202 | t.Fatalf("Failed to close acceptOverlapped handle") 203 | } 204 | } 205 | 206 | // TestCancelListen tests whether Accept() can be cancelled by closing the listener. 207 | func TestCancelAccept(t *testing.T) { 208 | address := `\\.\pipe\TestCancelListener` 209 | ln, err := Listen(address) 210 | if err != nil { 211 | t.Fatalf("Listen(%q): %v", address, err) 212 | } 213 | 214 | cancelled := make(chan struct{}) 215 | started := make(chan struct{}) 216 | go func() { 217 | close(started) 218 | conn, _ := ln.Accept() 219 | if conn != nil { 220 | t.Fatalf("Unexpected incoming connection: %v", conn) 221 | conn.Close() 222 | } 223 | cancelled <- struct{}{} 224 | }() 225 | <-started 226 | // Close listener after 20ms. This should give the go routine enough time to be actually 227 | // waiting for incoming connections inside ln.Accept(). 228 | time.AfterFunc(20*time.Millisecond, func() { 229 | if err := ln.Close(); err != nil { 230 | t.Fatalf("Error closing listener: %v", err) 231 | } 232 | }) 233 | // Any Close() should abort the ln.Accept() call within 100ms. 234 | // We fail with a timeout otherwise, to avoid blocking forever on a failing test. 235 | timeout := time.After(100 * time.Millisecond) 236 | select { 237 | case <-cancelled: 238 | // This is what should happen. 239 | case <-timeout: 240 | t.Fatal("Timeout trying to cancel accept.") 241 | } 242 | } 243 | 244 | // Test that PipeConn's read deadline works correctly 245 | func TestReadDeadline(t *testing.T) { 246 | address := `\\.\pipe\TestReadDeadline` 247 | var wg sync.WaitGroup 248 | wg.Add(1) 249 | 250 | go listenAndWait(address, wg, t) 251 | defer wg.Done() 252 | 253 | c, err := Dial(address) 254 | if err != nil { 255 | t.Fatalf("Error dialing into pipe: %v", err) 256 | } 257 | if c == nil { 258 | t.Fatal("Unexpected nil connection from Dial") 259 | } 260 | defer c.Close() 261 | deadline := time.Now().Add(time.Millisecond * 50) 262 | c.SetReadDeadline(deadline) 263 | msg, err := bufio.NewReader(c).ReadString('\n') 264 | end := time.Now() 265 | if msg != "" { 266 | t.Errorf("Pipe read timeout returned a non-empty message: %s", msg) 267 | } 268 | if err == nil { 269 | t.Error("Pipe read timeout returned nil error") 270 | } else { 271 | pe, ok := err.(PipeError) 272 | if !ok { 273 | t.Errorf("Got wrong error returned, expected PipeError, got '%t'", err) 274 | } 275 | if !pe.Timeout() { 276 | t.Error("Pipe read timeout didn't return an error indicating the timeout") 277 | } 278 | } 279 | checkDeadline(deadline, end, t) 280 | } 281 | 282 | // listenAndWait simply sets up a pipe listener that does nothing and closes after the waitgroup 283 | // is done. 284 | func listenAndWait(address string, wg sync.WaitGroup, t *testing.T) { 285 | ln, err := Listen(address) 286 | if err != nil { 287 | t.Fatalf("Error starting to listen on pipe: %v", err) 288 | } 289 | if ln == nil { 290 | t.Fatal("Got unexpected nil listener") 291 | } 292 | conn, err := ln.Accept() 293 | if err != nil { 294 | t.Fatalf("Error accepting connection: %v", err) 295 | } 296 | if conn == nil { 297 | t.Fatal("Got unexpected nil connection") 298 | } 299 | defer conn.Close() 300 | // don't read or write anything 301 | wg.Wait() 302 | } 303 | 304 | // TestWriteDeadline tests that PipeConn's write deadline works correctly 305 | func TestWriteDeadline(t *testing.T) { 306 | address := `\\.\pipe\TestWriteDeadline` 307 | var wg sync.WaitGroup 308 | wg.Add(1) 309 | 310 | go listenAndWait(address, wg, t) 311 | defer wg.Done() 312 | c, err := Dial(address) 313 | if err != nil { 314 | t.Fatalf("Error dialing into pipe: %v", err) 315 | } 316 | if c == nil { 317 | t.Fatal("Unexpected nil connection from Dial") 318 | } 319 | 320 | // windows pipes have a buffer, so even if we don't read from the pipe, 321 | // the write may succeed anyway, so we have to write a whole bunch to 322 | // test the time out 323 | deadline := time.Now().Add(time.Millisecond * 50) 324 | c.SetWriteDeadline(deadline) 325 | buffer := make([]byte, 1<<16) 326 | if _, err = io.ReadFull(rand.Reader, buffer); err != nil { 327 | t.Fatalf("Couldn't generate random buffer: %v", err) 328 | } 329 | _, err = c.Write(buffer) 330 | 331 | end := time.Now() 332 | 333 | if err == nil { 334 | t.Error("Pipe write timeout returned nil error") 335 | } else { 336 | pe, ok := err.(PipeError) 337 | if !ok { 338 | t.Errorf("Got wrong error returned, expected PipeError, got '%t'", err) 339 | } 340 | if !pe.Timeout() { 341 | t.Error("Pipe write timeout didn't return an error indicating the timeout") 342 | } 343 | } 344 | checkDeadline(deadline, end, t) 345 | } 346 | 347 | // TestDialTimeout tests that the DialTimeout function will actually timeout correctly 348 | func TestDialTimeout(t *testing.T) { 349 | timeout := time.Millisecond * 150 350 | deadline := time.Now().Add(timeout) 351 | c, err := DialTimeout(`\\.\pipe\TestDialTimeout`, timeout) 352 | end := time.Now() 353 | if c != nil { 354 | t.Errorf("DialTimeout returned non-nil connection: %v", c) 355 | } 356 | if err == nil { 357 | t.Error("DialTimeout returned nil error after timeout") 358 | } else { 359 | pe, ok := err.(PipeError) 360 | if !ok { 361 | t.Errorf("Got wrong error returned, expected PipeError, got '%t'", err) 362 | } 363 | if !pe.Timeout() { 364 | t.Error("Dial timeout didn't return an error indicating the timeout") 365 | } 366 | } 367 | checkDeadline(deadline, end, t) 368 | } 369 | 370 | // TestDialNoTimeout tests that the DialTimeout function will properly wait for the pipe and 371 | // connect when it is available 372 | func TestDialNoTimeout(t *testing.T) { 373 | timeout := time.Millisecond * 500 374 | address := `\\.\pipe\TestDialNoTimeout` 375 | go func() { 376 | <-time.After(50 * time.Millisecond) 377 | listenAndClose(address, t) 378 | }() 379 | 380 | deadline := time.Now().Add(timeout) 381 | c, err := DialTimeout(address, timeout) 382 | end := time.Now() 383 | 384 | if c == nil { 385 | t.Error("DialTimeout returned unexpected nil connection") 386 | } 387 | if err != nil { 388 | t.Error("DialTimeout returned unexpected non-nil error: ", err) 389 | } 390 | if end.After(deadline) { 391 | t.Fatalf("Ended %v after deadline", end.Sub(deadline)) 392 | } 393 | } 394 | 395 | // TestDial tests that you can dial before a pipe is available, 396 | // and that it'll pick up the pipe once it's ready 397 | func TestDial(t *testing.T) { 398 | address := `\\.\pipe\TestDial` 399 | var wg sync.WaitGroup 400 | wg.Add(1) 401 | go func() { 402 | wg.Done() 403 | conn, err := Dial(address) 404 | if err != nil { 405 | t.Fatalf("Got unexpected error from Dial: %v", err) 406 | } 407 | if conn == nil { 408 | t.Fatal("Got unexpected nil connection from Dial") 409 | } 410 | if err := conn.Close(); err != nil { 411 | t.Fatalf("Got unexpected error from conection.Close(): %v", err) 412 | } 413 | }() 414 | 415 | wg.Wait() 416 | <-time.After(50 * time.Millisecond) 417 | listenAndClose(address, t) 418 | } 419 | 420 | type RPCService struct{} 421 | 422 | func (s *RPCService) GetResponse(request string, response *string) error { 423 | *response = request 424 | return nil 425 | } 426 | 427 | // TestGoRPC tests that you can run go RPC over the pipe, 428 | // and that overlapping bi-directional communication is working 429 | // (write while a blocking read is in progress). 430 | func TestGoRPC(t *testing.T) { 431 | address := `\\.\pipe\TestRPC` 432 | ln, err := Listen(address) 433 | if err != nil { 434 | t.Fatalf("Error listening on %q: %v", address, err) 435 | } 436 | waitExit := make(chan struct{}) 437 | defer func() { 438 | ln.Close() 439 | <-waitExit 440 | }() 441 | 442 | go func() { 443 | server := rpc.NewServer() 444 | server.Register(&RPCService{}) 445 | for { 446 | conn, err := ln.Accept() 447 | if err != nil { 448 | // Ignore errors produced by a closed listener. 449 | if err != ErrClosed { 450 | t.Errorf("ln.Accept(): %v", err.Error()) 451 | } 452 | break 453 | } 454 | go server.ServeConn(conn) 455 | } 456 | close(waitExit) 457 | }() 458 | conn, err := Dial(address) 459 | if err != nil { 460 | t.Fatalf("Error dialing %q: %v", address, err) 461 | } 462 | client := rpc.NewClient(conn) 463 | defer client.Close() 464 | req := "dummy" 465 | var resp string 466 | if err = client.Call("RPCService.GetResponse", req, &resp); err != nil { 467 | t.Fatalf("Error calling RPCService.GetResponse: %v", err) 468 | } 469 | if req != resp { 470 | t.Fatalf("Unexpected result (expected: %q, got: %q)", req, resp) 471 | } 472 | } 473 | 474 | // listenAndClose is a helper method to just listen on a pipe and close as soon as someone connects. 475 | func listenAndClose(address string, t *testing.T) { 476 | ln, err := Listen(address) 477 | if err != nil { 478 | t.Fatalf("Got unexpected error from Listen: %v", err) 479 | } 480 | if ln == nil { 481 | t.Fatal("Got unexpected nil listener from Listen") 482 | } 483 | conn, err := ln.Accept() 484 | if err != nil { 485 | t.Fatalf("Got unexpected error from Accept: %v", err) 486 | } 487 | if conn == nil { 488 | t.Fatal("Got unexpected nil connection from Accept") 489 | } 490 | if err := conn.Close(); err != nil { 491 | t.Fatalf("Got unexpected error from conection.Close(): %v", err) 492 | } 493 | } 494 | 495 | // TestCommonUseCase is a full run-through of the most common use case, where you create a listener 496 | // and then dial into it with several clients in succession 497 | func TestCommonUseCase(t *testing.T) { 498 | addrs := []string{`\\.\pipe\TestCommonUseCase`, `\\127.0.0.1\pipe\TestCommonUseCase`} 499 | // always listen on the . version, since IP won't work for listening 500 | ln, err := Listen(addrs[0]) 501 | if err != nil { 502 | t.Fatalf("Listen(%q) failed: %v", addrs[0], err) 503 | } 504 | defer ln.Close() 505 | 506 | for _, address := range addrs { 507 | convos := 5 508 | clients := 10 509 | 510 | wg := sync.WaitGroup{} 511 | 512 | for x := 0; x < clients; x++ { 513 | wg.Add(1) 514 | go startClient(address, &wg, convos, t) 515 | } 516 | 517 | go startServer(ln, convos, t) 518 | 519 | select { 520 | case <-wait(&wg): 521 | // good! 522 | case <-time.After(time.Second): 523 | t.Fatal("Failed to finish after a reasonable timeout") 524 | } 525 | } 526 | } 527 | 528 | // wait simply waits on the waitgroup and closes the returned channel when done. 529 | func wait(wg *sync.WaitGroup) <-chan struct{} { 530 | done := make(chan struct{}) 531 | go func() { 532 | wg.Wait() 533 | close(done) 534 | }() 535 | return done 536 | } 537 | 538 | // startServer accepts connections and spawns goroutines to handle them 539 | func startServer(ln *PipeListener, iter int, t *testing.T) { 540 | for { 541 | conn, err := ln.Accept() 542 | if err == ErrClosed { 543 | return 544 | } 545 | if err != nil { 546 | t.Fatalf("Error accepting connection: %v", err) 547 | } 548 | go handleConnection(conn, iter, t) 549 | } 550 | } 551 | 552 | // handleConnection is the goroutine that handles connections on the server side 553 | // it expects to read a message and then write a message, convos times, before exiting. 554 | func handleConnection(conn net.Conn, convos int, t *testing.T) { 555 | r := bufio.NewReader(conn) 556 | for x := 0; x < convos; x++ { 557 | msg, err := r.ReadString('\n') 558 | if err != nil { 559 | t.Fatalf("Error reading from server connection: %v", err) 560 | } 561 | if msg != clientMsg { 562 | t.Fatalf("Read incorrect message from client. Expected '%s', got '%s'", clientMsg, msg) 563 | } 564 | 565 | if _, err := fmt.Fprint(conn, serverMsg); err != nil { 566 | t.Fatalf("Error on server writing to pipe: %v", err) 567 | } 568 | } 569 | if err := conn.Close(); err != nil { 570 | t.Fatalf("Error closing server side of connection: %v", err) 571 | } 572 | } 573 | 574 | // startClient waits on a pipe at the given address. It expects to write a message and then 575 | // read a message from the pipe, convos times, and then sends a message on the done 576 | // channel 577 | func startClient(address string, wg *sync.WaitGroup, convos int, t *testing.T) { 578 | defer wg.Done() 579 | c := make(chan *PipeConn) 580 | go asyncdial(address, c, t) 581 | 582 | var conn *PipeConn 583 | select { 584 | case conn = <-c: 585 | case <-time.After(time.Second): 586 | // Yes this is a long timeout, but sometimes it really does take a long time. 587 | t.Fatalf("Client timed out waiting for dial to resolve") 588 | } 589 | r := bufio.NewReader(conn) 590 | for x := 0; x < convos; x++ { 591 | if _, err := fmt.Fprint(conn, clientMsg); err != nil { 592 | t.Fatalf("Error on client writing to pipe: %v", err) 593 | } 594 | 595 | msg, err := r.ReadString('\n') 596 | if err != nil { 597 | t.Fatalf("Error reading from client connection: %v", err) 598 | } 599 | if msg != serverMsg { 600 | t.Fatalf("Read incorrect message from server. Expected '%s', got '%s'", serverMsg, msg) 601 | } 602 | } 603 | 604 | if err := conn.Close(); err != nil { 605 | t.Fatalf("Error closing client side of pipe %v", err) 606 | } 607 | } 608 | 609 | // asyncdial is a helper that dials and returns the connection on the given channel. 610 | // this is useful for being able to give dial a timeout 611 | func asyncdial(address string, c chan *PipeConn, t *testing.T) { 612 | conn, err := Dial(address) 613 | if err != nil { 614 | t.Fatalf("Error from dial: %v", err) 615 | } 616 | c <- conn 617 | } 618 | 619 | // exists is a simple helper function to detect if a file exists on disk 620 | func exists(path string) (bool, error) { 621 | _, err := os.Stat(path) 622 | if err == nil { 623 | return true, nil 624 | } 625 | if os.IsNotExist(err) { 626 | return false, nil 627 | } 628 | return false, err 629 | } 630 | 631 | func checkDeadline(deadline, end time.Time, t *testing.T) { 632 | if end.Before(deadline) { 633 | t.Fatalf("Ended %v before deadline", deadline.Sub(end)) 634 | } 635 | diff := end.Sub(deadline) 636 | 637 | // we need a huge fudge factor here because Windows has really poor 638 | // resolution for timeouts, and in practice, the timeout can be 400ms or 639 | // more after the expected timeout. 640 | if diff > 500*time.Millisecond { 641 | t.Fatalf("Ended significantly (%v) after deadline", diff) 642 | } 643 | } 644 | -------------------------------------------------------------------------------- /znpipe_windows_386.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | // go build mksyscall_windows.go && ./mksyscall_windows npipe_windows.go 3 | // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT 4 | 5 | package npipe 6 | 7 | import "unsafe" 8 | import "syscall" 9 | 10 | var ( 11 | modkernel32 = syscall.NewLazyDLL("kernel32.dll") 12 | 13 | procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") 14 | procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") 15 | procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe") 16 | procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW") 17 | procCreateEventW = modkernel32.NewProc("CreateEventW") 18 | procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult") 19 | procCancelIoEx = modkernel32.NewProc("CancelIoEx") 20 | ) 21 | 22 | func createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) { 23 | 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) 24 | handle = syscall.Handle(r0) 25 | if handle == syscall.InvalidHandle { 26 | if e1 != 0 { 27 | err = error(e1) 28 | } else { 29 | err = syscall.EINVAL 30 | } 31 | } 32 | return 33 | } 34 | 35 | func cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) { 36 | r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0) 37 | if r1 == 0 { 38 | if e1 != 0 { 39 | err = error(e1) 40 | } else { 41 | err = syscall.EINVAL 42 | } 43 | } 44 | return 45 | } 46 | 47 | func connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) { 48 | r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0) 49 | if r1 == 0 { 50 | if e1 != 0 { 51 | err = error(e1) 52 | } else { 53 | err = syscall.EINVAL 54 | } 55 | } 56 | return 57 | } 58 | 59 | func disconnectNamedPipe(handle syscall.Handle) (err error) { 60 | r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(handle), 0, 0) 61 | if r1 == 0 { 62 | if e1 != 0 { 63 | err = error(e1) 64 | } else { 65 | err = syscall.EINVAL 66 | } 67 | } 68 | return 69 | } 70 | 71 | func waitNamedPipe(name *uint16, timeout uint32) (err error) { 72 | r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0) 73 | if r1 == 0 { 74 | if e1 != 0 { 75 | err = error(e1) 76 | } else { 77 | err = syscall.EINVAL 78 | } 79 | } 80 | return 81 | } 82 | 83 | func createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) { 84 | var _p0 uint32 85 | if manualReset { 86 | _p0 = 1 87 | } else { 88 | _p0 = 0 89 | } 90 | var _p1 uint32 91 | if initialState { 92 | _p1 = 1 93 | } else { 94 | _p1 = 0 95 | } 96 | r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(sa)), uintptr(_p0), uintptr(_p1), uintptr(unsafe.Pointer(name)), 0, 0) 97 | handle = syscall.Handle(r0) 98 | if handle == syscall.InvalidHandle { 99 | if e1 != 0 { 100 | err = error(e1) 101 | } else { 102 | err = syscall.EINVAL 103 | } 104 | } 105 | return 106 | } 107 | 108 | func getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) { 109 | var _p0 uint32 110 | if wait { 111 | _p0 = 1 112 | } else { 113 | _p0 = 0 114 | } 115 | r1, _, e1 := syscall.Syscall6(procGetOverlappedResult.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transferred)), uintptr(_p0), 0, 0) 116 | if r1 == 0 { 117 | if e1 != 0 { 118 | err = error(e1) 119 | } else { 120 | err = syscall.EINVAL 121 | } 122 | } 123 | return 124 | } 125 | -------------------------------------------------------------------------------- /znpipe_windows_amd64.go: -------------------------------------------------------------------------------- 1 | // +build windows 2 | // go build mksyscall_windows.go && ./mksyscall_windows npipe_windows.go 3 | // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT 4 | 5 | package npipe 6 | 7 | import "unsafe" 8 | import "syscall" 9 | 10 | var ( 11 | modkernel32 = syscall.NewLazyDLL("kernel32.dll") 12 | 13 | procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") 14 | procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") 15 | procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe") 16 | procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW") 17 | procCreateEventW = modkernel32.NewProc("CreateEventW") 18 | procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult") 19 | procCancelIoEx = modkernel32.NewProc("CancelIoEx") 20 | ) 21 | 22 | func createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) { 23 | 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) 24 | handle = syscall.Handle(r0) 25 | if handle == syscall.InvalidHandle { 26 | if e1 != 0 { 27 | err = error(e1) 28 | } else { 29 | err = syscall.EINVAL 30 | } 31 | } 32 | return 33 | } 34 | 35 | func cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) { 36 | r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0) 37 | if r1 == 0 { 38 | if e1 != 0 { 39 | err = error(e1) 40 | } else { 41 | err = syscall.EINVAL 42 | } 43 | } 44 | return 45 | } 46 | 47 | func connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) { 48 | r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0) 49 | if r1 == 0 { 50 | if e1 != 0 { 51 | err = error(e1) 52 | } else { 53 | err = syscall.EINVAL 54 | } 55 | } 56 | return 57 | } 58 | 59 | func disconnectNamedPipe(handle syscall.Handle) (err error) { 60 | r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(handle), 0, 0) 61 | if r1 == 0 { 62 | if e1 != 0 { 63 | err = error(e1) 64 | } else { 65 | err = syscall.EINVAL 66 | } 67 | } 68 | return 69 | } 70 | 71 | func waitNamedPipe(name *uint16, timeout uint32) (err error) { 72 | r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0) 73 | if r1 == 0 { 74 | if e1 != 0 { 75 | err = error(e1) 76 | } else { 77 | err = syscall.EINVAL 78 | } 79 | } 80 | return 81 | } 82 | 83 | func createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) { 84 | var _p0 uint32 85 | if manualReset { 86 | _p0 = 1 87 | } else { 88 | _p0 = 0 89 | } 90 | var _p1 uint32 91 | if initialState { 92 | _p1 = 1 93 | } else { 94 | _p1 = 0 95 | } 96 | r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(sa)), uintptr(_p0), uintptr(_p1), uintptr(unsafe.Pointer(name)), 0, 0) 97 | handle = syscall.Handle(r0) 98 | if handle == syscall.InvalidHandle { 99 | if e1 != 0 { 100 | err = error(e1) 101 | } else { 102 | err = syscall.EINVAL 103 | } 104 | } 105 | return 106 | } 107 | 108 | func getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) { 109 | var _p0 uint32 110 | if wait { 111 | _p0 = 1 112 | } else { 113 | _p0 = 0 114 | } 115 | r1, _, e1 := syscall.Syscall6(procGetOverlappedResult.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transferred)), uintptr(_p0), 0, 0) 116 | if r1 == 0 { 117 | if e1 != 0 { 118 | err = error(e1) 119 | } else { 120 | err = syscall.EINVAL 121 | } 122 | } 123 | return 124 | } 125 | --------------------------------------------------------------------------------