pipe.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package winio
  2. import (
  3. "errors"
  4. "io"
  5. "net"
  6. "os"
  7. "syscall"
  8. "time"
  9. "unsafe"
  10. )
  11. //sys connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) = ConnectNamedPipe
  12. //sys createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *securityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW
  13. //sys createFile(name string, access uint32, mode uint32, sa *securityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateFileW
  14. //sys waitNamedPipe(name string, timeout uint32) (err error) = WaitNamedPipeW
  15. //sys getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) = GetNamedPipeInfo
  16. //sys getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW
  17. type securityAttributes struct {
  18. Length uint32
  19. SecurityDescriptor *byte
  20. InheritHandle uint32
  21. }
  22. const (
  23. cERROR_PIPE_BUSY = syscall.Errno(231)
  24. cERROR_PIPE_CONNECTED = syscall.Errno(535)
  25. cERROR_SEM_TIMEOUT = syscall.Errno(121)
  26. cPIPE_ACCESS_DUPLEX = 0x3
  27. cFILE_FLAG_FIRST_PIPE_INSTANCE = 0x80000
  28. cSECURITY_SQOS_PRESENT = 0x100000
  29. cSECURITY_ANONYMOUS = 0
  30. cPIPE_REJECT_REMOTE_CLIENTS = 0x8
  31. cPIPE_UNLIMITED_INSTANCES = 255
  32. cNMPWAIT_USE_DEFAULT_WAIT = 0
  33. cNMPWAIT_NOWAIT = 1
  34. cPIPE_TYPE_MESSAGE = 4
  35. cPIPE_READMODE_MESSAGE = 2
  36. )
  37. var (
  38. // ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed.
  39. // This error should match net.errClosing since docker takes a dependency on its text.
  40. ErrPipeListenerClosed = errors.New("use of closed network connection")
  41. errPipeWriteClosed = errors.New("pipe has been closed for write")
  42. )
  43. type win32Pipe struct {
  44. *win32File
  45. path string
  46. }
  47. type win32MessageBytePipe struct {
  48. win32Pipe
  49. writeClosed bool
  50. readEOF bool
  51. }
  52. type pipeAddress string
  53. func (f *win32Pipe) LocalAddr() net.Addr {
  54. return pipeAddress(f.path)
  55. }
  56. func (f *win32Pipe) RemoteAddr() net.Addr {
  57. return pipeAddress(f.path)
  58. }
  59. func (f *win32Pipe) SetDeadline(t time.Time) error {
  60. f.SetReadDeadline(t)
  61. f.SetWriteDeadline(t)
  62. return nil
  63. }
  64. // CloseWrite closes the write side of a message pipe in byte mode.
  65. func (f *win32MessageBytePipe) CloseWrite() error {
  66. if f.writeClosed {
  67. return errPipeWriteClosed
  68. }
  69. _, err := f.win32File.Write(nil)
  70. if err != nil {
  71. return err
  72. }
  73. f.writeClosed = true
  74. return nil
  75. }
  76. // Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since
  77. // they are used to implement CloseWrite().
  78. func (f *win32MessageBytePipe) Write(b []byte) (int, error) {
  79. if f.writeClosed {
  80. return 0, errPipeWriteClosed
  81. }
  82. if len(b) == 0 {
  83. return 0, nil
  84. }
  85. return f.win32File.Write(b)
  86. }
  87. // Read reads bytes from a message pipe in byte mode. A read of a zero-byte message on a message
  88. // mode pipe will return io.EOF, as will all subsequent reads.
  89. func (f *win32MessageBytePipe) Read(b []byte) (int, error) {
  90. if f.readEOF {
  91. return 0, io.EOF
  92. }
  93. n, err := f.win32File.Read(b)
  94. if err == io.EOF {
  95. // If this was the result of a zero-byte read, then
  96. // it is possible that the read was due to a zero-size
  97. // message. Since we are simulating CloseWrite with a
  98. // zero-byte message, ensure that all future Read() calls
  99. // also return EOF.
  100. f.readEOF = true
  101. }
  102. return n, err
  103. }
  104. func (s pipeAddress) Network() string {
  105. return "pipe"
  106. }
  107. func (s pipeAddress) String() string {
  108. return string(s)
  109. }
  110. // DialPipe connects to a named pipe by path, timing out if the connection
  111. // takes longer than the specified duration. If timeout is nil, then the timeout
  112. // is the default timeout established by the pipe server.
  113. func DialPipe(path string, timeout *time.Duration) (net.Conn, error) {
  114. var absTimeout time.Time
  115. if timeout != nil {
  116. absTimeout = time.Now().Add(*timeout)
  117. }
  118. var err error
  119. var h syscall.Handle
  120. for {
  121. h, err = createFile(path, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0)
  122. if err != cERROR_PIPE_BUSY {
  123. break
  124. }
  125. now := time.Now()
  126. var ms uint32
  127. if absTimeout.IsZero() {
  128. ms = cNMPWAIT_USE_DEFAULT_WAIT
  129. } else if now.After(absTimeout) {
  130. ms = cNMPWAIT_NOWAIT
  131. } else {
  132. ms = uint32(absTimeout.Sub(now).Nanoseconds() / 1000 / 1000)
  133. }
  134. err = waitNamedPipe(path, ms)
  135. if err != nil {
  136. if err == cERROR_SEM_TIMEOUT {
  137. return nil, ErrTimeout
  138. }
  139. break
  140. }
  141. }
  142. if err != nil {
  143. return nil, &os.PathError{Op: "open", Path: path, Err: err}
  144. }
  145. var flags uint32
  146. err = getNamedPipeInfo(h, &flags, nil, nil, nil)
  147. if err != nil {
  148. return nil, err
  149. }
  150. var state uint32
  151. err = getNamedPipeHandleState(h, &state, nil, nil, nil, nil, 0)
  152. if err != nil {
  153. return nil, err
  154. }
  155. if state&cPIPE_READMODE_MESSAGE != 0 {
  156. return nil, &os.PathError{Op: "open", Path: path, Err: errors.New("message readmode pipes not supported")}
  157. }
  158. f, err := makeWin32File(h)
  159. if err != nil {
  160. syscall.Close(h)
  161. return nil, err
  162. }
  163. // If the pipe is in message mode, return a message byte pipe, which
  164. // supports CloseWrite().
  165. if flags&cPIPE_TYPE_MESSAGE != 0 {
  166. return &win32MessageBytePipe{
  167. win32Pipe: win32Pipe{win32File: f, path: path},
  168. }, nil
  169. }
  170. return &win32Pipe{win32File: f, path: path}, nil
  171. }
  172. type acceptResponse struct {
  173. f *win32File
  174. err error
  175. }
  176. type win32PipeListener struct {
  177. firstHandle syscall.Handle
  178. path string
  179. securityDescriptor []byte
  180. config PipeConfig
  181. acceptCh chan (chan acceptResponse)
  182. closeCh chan int
  183. doneCh chan int
  184. }
  185. func makeServerPipeHandle(path string, securityDescriptor []byte, c *PipeConfig, first bool) (syscall.Handle, error) {
  186. var flags uint32 = cPIPE_ACCESS_DUPLEX | syscall.FILE_FLAG_OVERLAPPED
  187. if first {
  188. flags |= cFILE_FLAG_FIRST_PIPE_INSTANCE
  189. }
  190. var mode uint32 = cPIPE_REJECT_REMOTE_CLIENTS
  191. if c.MessageMode {
  192. mode |= cPIPE_TYPE_MESSAGE
  193. }
  194. var sa securityAttributes
  195. sa.Length = uint32(unsafe.Sizeof(sa))
  196. if securityDescriptor != nil {
  197. sa.SecurityDescriptor = &securityDescriptor[0]
  198. }
  199. h, err := createNamedPipe(path, flags, mode, cPIPE_UNLIMITED_INSTANCES, uint32(c.OutputBufferSize), uint32(c.InputBufferSize), 0, &sa)
  200. if err != nil {
  201. return 0, &os.PathError{Op: "open", Path: path, Err: err}
  202. }
  203. return h, nil
  204. }
  205. func (l *win32PipeListener) makeServerPipe() (*win32File, error) {
  206. h, err := makeServerPipeHandle(l.path, l.securityDescriptor, &l.config, false)
  207. if err != nil {
  208. return nil, err
  209. }
  210. f, err := makeWin32File(h)
  211. if err != nil {
  212. syscall.Close(h)
  213. return nil, err
  214. }
  215. return f, nil
  216. }
  217. func (l *win32PipeListener) listenerRoutine() {
  218. closed := false
  219. for !closed {
  220. select {
  221. case <-l.closeCh:
  222. closed = true
  223. case responseCh := <-l.acceptCh:
  224. p, err := l.makeServerPipe()
  225. if err == nil {
  226. // Wait for the client to connect.
  227. ch := make(chan error)
  228. go func() {
  229. ch <- connectPipe(p)
  230. }()
  231. select {
  232. case err = <-ch:
  233. if err != nil {
  234. p.Close()
  235. p = nil
  236. }
  237. case <-l.closeCh:
  238. // Abort the connect request by closing the handle.
  239. p.Close()
  240. p = nil
  241. err = <-ch
  242. if err == nil || err == ErrFileClosed {
  243. err = ErrPipeListenerClosed
  244. }
  245. closed = true
  246. }
  247. }
  248. responseCh <- acceptResponse{p, err}
  249. }
  250. }
  251. syscall.Close(l.firstHandle)
  252. l.firstHandle = 0
  253. // Notify Close() and Accept() callers that the handle has been closed.
  254. close(l.doneCh)
  255. }
  256. // PipeConfig contain configuration for the pipe listener.
  257. type PipeConfig struct {
  258. // SecurityDescriptor contains a Windows security descriptor in SDDL format.
  259. SecurityDescriptor string
  260. // MessageMode determines whether the pipe is in byte or message mode. In either
  261. // case the pipe is read in byte mode by default. The only practical difference in
  262. // this implementation is that CloseWrite() is only supported for message mode pipes;
  263. // CloseWrite() is implemented as a zero-byte write, but zero-byte writes are only
  264. // transferred to the reader (and returned as io.EOF in this implementation)
  265. // when the pipe is in message mode.
  266. MessageMode bool
  267. // InputBufferSize specifies the size the input buffer, in bytes.
  268. InputBufferSize int32
  269. // OutputBufferSize specifies the size the input buffer, in bytes.
  270. OutputBufferSize int32
  271. }
  272. // ListenPipe creates a listener on a Windows named pipe path, e.g. \\.\pipe\mypipe.
  273. // The pipe must not already exist.
  274. func ListenPipe(path string, c *PipeConfig) (net.Listener, error) {
  275. var (
  276. sd []byte
  277. err error
  278. )
  279. if c == nil {
  280. c = &PipeConfig{}
  281. }
  282. if c.SecurityDescriptor != "" {
  283. sd, err = SddlToSecurityDescriptor(c.SecurityDescriptor)
  284. if err != nil {
  285. return nil, err
  286. }
  287. }
  288. h, err := makeServerPipeHandle(path, sd, c, true)
  289. if err != nil {
  290. return nil, err
  291. }
  292. // Immediately open and then close a client handle so that the named pipe is
  293. // created but not currently accepting connections.
  294. h2, err := createFile(path, 0, 0, nil, syscall.OPEN_EXISTING, cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0)
  295. if err != nil {
  296. syscall.Close(h)
  297. return nil, err
  298. }
  299. syscall.Close(h2)
  300. l := &win32PipeListener{
  301. firstHandle: h,
  302. path: path,
  303. securityDescriptor: sd,
  304. config: *c,
  305. acceptCh: make(chan (chan acceptResponse)),
  306. closeCh: make(chan int),
  307. doneCh: make(chan int),
  308. }
  309. go l.listenerRoutine()
  310. return l, nil
  311. }
  312. func connectPipe(p *win32File) error {
  313. c, err := p.prepareIo()
  314. if err != nil {
  315. return err
  316. }
  317. err = connectNamedPipe(p.handle, &c.o)
  318. _, err = p.asyncIo(c, time.Time{}, 0, err)
  319. if err != nil && err != cERROR_PIPE_CONNECTED {
  320. return err
  321. }
  322. return nil
  323. }
  324. func (l *win32PipeListener) Accept() (net.Conn, error) {
  325. ch := make(chan acceptResponse)
  326. select {
  327. case l.acceptCh <- ch:
  328. response := <-ch
  329. err := response.err
  330. if err != nil {
  331. return nil, err
  332. }
  333. if l.config.MessageMode {
  334. return &win32MessageBytePipe{
  335. win32Pipe: win32Pipe{win32File: response.f, path: l.path},
  336. }, nil
  337. }
  338. return &win32Pipe{win32File: response.f, path: l.path}, nil
  339. case <-l.doneCh:
  340. return nil, ErrPipeListenerClosed
  341. }
  342. }
  343. func (l *win32PipeListener) Close() error {
  344. select {
  345. case l.closeCh <- 1:
  346. <-l.doneCh
  347. case <-l.doneCh:
  348. }
  349. return nil
  350. }
  351. func (l *win32PipeListener) Addr() net.Addr {
  352. return pipeAddress(l.path)
  353. }