vendor/gopkg.in/natefinch/npipe.v2/npipe_windows.go

531 lines · 15933 bytes

  1package 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
 11import (
 12	"fmt"
 13	"io"
 14	"net"
 15	"sync"
 16	"syscall"
 17	"time"
 18)
 19
 20const (
 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
 69var _ net.Conn = (*PipeConn)(nil)
 70var _ net.Listener = (*PipeListener)(nil)
 71
 72// ErrClosed is the error returned by PipeListener.Accept when Close is called
 73// on the PipeListener.
 74var ErrClosed = PipeError{"Pipe has been closed.", false}
 75
 76// PipeError is an error related to a call to a pipe
 77type PipeError struct {
 78	msg     string
 79	timeout bool
 80}
 81
 82// Error implements the error interface
 83func (e PipeError) Error() string {
 84	return e.msg
 85}
 86
 87// Timeout implements net.AddrError.Timeout()
 88func (e PipeError) Timeout() bool {
 89	return e.timeout
 90}
 91
 92// Temporary implements net.AddrError.Temporary()
 93func (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\<name> for local pipes and \\<computer>\pipe\<name>
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`)
111func 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
126func 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
159func 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.
170func 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).
181func 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.
194func 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\<name>
226//
227// Listen will return a PipeError for an incorrectly formatted pipe name.
228func 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.
245type 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.
262func (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.
277func (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.
342func (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.
382func (l *PipeListener) Addr() net.Addr { return l.addr }
383
384// PipeConn is the implementation of the net.Conn interface for named pipe connections.
385type 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
394type 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.
402func (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.
432func (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.
446func (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.
458func (c *PipeConn) Close() error {
459	return syscall.CloseHandle(c.handle)
460}
461
462// LocalAddr returns the local network address.
463func (c *PipeConn) LocalAddr() net.Addr {
464	return c.addr
465}
466
467// RemoteAddr returns the remote network address.
468func (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
475func (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
483func (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
490func (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.
496type PipeAddr string
497
498// Network returns the address's network name, "pipe".
499func (a PipeAddr) Network() string { return "pipe" }
500
501// String returns the address of the pipe
502func (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.
510func 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
526func badAddr(addr string) PipeError {
527	return PipeError{fmt.Sprintf("Invalid pipe address '%s'.", addr), false}
528}
529func timeout(addr string) PipeError {
530	return PipeError{fmt.Sprintf("Pipe IO timed out waiting for '%s'", addr), true}
531}