main
Raw Download raw file
  1//go:build windows
  2// +build windows
  3
  4package winio
  5
  6import (
  7	"context"
  8	"errors"
  9	"fmt"
 10	"io"
 11	"net"
 12	"os"
 13	"runtime"
 14	"time"
 15	"unsafe"
 16
 17	"golang.org/x/sys/windows"
 18
 19	"github.com/Microsoft/go-winio/internal/fs"
 20)
 21
 22//sys connectNamedPipe(pipe windows.Handle, o *windows.Overlapped) (err error) = ConnectNamedPipe
 23//sys createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *windows.SecurityAttributes) (handle windows.Handle, err error)  [failretval==windows.InvalidHandle] = CreateNamedPipeW
 24//sys disconnectNamedPipe(pipe windows.Handle) (err error) = DisconnectNamedPipe
 25//sys getNamedPipeInfo(pipe windows.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) = GetNamedPipeInfo
 26//sys getNamedPipeHandleState(pipe windows.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW
 27//sys ntCreateNamedPipeFile(pipe *windows.Handle, access ntAccessMask, oa *objectAttributes, iosb *ioStatusBlock, share ntFileShareMode, disposition ntFileCreationDisposition, options ntFileOptions, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (status ntStatus) = ntdll.NtCreateNamedPipeFile
 28//sys rtlNtStatusToDosError(status ntStatus) (winerr error) = ntdll.RtlNtStatusToDosErrorNoTeb
 29//sys rtlDosPathNameToNtPathName(name *uint16, ntName *unicodeString, filePart uintptr, reserved uintptr) (status ntStatus) = ntdll.RtlDosPathNameToNtPathName_U
 30//sys rtlDefaultNpAcl(dacl *uintptr) (status ntStatus) = ntdll.RtlDefaultNpAcl
 31
 32type PipeConn interface {
 33	net.Conn
 34	Disconnect() error
 35	Flush() error
 36}
 37
 38// type aliases for mkwinsyscall code
 39type (
 40	ntAccessMask              = fs.AccessMask
 41	ntFileShareMode           = fs.FileShareMode
 42	ntFileCreationDisposition = fs.NTFileCreationDisposition
 43	ntFileOptions             = fs.NTCreateOptions
 44)
 45
 46type ioStatusBlock struct {
 47	Status, Information uintptr
 48}
 49
 50//	typedef struct _OBJECT_ATTRIBUTES {
 51//	  ULONG           Length;
 52//	  HANDLE          RootDirectory;
 53//	  PUNICODE_STRING ObjectName;
 54//	  ULONG           Attributes;
 55//	  PVOID           SecurityDescriptor;
 56//	  PVOID           SecurityQualityOfService;
 57//	} OBJECT_ATTRIBUTES;
 58//
 59// https://learn.microsoft.com/en-us/windows/win32/api/ntdef/ns-ntdef-_object_attributes
 60type objectAttributes struct {
 61	Length             uintptr
 62	RootDirectory      uintptr
 63	ObjectName         *unicodeString
 64	Attributes         uintptr
 65	SecurityDescriptor *securityDescriptor
 66	SecurityQoS        uintptr
 67}
 68
 69type unicodeString struct {
 70	Length        uint16
 71	MaximumLength uint16
 72	Buffer        uintptr
 73}
 74
 75//	typedef struct _SECURITY_DESCRIPTOR {
 76//	  BYTE                        Revision;
 77//	  BYTE                        Sbz1;
 78//	  SECURITY_DESCRIPTOR_CONTROL Control;
 79//	  PSID                        Owner;
 80//	  PSID                        Group;
 81//	  PACL                        Sacl;
 82//	  PACL                        Dacl;
 83//	} SECURITY_DESCRIPTOR, *PISECURITY_DESCRIPTOR;
 84//
 85// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-security_descriptor
 86type securityDescriptor struct {
 87	Revision byte
 88	Sbz1     byte
 89	Control  uint16
 90	Owner    uintptr
 91	Group    uintptr
 92	Sacl     uintptr //revive:disable-line:var-naming SACL, not Sacl
 93	Dacl     uintptr //revive:disable-line:var-naming DACL, not Dacl
 94}
 95
 96type ntStatus int32
 97
 98func (status ntStatus) Err() error {
 99	if status >= 0 {
100		return nil
101	}
102	return rtlNtStatusToDosError(status)
103}
104
105var (
106	// ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed.
107	ErrPipeListenerClosed = net.ErrClosed
108
109	errPipeWriteClosed = errors.New("pipe has been closed for write")
110)
111
112type win32Pipe struct {
113	*win32File
114	path string
115}
116
117var _ PipeConn = (*win32Pipe)(nil)
118
119type win32MessageBytePipe struct {
120	win32Pipe
121	writeClosed bool
122	readEOF     bool
123}
124
125type pipeAddress string
126
127func (f *win32Pipe) LocalAddr() net.Addr {
128	return pipeAddress(f.path)
129}
130
131func (f *win32Pipe) RemoteAddr() net.Addr {
132	return pipeAddress(f.path)
133}
134
135func (f *win32Pipe) SetDeadline(t time.Time) error {
136	if err := f.SetReadDeadline(t); err != nil {
137		return err
138	}
139	return f.SetWriteDeadline(t)
140}
141
142func (f *win32Pipe) Disconnect() error {
143	return disconnectNamedPipe(f.win32File.handle)
144}
145
146// CloseWrite closes the write side of a message pipe in byte mode.
147func (f *win32MessageBytePipe) CloseWrite() error {
148	if f.writeClosed {
149		return errPipeWriteClosed
150	}
151	err := f.win32File.Flush()
152	if err != nil {
153		return err
154	}
155	_, err = f.win32File.Write(nil)
156	if err != nil {
157		return err
158	}
159	f.writeClosed = true
160	return nil
161}
162
163// Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since
164// they are used to implement CloseWrite().
165func (f *win32MessageBytePipe) Write(b []byte) (int, error) {
166	if f.writeClosed {
167		return 0, errPipeWriteClosed
168	}
169	if len(b) == 0 {
170		return 0, nil
171	}
172	return f.win32File.Write(b)
173}
174
175// Read reads bytes from a message pipe in byte mode. A read of a zero-byte message on a message
176// mode pipe will return io.EOF, as will all subsequent reads.
177func (f *win32MessageBytePipe) Read(b []byte) (int, error) {
178	if f.readEOF {
179		return 0, io.EOF
180	}
181	n, err := f.win32File.Read(b)
182	if err == io.EOF { //nolint:errorlint
183		// If this was the result of a zero-byte read, then
184		// it is possible that the read was due to a zero-size
185		// message. Since we are simulating CloseWrite with a
186		// zero-byte message, ensure that all future Read() calls
187		// also return EOF.
188		f.readEOF = true
189	} else if err == windows.ERROR_MORE_DATA { //nolint:errorlint // err is Errno
190		// ERROR_MORE_DATA indicates that the pipe's read mode is message mode
191		// and the message still has more bytes. Treat this as a success, since
192		// this package presents all named pipes as byte streams.
193		err = nil
194	}
195	return n, err
196}
197
198func (pipeAddress) Network() string {
199	return "pipe"
200}
201
202func (s pipeAddress) String() string {
203	return string(s)
204}
205
206// tryDialPipe attempts to dial the pipe at `path` until `ctx` cancellation or timeout.
207func tryDialPipe(ctx context.Context, path *string, access fs.AccessMask, impLevel PipeImpLevel) (windows.Handle, error) {
208	for {
209		select {
210		case <-ctx.Done():
211			return windows.Handle(0), ctx.Err()
212		default:
213			h, err := fs.CreateFile(*path,
214				access,
215				0,   // mode
216				nil, // security attributes
217				fs.OPEN_EXISTING,
218				fs.FILE_FLAG_OVERLAPPED|fs.SECURITY_SQOS_PRESENT|fs.FileSQSFlag(impLevel),
219				0, // template file handle
220			)
221			if err == nil {
222				return h, nil
223			}
224			if err != windows.ERROR_PIPE_BUSY { //nolint:errorlint // err is Errno
225				return h, &os.PathError{Err: err, Op: "open", Path: *path}
226			}
227			// Wait 10 msec and try again. This is a rather simplistic
228			// view, as we always try each 10 milliseconds.
229			time.Sleep(10 * time.Millisecond)
230		}
231	}
232}
233
234// DialPipe connects to a named pipe by path, timing out if the connection
235// takes longer than the specified duration. If timeout is nil, then we use
236// a default timeout of 2 seconds.  (We do not use WaitNamedPipe.)
237func DialPipe(path string, timeout *time.Duration) (net.Conn, error) {
238	var absTimeout time.Time
239	if timeout != nil {
240		absTimeout = time.Now().Add(*timeout)
241	} else {
242		absTimeout = time.Now().Add(2 * time.Second)
243	}
244	ctx, cancel := context.WithDeadline(context.Background(), absTimeout)
245	defer cancel()
246	conn, err := DialPipeContext(ctx, path)
247	if errors.Is(err, context.DeadlineExceeded) {
248		return nil, ErrTimeout
249	}
250	return conn, err
251}
252
253// DialPipeContext attempts to connect to a named pipe by `path` until `ctx`
254// cancellation or timeout.
255func DialPipeContext(ctx context.Context, path string) (net.Conn, error) {
256	return DialPipeAccess(ctx, path, uint32(fs.GENERIC_READ|fs.GENERIC_WRITE))
257}
258
259// PipeImpLevel is an enumeration of impersonation levels that may be set
260// when calling DialPipeAccessImpersonation.
261type PipeImpLevel uint32
262
263const (
264	PipeImpLevelAnonymous      = PipeImpLevel(fs.SECURITY_ANONYMOUS)
265	PipeImpLevelIdentification = PipeImpLevel(fs.SECURITY_IDENTIFICATION)
266	PipeImpLevelImpersonation  = PipeImpLevel(fs.SECURITY_IMPERSONATION)
267	PipeImpLevelDelegation     = PipeImpLevel(fs.SECURITY_DELEGATION)
268)
269
270// DialPipeAccess attempts to connect to a named pipe by `path` with `access` until `ctx`
271// cancellation or timeout.
272func DialPipeAccess(ctx context.Context, path string, access uint32) (net.Conn, error) {
273	return DialPipeAccessImpLevel(ctx, path, access, PipeImpLevelAnonymous)
274}
275
276// DialPipeAccessImpLevel attempts to connect to a named pipe by `path` with
277// `access` at `impLevel` until `ctx` cancellation or timeout. The other
278// DialPipe* implementations use PipeImpLevelAnonymous.
279func DialPipeAccessImpLevel(ctx context.Context, path string, access uint32, impLevel PipeImpLevel) (net.Conn, error) {
280	var err error
281	var h windows.Handle
282	h, err = tryDialPipe(ctx, &path, fs.AccessMask(access), impLevel)
283	if err != nil {
284		return nil, err
285	}
286
287	var flags uint32
288	err = getNamedPipeInfo(h, &flags, nil, nil, nil)
289	if err != nil {
290		return nil, err
291	}
292
293	f, err := makeWin32File(h)
294	if err != nil {
295		windows.Close(h)
296		return nil, err
297	}
298
299	// If the pipe is in message mode, return a message byte pipe, which
300	// supports CloseWrite().
301	if flags&windows.PIPE_TYPE_MESSAGE != 0 {
302		return &win32MessageBytePipe{
303			win32Pipe: win32Pipe{win32File: f, path: path},
304		}, nil
305	}
306	return &win32Pipe{win32File: f, path: path}, nil
307}
308
309type acceptResponse struct {
310	f   *win32File
311	err error
312}
313
314type win32PipeListener struct {
315	firstHandle windows.Handle
316	path        string
317	config      PipeConfig
318	acceptCh    chan (chan acceptResponse)
319	closeCh     chan int
320	doneCh      chan int
321}
322
323func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (windows.Handle, error) {
324	path16, err := windows.UTF16FromString(path)
325	if err != nil {
326		return 0, &os.PathError{Op: "open", Path: path, Err: err}
327	}
328
329	var oa objectAttributes
330	oa.Length = unsafe.Sizeof(oa)
331
332	var ntPath unicodeString
333	if err := rtlDosPathNameToNtPathName(&path16[0],
334		&ntPath,
335		0,
336		0,
337	).Err(); err != nil {
338		return 0, &os.PathError{Op: "open", Path: path, Err: err}
339	}
340	defer windows.LocalFree(windows.Handle(ntPath.Buffer)) //nolint:errcheck
341	oa.ObjectName = &ntPath
342	oa.Attributes = windows.OBJ_CASE_INSENSITIVE
343
344	// The security descriptor is only needed for the first pipe.
345	if first {
346		if sd != nil {
347			//todo: does `sdb` need to be allocated on the heap, or can go allocate it?
348			l := uint32(len(sd))
349			sdb, err := windows.LocalAlloc(0, l)
350			if err != nil {
351				return 0, fmt.Errorf("LocalAlloc for security descriptor with of length %d: %w", l, err)
352			}
353			defer windows.LocalFree(windows.Handle(sdb)) //nolint:errcheck
354			copy((*[0xffff]byte)(unsafe.Pointer(sdb))[:], sd)
355			oa.SecurityDescriptor = (*securityDescriptor)(unsafe.Pointer(sdb))
356		} else {
357			// Construct the default named pipe security descriptor.
358			var dacl uintptr
359			if err := rtlDefaultNpAcl(&dacl).Err(); err != nil {
360				return 0, fmt.Errorf("getting default named pipe ACL: %w", err)
361			}
362			defer windows.LocalFree(windows.Handle(dacl)) //nolint:errcheck
363
364			sdb := &securityDescriptor{
365				Revision: 1,
366				Control:  windows.SE_DACL_PRESENT,
367				Dacl:     dacl,
368			}
369			oa.SecurityDescriptor = sdb
370		}
371	}
372
373	typ := uint32(windows.FILE_PIPE_REJECT_REMOTE_CLIENTS)
374	if c.MessageMode {
375		typ |= windows.FILE_PIPE_MESSAGE_TYPE
376	}
377
378	disposition := fs.FILE_OPEN
379	access := fs.GENERIC_READ | fs.GENERIC_WRITE | fs.SYNCHRONIZE
380	if first {
381		disposition = fs.FILE_CREATE
382		// By not asking for read or write access, the named pipe file system
383		// will put this pipe into an initially disconnected state, blocking
384		// client connections until the next call with first == false.
385		access = fs.SYNCHRONIZE
386	}
387
388	timeout := int64(-50 * 10000) // 50ms
389
390	var (
391		h    windows.Handle
392		iosb ioStatusBlock
393	)
394	err = ntCreateNamedPipeFile(&h,
395		access,
396		&oa,
397		&iosb,
398		fs.FILE_SHARE_READ|fs.FILE_SHARE_WRITE,
399		disposition,
400		0,
401		typ,
402		0,
403		0,
404		0xffffffff,
405		uint32(c.InputBufferSize),
406		uint32(c.OutputBufferSize),
407		&timeout).Err()
408	if err != nil {
409		return 0, &os.PathError{Op: "open", Path: path, Err: err}
410	}
411
412	runtime.KeepAlive(ntPath)
413	return h, nil
414}
415
416func (l *win32PipeListener) makeServerPipe() (*win32File, error) {
417	h, err := makeServerPipeHandle(l.path, nil, &l.config, false)
418	if err != nil {
419		return nil, err
420	}
421	f, err := makeWin32File(h)
422	if err != nil {
423		windows.Close(h)
424		return nil, err
425	}
426	return f, nil
427}
428
429func (l *win32PipeListener) makeConnectedServerPipe() (*win32File, error) {
430	p, err := l.makeServerPipe()
431	if err != nil {
432		return nil, err
433	}
434
435	// Wait for the client to connect.
436	ch := make(chan error)
437	go func(p *win32File) {
438		ch <- connectPipe(p)
439	}(p)
440
441	select {
442	case err = <-ch:
443		if err != nil {
444			p.Close()
445			p = nil
446		}
447	case <-l.closeCh:
448		// Abort the connect request by closing the handle.
449		p.Close()
450		p = nil
451		err = <-ch
452		if err == nil || err == ErrFileClosed { //nolint:errorlint // err is Errno
453			err = ErrPipeListenerClosed
454		}
455	}
456	return p, err
457}
458
459func (l *win32PipeListener) listenerRoutine() {
460	closed := false
461	for !closed {
462		select {
463		case <-l.closeCh:
464			closed = true
465		case responseCh := <-l.acceptCh:
466			var (
467				p   *win32File
468				err error
469			)
470			for {
471				p, err = l.makeConnectedServerPipe()
472				// If the connection was immediately closed by the client, try
473				// again.
474				if err != windows.ERROR_NO_DATA { //nolint:errorlint // err is Errno
475					break
476				}
477			}
478			responseCh <- acceptResponse{p, err}
479			closed = err == ErrPipeListenerClosed //nolint:errorlint // err is Errno
480		}
481	}
482	windows.Close(l.firstHandle)
483	l.firstHandle = 0
484	// Notify Close() and Accept() callers that the handle has been closed.
485	close(l.doneCh)
486}
487
488// PipeConfig contain configuration for the pipe listener.
489type PipeConfig struct {
490	// SecurityDescriptor contains a Windows security descriptor in SDDL format.
491	SecurityDescriptor string
492
493	// MessageMode determines whether the pipe is in byte or message mode. In either
494	// case the pipe is read in byte mode by default. The only practical difference in
495	// this implementation is that CloseWrite() is only supported for message mode pipes;
496	// CloseWrite() is implemented as a zero-byte write, but zero-byte writes are only
497	// transferred to the reader (and returned as io.EOF in this implementation)
498	// when the pipe is in message mode.
499	MessageMode bool
500
501	// InputBufferSize specifies the size of the input buffer, in bytes.
502	InputBufferSize int32
503
504	// OutputBufferSize specifies the size of the output buffer, in bytes.
505	OutputBufferSize int32
506}
507
508// ListenPipe creates a listener on a Windows named pipe path, e.g. \\.\pipe\mypipe.
509// The pipe must not already exist.
510func ListenPipe(path string, c *PipeConfig) (net.Listener, error) {
511	var (
512		sd  []byte
513		err error
514	)
515	if c == nil {
516		c = &PipeConfig{}
517	}
518	if c.SecurityDescriptor != "" {
519		sd, err = SddlToSecurityDescriptor(c.SecurityDescriptor)
520		if err != nil {
521			return nil, err
522		}
523	}
524	h, err := makeServerPipeHandle(path, sd, c, true)
525	if err != nil {
526		return nil, err
527	}
528	l := &win32PipeListener{
529		firstHandle: h,
530		path:        path,
531		config:      *c,
532		acceptCh:    make(chan (chan acceptResponse)),
533		closeCh:     make(chan int),
534		doneCh:      make(chan int),
535	}
536	go l.listenerRoutine()
537	return l, nil
538}
539
540func connectPipe(p *win32File) error {
541	c, err := p.prepareIO()
542	if err != nil {
543		return err
544	}
545	defer p.wg.Done()
546
547	err = connectNamedPipe(p.handle, &c.o)
548	_, err = p.asyncIO(c, nil, 0, err)
549	if err != nil && err != windows.ERROR_PIPE_CONNECTED { //nolint:errorlint // err is Errno
550		return err
551	}
552	return nil
553}
554
555func (l *win32PipeListener) Accept() (net.Conn, error) {
556	ch := make(chan acceptResponse)
557	select {
558	case l.acceptCh <- ch:
559		response := <-ch
560		err := response.err
561		if err != nil {
562			return nil, err
563		}
564		if l.config.MessageMode {
565			return &win32MessageBytePipe{
566				win32Pipe: win32Pipe{win32File: response.f, path: l.path},
567			}, nil
568		}
569		return &win32Pipe{win32File: response.f, path: l.path}, nil
570	case <-l.doneCh:
571		return nil, ErrPipeListenerClosed
572	}
573}
574
575func (l *win32PipeListener) Close() error {
576	select {
577	case l.closeCh <- 1:
578		<-l.doneCh
579	case <-l.doneCh:
580	}
581	return nil
582}
583
584func (l *win32PipeListener) Addr() net.Addr {
585	return pipeAddress(l.path)
586}