Merge pull request #14758 from Microsoft/10662-pipestohcs

Windows: [TP3] new hcsshim stdin/out/err handling
This commit is contained in:
Arnaud Porterie 2015-08-13 22:52:48 -07:00
commit 693ff58cd2
16 changed files with 214 additions and 1385 deletions

View file

@ -8,22 +8,16 @@ import (
"github.com/Sirupsen/logrus"
"github.com/docker/docker/daemon/execdriver"
"github.com/docker/docker/pkg/stringid"
"github.com/microsoft/hcsshim"
"github.com/natefinch/npipe"
)
// Exec implements the exec driver Driver interface.
func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) {
var (
inListen, outListen, errListen *npipe.PipeListener
term execdriver.Terminal
err error
randomID = stringid.GenerateNonCryptoID()
serverPipeFormat, clientPipeFormat string
pid uint32
exitCode int32
term execdriver.Terminal
err error
exitCode int32
)
active := d.activeContainers[c.ID]
@ -39,64 +33,6 @@ func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessCo
// Configure the environment for the process // Note NOT c.ProcessConfig.Tty
createProcessParms.Environment = setupEnvironmentVariables(processConfig.Env)
// We use another unique ID here for each exec instance otherwise it
// may conflict with the pipe name being used by RUN.
// We use a different pipe name between real and dummy mode in the HCS
if dummyMode {
clientPipeFormat = `\\.\pipe\docker-exec-%[1]s-%[2]s-%[3]s`
serverPipeFormat = clientPipeFormat
} else {
clientPipeFormat = `\\.\pipe\docker-exec-%[2]s-%[3]s`
serverPipeFormat = `\\.\Containers\%[1]s\Device\NamedPipe\docker-exec-%[2]s-%[3]s`
}
// Connect stdin
if pipes.Stdin != nil {
stdInPipe := fmt.Sprintf(serverPipeFormat, c.ID, randomID, "stdin")
createProcessParms.StdInPipe = fmt.Sprintf(clientPipeFormat, c.ID, randomID, "stdin")
// Listen on the named pipe
inListen, err = npipe.Listen(stdInPipe)
if err != nil {
logrus.Errorf("stdin failed to listen on %s %s ", stdInPipe, err)
return -1, err
}
defer inListen.Close()
// Launch a goroutine to do the accept. We do this so that we can
// cause an otherwise blocking goroutine to gracefully close when
// the caller (us) closes the listener
go stdinAccept(inListen, stdInPipe, pipes.Stdin)
}
// Connect stdout
stdOutPipe := fmt.Sprintf(serverPipeFormat, c.ID, randomID, "stdout")
createProcessParms.StdOutPipe = fmt.Sprintf(clientPipeFormat, c.ID, randomID, "stdout")
outListen, err = npipe.Listen(stdOutPipe)
if err != nil {
logrus.Errorf("stdout failed to listen on %s %s", stdOutPipe, err)
return -1, err
}
defer outListen.Close()
go stdouterrAccept(outListen, stdOutPipe, pipes.Stdout)
// No stderr on TTY. Note NOT c.ProcessConfig.Tty
if !processConfig.Tty {
// Connect stderr
stdErrPipe := fmt.Sprintf(serverPipeFormat, c.ID, randomID, "stderr")
createProcessParms.StdErrPipe = fmt.Sprintf(clientPipeFormat, c.ID, randomID, "stderr")
errListen, err = npipe.Listen(stdErrPipe)
if err != nil {
logrus.Errorf("Stderr failed to listen on %s %s", stdErrPipe, err)
return -1, err
}
defer errListen.Close()
go stdouterrAccept(errListen, stdErrPipe, pipes.Stderr)
}
// While this should get caught earlier, just in case, validate that we
// have something to run.
if processConfig.Entrypoint == "" {
@ -114,13 +50,16 @@ func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessCo
logrus.Debugln("commandLine: ", createProcessParms.CommandLine)
// Start the command running in the container.
pid, err = hcsshim.CreateProcessInComputeSystem(c.ID, createProcessParms)
pid, stdin, stdout, stderr, err := hcsshim.CreateProcessInComputeSystem(c.ID, pipes.Stdin != nil, true, !processConfig.Tty, createProcessParms)
if err != nil {
logrus.Errorf("CreateProcessInComputeSystem() failed %s", err)
return -1, err
}
// Now that the process has been launched, begin copying data to and from
// the named pipes for the std handles.
setupPipes(stdin, stdout, stderr, pipes)
// Note NOT c.ProcessConfig.Tty
if processConfig.Tty {
term = NewTtyConsole(c.ID, pid)

View file

@ -6,77 +6,49 @@ import (
"io"
"github.com/Sirupsen/logrus"
"github.com/natefinch/npipe"
"github.com/docker/docker/daemon/execdriver"
)
// stdinAccept runs as a go function. It waits for the container system
// to accept our offer of a named pipe for stdin. Once accepted, if we are
// running "attached" to the container (eg docker run -i), then we spin up
// a further thread to copy anything from the client into the container.
//
// Important design note. This function is run as a go function for a very
// good reason. The named pipe Accept call is blocking until one of two things
// happen. Either someone connects to it, or it is forcibly closed. Let's
// assume that no-one connects to it, the only way otherwise the Run()
// method would continue is by closing it. However, as that would be the same
// thread, it can't close it. Hence we run as another thread allowing Run()
// to close the named pipe.
func stdinAccept(inListen *npipe.PipeListener, pipeName string, copyfrom io.ReadCloser) {
// General comment. Handling I/O for a container is very different to Linux.
// We use a named pipe to HCS to copy I/O both in and out of the container,
// very similar to how docker daemon communicates with a CLI.
// Wait for the pipe to be connected to by the shim
logrus.Debugln("stdinAccept: Waiting on ", pipeName)
stdinConn, err := inListen.Accept()
if err != nil {
logrus.Errorf("Failed to accept on pipe %s %s", pipeName, err)
return
}
logrus.Debugln("Connected to ", stdinConn.RemoteAddr())
// startStdinCopy asynchronously copies an io.Reader to the container's
// process's stdin pipe and closes the pipe when there is no more data to copy.
func startStdinCopy(dst io.WriteCloser, src io.Reader) {
// Anything that comes from the client stdin should be copied
// across to the stdin named pipe of the container.
if copyfrom != nil {
go func() {
defer stdinConn.Close()
logrus.Debugln("Calling io.Copy on stdin")
bytes, err := io.Copy(stdinConn, copyfrom)
logrus.Debugf("Finished io.Copy on stdin bytes=%d err=%s pipe=%s", bytes, err, stdinConn.RemoteAddr())
}()
} else {
defer stdinConn.Close()
}
go func() {
defer dst.Close()
bytes, err := io.Copy(dst, src)
logrus.Debugf("Copied %d bytes from stdin err=%s", bytes, err)
}()
}
// stdouterrAccept runs as a go function. It waits for the container system to
// accept our offer of a named pipe - in fact two of them - one for stdout
// and one for stderr (we are called twice). Once the named pipe is accepted,
// if we are running "attached" to the container (eg docker run -i), then we
// spin up a further thread to copy anything from the containers output channels
// to the client.
func stdouterrAccept(outerrListen *npipe.PipeListener, pipeName string, copyto io.Writer) {
// Wait for the pipe to be connected to by the shim
logrus.Debugln("out/err: Waiting on ", pipeName)
outerrConn, err := outerrListen.Accept()
if err != nil {
logrus.Errorf("Failed to accept on pipe %s %s", pipeName, err)
return
}
logrus.Debugln("Connected to ", outerrConn.RemoteAddr())
// startStdouterrCopy asynchronously copies data from the container's process's
// stdout or stderr pipe to an io.Writer and closes the pipe when there is no
// more data to copy.
func startStdouterrCopy(dst io.Writer, src io.ReadCloser, name string) {
// Anything that comes from the container named pipe stdout/err should be copied
// across to the stdout/err of the client
if copyto != nil {
go func() {
defer outerrConn.Close()
logrus.Debugln("Calling io.Copy on ", pipeName)
bytes, err := io.Copy(copyto, outerrConn)
logrus.Debugf("Copied %d bytes from pipe=%s", bytes, outerrConn.RemoteAddr())
if err != nil {
// Not fatal, just debug log it
logrus.Debugf("Error hit during copy %s", err)
}
}()
} else {
defer outerrConn.Close()
go func() {
defer src.Close()
bytes, err := io.Copy(dst, src)
logrus.Debugf("Copied %d bytes from %s err=%s", bytes, name, err)
}()
}
// setupPipes starts the asynchronous copying of data to and from the named
// pipes used byt he HCS for the std handles.
func setupPipes(stdin io.WriteCloser, stdout, stderr io.ReadCloser, pipes *execdriver.Pipes) {
if stdin != nil {
startStdinCopy(stdin, pipes.Stdin)
}
if stdout != nil {
startStdouterrCopy(pipes.Stdout, stdout, "stdout")
}
if stderr != nil {
startStdouterrCopy(pipes.Stderr, stderr, "stderr")
}
}

View file

@ -15,7 +15,6 @@ import (
"github.com/Sirupsen/logrus"
"github.com/docker/docker/daemon/execdriver"
"github.com/microsoft/hcsshim"
"github.com/natefinch/npipe"
)
// defaultContainerNAT is the default name of the container NAT device that is
@ -60,23 +59,28 @@ type device struct {
}
type containerInit struct {
SystemType string
Name string
IsDummy bool
VolumePath string
Devices []device
IgnoreFlushesDuringBoot bool
LayerFolderPath string
Layers []layer
SystemType string // HCS requires this to be hard-coded to "Container"
Name string // Name of the container. We use the docker ID.
Owner string // The management platform that created this container
IsDummy bool // Used for development purposes.
VolumePath string // Windows volume path for scratch space
Devices []device // Devices used by the container
IgnoreFlushesDuringBoot bool // Optimisation hint for container startup in Windows
LayerFolderPath string // Where the layer folders are located
Layers []layer // List of storage layers
}
// defaultOwner is a tag passed to HCS to allow it to differentiate between
// container creator management stacks. We hard code "docker" in the case
// of docker.
const defaultOwner = "docker"
// Run implements the exec driver Driver interface
func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) {
var (
term execdriver.Terminal
err error
inListen, outListen, errListen *npipe.PipeListener
term execdriver.Terminal
err error
)
// Make sure the client isn't asking for options which aren't supported
@ -88,6 +92,7 @@ func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba
cu := &containerInit{
SystemType: "Container",
Name: c.ID,
Owner: defaultOwner,
IsDummy: dummyMode,
VolumePath: c.Rootfs,
IgnoreFlushesDuringBoot: c.FirstStart,
@ -224,16 +229,6 @@ func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba
}
}()
// We use a different pipe name between real and dummy mode in the HCS
var serverPipeFormat, clientPipeFormat string
if dummyMode {
clientPipeFormat = `\\.\pipe\docker-run-%[1]s-%[2]s`
serverPipeFormat = clientPipeFormat
} else {
clientPipeFormat = `\\.\pipe\docker-run-%[2]s`
serverPipeFormat = `\\.\Containers\%[1]s\Device\NamedPipe\docker-run-%[2]s`
}
createProcessParms := hcsshim.CreateProcessParams{
EmulateConsole: c.ProcessConfig.Tty,
WorkingDirectory: c.WorkingDir,
@ -243,51 +238,6 @@ func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba
// Configure the environment for the process
createProcessParms.Environment = setupEnvironmentVariables(c.ProcessConfig.Env)
// Connect stdin
if pipes.Stdin != nil {
stdInPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stdin")
createProcessParms.StdInPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stdin")
// Listen on the named pipe
inListen, err = npipe.Listen(stdInPipe)
if err != nil {
logrus.Errorf("stdin failed to listen on %s err=%s", stdInPipe, err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
defer inListen.Close()
// Launch a goroutine to do the accept. We do this so that we can
// cause an otherwise blocking goroutine to gracefully close when
// the caller (us) closes the listener
go stdinAccept(inListen, stdInPipe, pipes.Stdin)
}
// Connect stdout
stdOutPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stdout")
createProcessParms.StdOutPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stdout")
outListen, err = npipe.Listen(stdOutPipe)
if err != nil {
logrus.Errorf("stdout failed to listen on %s err=%s", stdOutPipe, err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
defer outListen.Close()
go stdouterrAccept(outListen, stdOutPipe, pipes.Stdout)
// No stderr on TTY.
if !c.ProcessConfig.Tty {
// Connect stderr
stdErrPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stderr")
createProcessParms.StdErrPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stderr")
errListen, err = npipe.Listen(stdErrPipe)
if err != nil {
logrus.Errorf("stderr failed to listen on %s err=%s", stdErrPipe, err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
defer errListen.Close()
go stdouterrAccept(errListen, stdErrPipe, pipes.Stderr)
}
// This should get caught earlier, but just in case - validate that we
// have something to run
if c.ProcessConfig.Entrypoint == "" {
@ -305,14 +255,16 @@ func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba
logrus.Debugf("CommandLine: %s", createProcessParms.CommandLine)
// Start the command running in the container.
var pid uint32
pid, err = hcsshim.CreateProcessInComputeSystem(c.ID, createProcessParms)
pid, stdin, stdout, stderr, err := hcsshim.CreateProcessInComputeSystem(c.ID, pipes.Stdin != nil, true, !c.ProcessConfig.Tty, createProcessParms)
if err != nil {
logrus.Errorf("CreateProcessInComputeSystem() failed %s", err)
return execdriver.ExitStatus{ExitCode: -1}, err
}
// Now that the process has been launched, begin copying data to and from
// the named pipes for the std handles.
setupPipes(stdin, stdout, stderr, pipes)
//Save the PID as we'll need this in Kill()
logrus.Debugf("PID %d", pid)
c.ContainerPid = int(pid)

View file

@ -13,10 +13,9 @@ clone git github.com/go-check/check 64131543e7896d5bcc6bd5a76287eb75ea96c673
clone git github.com/gorilla/context 14f550f51a
clone git github.com/gorilla/mux e444e69cbd
clone git github.com/kr/pty 5cf931ef8f
clone git github.com/microsoft/hcsshim f674a70f1306dbe20b3a516bedd3285d85db60d9
clone git github.com/mattn/go-sqlite3 b4142c444a8941d0d92b0b7103a24df9cd815e42
clone git github.com/microsoft/hcsshim da093dac579302d7b413696b96dec0b5e1bce8d4
clone git github.com/mistifyio/go-zfs v2.1.1
clone git github.com/natefinch/npipe 0938d701e50e580f5925c773055eb6d6b32a0cbc
clone git github.com/tchap/go-patricia v2.1.0
clone git golang.org/x/net 3cffabab72adf04f8e3b01c5baf775361837b5fe https://github.com/golang/net.git
clone hg code.google.com/p/gosqlite 74691fb6f837

View file

@ -3,6 +3,8 @@ package hcsshim
import (
"encoding/json"
"fmt"
"io"
"runtime"
"syscall"
"unsafe"
@ -12,30 +14,71 @@ import (
// processParameters is use to both the input of CreateProcessInComputeSystem
// and to convert the parameters to JSON for passing onto the HCS
type CreateProcessParams struct {
ApplicationName string
CommandLine string
WorkingDirectory string
StdInPipe, StdOutPipe, StdErrPipe string
Environment map[string]string
EmulateConsole bool
ConsoleSize [2]int
ApplicationName string
CommandLine string
WorkingDirectory string
Environment map[string]string
EmulateConsole bool
ConsoleSize [2]int
}
// pipe struct used for the stdin/stdout/stderr pipes
type pipe struct {
handle syscall.Handle
}
func makePipe(h syscall.Handle) *pipe {
p := &pipe{h}
runtime.SetFinalizer(p, (*pipe).closeHandle)
return p
}
func (p *pipe) closeHandle() {
if p.handle != 0 {
syscall.CloseHandle(p.handle)
p.handle = 0
}
}
func (p *pipe) Close() error {
p.closeHandle()
runtime.SetFinalizer(p, nil)
return nil
}
func (p *pipe) Read(b []byte) (int, error) {
// syscall.Read returns 0, nil on ERROR_BROKEN_PIPE, but for
// our purposes this should indicate EOF. This may be a go bug.
var read uint32
err := syscall.ReadFile(p.handle, b, &read, nil)
if err != nil {
if err == syscall.ERROR_BROKEN_PIPE {
return 0, io.EOF
}
return 0, err
}
return int(read), nil
}
func (p *pipe) Write(b []byte) (int, error) {
return syscall.Write(p.handle, b)
}
// CreateProcessInComputeSystem starts a process in a container. This is invoked, for example,
// as a result of docker run, docker exec, or RUN in Dockerfile. If successful,
// it returns the PID of the process.
func CreateProcessInComputeSystem(id string, params CreateProcessParams) (processid uint32, err error) {
func CreateProcessInComputeSystem(id string, useStdin bool, useStdout bool, useStderr bool, params CreateProcessParams) (processid uint32, stdin io.WriteCloser, stdout io.ReadCloser, stderr io.ReadCloser, err error) {
title := "HCSShim::CreateProcessInComputeSystem"
logrus.Debugf(title+"id=%s params=%s", id, params)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procCreateProcessInComputeSystem)
dll, proc, err := loadAndFind(procCreateProcessWithStdHandlesInComputeSystem)
if dll != nil {
defer dll.Release()
}
if err != nil {
return 0, err
return
}
// Convert id to uint16 pointer for calling the procedure
@ -43,7 +86,7 @@ func CreateProcessInComputeSystem(id string, params CreateProcessParams) (proces
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of id %s to pointer %s", id, err)
logrus.Error(err)
return 0, err
return
}
// If we are not emulating a console, ignore any console size passed to us
@ -55,13 +98,13 @@ func CreateProcessInComputeSystem(id string, params CreateProcessParams) (proces
paramsJson, err := json.Marshal(params)
if err != nil {
err = fmt.Errorf(title+" - Failed to marshall params %v %s", params, err)
return 0, err
return
}
// Convert paramsJson to uint16 pointer for calling the procedure
paramsJsonp, err := syscall.UTF16PtrFromString(string(paramsJson))
if err != nil {
return 0, err
return
}
// Get a POINTER to variable to take the pid outparm
@ -69,11 +112,26 @@ func CreateProcessInComputeSystem(id string, params CreateProcessParams) (proces
logrus.Debugf(title+" - Calling the procedure itself %s %s", id, paramsJson)
var stdinHandle, stdoutHandle, stderrHandle syscall.Handle
var stdinParam, stdoutParam, stderrParam uintptr
if useStdin {
stdinParam = uintptr(unsafe.Pointer(&stdinHandle))
}
if useStdout {
stdoutParam = uintptr(unsafe.Pointer(&stdoutHandle))
}
if useStderr {
stderrParam = uintptr(unsafe.Pointer(&stderrHandle))
}
// Call the procedure itself.
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(idp)),
uintptr(unsafe.Pointer(paramsJsonp)),
uintptr(unsafe.Pointer(pid)))
uintptr(unsafe.Pointer(pid)),
stdinParam,
stdoutParam,
stderrParam)
use(unsafe.Pointer(idp))
use(unsafe.Pointer(paramsJsonp))
@ -81,9 +139,19 @@ func CreateProcessInComputeSystem(id string, params CreateProcessParams) (proces
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s id=%s params=%v", r1, syscall.Errno(r1), id, params)
logrus.Error(err)
return 0, err
return
}
if useStdin {
stdin = makePipe(stdinHandle)
}
if useStdout {
stdout = makePipe(stdoutHandle)
}
if useStderr {
stderr = makePipe(stderrHandle)
}
logrus.Debugf(title+" - succeeded id=%s params=%s pid=%d", id, paramsJson, *pid)
return *pid, nil
return *pid, stdin, stdout, stderr, nil
}

View file

@ -15,5 +15,5 @@ func NewGUID(source string) *GUID {
}
func (g *GUID) ToString() string {
return fmt.Sprintf("%x-%x-%x-%x-%x", g[0:4], g[4:6], g[6:8], g[8:10], g[10:])
return fmt.Sprintf("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x-%02x", g[3], g[2], g[1], g[0], g[5], g[4], g[7], g[6], g[8:10], g[10:])
}

View file

@ -16,14 +16,14 @@ const (
shimDLLName = "vmcompute.dll"
// Container related functions in the shim DLL
procCreateComputeSystem = "CreateComputeSystem"
procStartComputeSystem = "StartComputeSystem"
procCreateProcessInComputeSystem = "CreateProcessInComputeSystem"
procWaitForProcessInComputeSystem = "WaitForProcessInComputeSystem"
procShutdownComputeSystem = "ShutdownComputeSystem"
procTerminateComputeSystem = "TerminateComputeSystem"
procTerminateProcessInComputeSystem = "TerminateProcessInComputeSystem"
procResizeConsoleInComputeSystem = "ResizeConsoleInComputeSystem"
procCreateComputeSystem = "CreateComputeSystem"
procStartComputeSystem = "StartComputeSystem"
procCreateProcessWithStdHandlesInComputeSystem = "CreateProcessWithStdHandlesInComputeSystem"
procWaitForProcessInComputeSystem = "WaitForProcessInComputeSystem"
procShutdownComputeSystem = "ShutdownComputeSystem"
procTerminateComputeSystem = "TerminateComputeSystem"
procTerminateProcessInComputeSystem = "TerminateProcessInComputeSystem"
procResizeConsoleInComputeSystem = "ResizeConsoleInComputeSystem"
// Storage related functions in the shim DLL
procLayerExists = "LayerExists"
@ -39,6 +39,7 @@ const (
procExportLayer = "ExportLayer"
procImportLayer = "ImportLayer"
procGetSharedBaseImages = "GetBaseImages"
procNameToGuid = "NameToGuid"
// Name of the standard OLE dll
oleDLLName = "Ole32.dll"

View file

@ -4,6 +4,7 @@ package hcsshim
// functionality.
import (
"path/filepath"
"syscall"
"github.com/Sirupsen/logrus"
@ -84,9 +85,14 @@ func layerPathsToDescriptors(parentLayerPaths []string) ([]WC_LAYER_DESCRIPTOR,
var layers []WC_LAYER_DESCRIPTOR
for i := 0; i < len(parentLayerPaths); i++ {
// Create a layer descriptor, using the folder path
// Create a layer descriptor, using the folder name
// as the source for a GUID LayerId
g := NewGUID(parentLayerPaths[i])
_, folderName := filepath.Split(parentLayerPaths[i])
g, err := NameToGuid(folderName)
if err != nil {
logrus.Debugf("Failed to convert name to guid %s", err)
return nil, err
}
p, err := syscall.UTF16PtrFromString(parentLayerPaths[i])
if err != nil {
@ -95,7 +101,7 @@ func layerPathsToDescriptors(parentLayerPaths []string) ([]WC_LAYER_DESCRIPTOR,
}
layers = append(layers, WC_LAYER_DESCRIPTOR{
LayerId: *g,
LayerId: g,
Flags: 0,
Pathp: p,
})

View file

@ -0,0 +1,46 @@
package hcsshim
import (
"fmt"
"syscall"
"unsafe"
"github.com/Sirupsen/logrus"
)
func NameToGuid(name string) (id GUID, err error) {
title := "hcsshim::NameToGuid "
logrus.Debugf(title+"Name %s", name)
// Load the DLL and get a handle to the procedure we need
dll, proc, err := loadAndFind(procNameToGuid)
if dll != nil {
defer dll.Release()
}
if err != nil {
return
}
// Convert name to uint16 pointer for calling the procedure
namep, err := syscall.UTF16PtrFromString(name)
if err != nil {
err = fmt.Errorf(title+" - Failed conversion of name %s to pointer %s", name, err)
logrus.Error(err)
return
}
// Call the procedure itself.
logrus.Debugf("Calling proc")
r1, _, _ := proc.Call(
uintptr(unsafe.Pointer(namep)),
uintptr(unsafe.Pointer(&id)))
if r1 != 0 {
err = fmt.Errorf(title+" - Win32 API call returned error r1=%d err=%s name=%s",
r1, syscall.Errno(r1), name)
logrus.Error(err)
return
}
return
}

View file

@ -1,22 +0,0 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe

View file

@ -1,8 +0,0 @@
The MIT License (MIT)
Copyright (c) 2013 npipe authors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,308 +0,0 @@
npipe [![Build status](https://ci.appveyor.com/api/projects/status/00vuepirsot29qwi)](https://ci.appveyor.com/project/natefinch/npipe) [![GoDoc](https://godoc.org/gopkg.in/natefinch/npipe.v2?status.svg)](https://godoc.org/gopkg.in/natefinch/npipe.v2)
=====
Package npipe provides a pure Go wrapper around Windows named pipes.
Windows named pipe documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365780
Note that the code lives at https://github.com/natefinch/npipe (v2 branch)
but should be imported as gopkg.in/natefinch/npipe.v2 (the package name is
still npipe).
npipe provides an interface based on stdlib's net package, with Dial, Listen,
and Accept functions, as well as associated implementations of net.Conn and
net.Listener. It supports rpc over the connection.
### Notes
* Deadlines for reading/writing to the connection are only functional in Windows Vista/Server 2008 and above, due to limitations with the Windows API.
* The pipes support byte mode only (no support for message mode)
### Examples
The Dial function connects a client to a named pipe:
conn, err := npipe.Dial(`\\.\pipe\mypipename`)
if err != nil {
<handle error>
}
fmt.Fprintf(conn, "Hi server!\n")
msg, err := bufio.NewReader(conn).ReadString('\n')
...
The Listen function creates servers:
ln, err := npipe.Listen(`\\.\pipe\mypipename`)
if err != nil {
// handle error
}
for {
conn, err := ln.Accept()
if err != nil {
// handle error
continue
}
go handleConnection(conn)
}
## Variables
``` go
var ErrClosed = PipeError{"Pipe has been closed.", false}
```
ErrClosed is the error returned by PipeListener.Accept when Close is called
on the PipeListener.
## type PipeAddr
``` go
type PipeAddr string
```
PipeAddr represents the address of a named pipe.
### func (PipeAddr) Network
``` go
func (a PipeAddr) Network() string
```
Network returns the address's network name, "pipe".
### func (PipeAddr) String
``` go
func (a PipeAddr) String() string
```
String returns the address of the pipe
## type PipeConn
``` go
type PipeConn struct {
// contains filtered or unexported fields
}
```
PipeConn is the implementation of the net.Conn interface for named pipe connections.
### func Dial
``` go
func Dial(address string) (*PipeConn, error)
```
Dial connects to a named pipe with the given address. If the specified pipe is not available,
it will wait indefinitely for the pipe to become available.
The address must be of the form \\.\\pipe\<name> for local pipes and \\<computer>\pipe\<name>
for remote pipes.
Dial will return a PipeError if you pass in a badly formatted pipe name.
Examples:
// local pipe
conn, err := Dial(`\\.\pipe\mypipename`)
// remote pipe
conn, err := Dial(`\\othercomp\pipe\mypipename`)
### func DialTimeout
``` go
func DialTimeout(address string, timeout time.Duration) (*PipeConn, error)
```
DialTimeout acts like Dial, but will time out after the duration of timeout
### func (\*PipeConn) Close
``` go
func (c *PipeConn) Close() error
```
Close closes the connection.
### func (\*PipeConn) LocalAddr
``` go
func (c *PipeConn) LocalAddr() net.Addr
```
LocalAddr returns the local network address.
### func (\*PipeConn) Read
``` go
func (c *PipeConn) Read(b []byte) (int, error)
```
Read implements the net.Conn Read method.
### func (\*PipeConn) RemoteAddr
``` go
func (c *PipeConn) RemoteAddr() net.Addr
```
RemoteAddr returns the remote network address.
### func (\*PipeConn) SetDeadline
``` go
func (c *PipeConn) SetDeadline(t time.Time) error
```
SetDeadline implements the net.Conn SetDeadline method.
Note that timeouts are only supported on Windows Vista/Server 2008 and above
### func (\*PipeConn) SetReadDeadline
``` go
func (c *PipeConn) SetReadDeadline(t time.Time) error
```
SetReadDeadline implements the net.Conn SetReadDeadline method.
Note that timeouts are only supported on Windows Vista/Server 2008 and above
### func (\*PipeConn) SetWriteDeadline
``` go
func (c *PipeConn) SetWriteDeadline(t time.Time) error
```
SetWriteDeadline implements the net.Conn SetWriteDeadline method.
Note that timeouts are only supported on Windows Vista/Server 2008 and above
### func (\*PipeConn) Write
``` go
func (c *PipeConn) Write(b []byte) (int, error)
```
Write implements the net.Conn Write method.
## type PipeError
``` go
type PipeError struct {
// contains filtered or unexported fields
}
```
PipeError is an error related to a call to a pipe
### func (PipeError) Error
``` go
func (e PipeError) Error() string
```
Error implements the error interface
### func (PipeError) Temporary
``` go
func (e PipeError) Temporary() bool
```
Temporary implements net.AddrError.Temporary()
### func (PipeError) Timeout
``` go
func (e PipeError) Timeout() bool
```
Timeout implements net.AddrError.Timeout()
## type PipeListener
``` go
type PipeListener struct {
// contains filtered or unexported fields
}
```
PipeListener is a named pipe listener. Clients should typically
use variables of type net.Listener instead of assuming named pipe.
### func Listen
``` go
func Listen(address string) (*PipeListener, error)
```
Listen returns a new PipeListener that will listen on a pipe with the given
address. The address must be of the form \\.\pipe\<name>
Listen will return a PipeError for an incorrectly formatted pipe name.
### func (\*PipeListener) Accept
``` go
func (l *PipeListener) Accept() (net.Conn, error)
```
Accept implements the Accept method in the net.Listener interface; it
waits for the next call and returns a generic net.Conn.
### func (\*PipeListener) AcceptPipe
``` go
func (l *PipeListener) AcceptPipe() (*PipeConn, error)
```
AcceptPipe accepts the next incoming call and returns the new connection.
### func (\*PipeListener) Addr
``` go
func (l *PipeListener) Addr() net.Addr
```
Addr returns the listener's network address, a PipeAddr.
### func (\*PipeListener) Close
``` go
func (l *PipeListener) Close() error
```
Close stops listening on the address.
Already Accepted connections are not closed.

View file

@ -1,50 +0,0 @@
// Copyright 2013 Nate Finch. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Package npipe provides a pure Go wrapper around Windows named pipes.
//
// !! Note, this package is Windows-only. There is no code to compile on linux.
//
// Windows named pipe documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365780
//
// Note that the code lives at https://github.com/natefinch/npipe (v2 branch)
// but should be imported as gopkg.in/natefinch/npipe.v2 (the package name is
// still npipe).
//
// npipe provides an interface based on stdlib's net package, with Dial, Listen,
// and Accept functions, as well as associated implementations of net.Conn and
// net.Listener. It supports rpc over the connection.
//
// Notes
//
// * Deadlines for reading/writing to the connection are only functional in Windows Vista/Server 2008 and above, due to limitations with the Windows API.
//
// * The pipes support byte mode only (no support for message mode)
//
// Examples
//
// The Dial function connects a client to a named pipe:
// conn, err := npipe.Dial(`\\.\pipe\mypipename`)
// if err != nil {
// <handle error>
// }
// fmt.Fprintf(conn, "Hi server!\n")
// msg, err := bufio.NewReader(conn).ReadString('\n')
// ...
//
// The Listen function creates servers:
//
// ln, err := npipe.Listen(`\\.\pipe\mypipename`)
// if err != nil {
// // handle error
// }
// for {
// conn, err := ln.Accept()
// if err != nil {
// // handle error
// continue
// }
// go handleConnection(conn)
// }
package npipe

View file

@ -1,518 +0,0 @@
package npipe
//sys createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW
//sys connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) = ConnectNamedPipe
//sys disconnectNamedPipe(handle syscall.Handle) (err error) = DisconnectNamedPipe
//sys waitNamedPipe(name *uint16, timeout uint32) (err error) = WaitNamedPipeW
//sys createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateEventW
//sys getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) = GetOverlappedResult
//sys cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) = CancelIoEx
import (
"fmt"
"io"
"net"
"sync"
"syscall"
"time"
)
const (
// openMode
pipe_access_duplex = 0x3
pipe_access_inbound = 0x1
pipe_access_outbound = 0x2
// openMode write flags
file_flag_first_pipe_instance = 0x00080000
file_flag_write_through = 0x80000000
file_flag_overlapped = 0x40000000
// openMode ACL flags
write_dac = 0x00040000
write_owner = 0x00080000
access_system_security = 0x01000000
// pipeMode
pipe_type_byte = 0x0
pipe_type_message = 0x4
// pipeMode read mode flags
pipe_readmode_byte = 0x0
pipe_readmode_message = 0x2
// pipeMode wait mode flags
pipe_wait = 0x0
pipe_nowait = 0x1
// pipeMode remote-client mode flags
pipe_accept_remote_clients = 0x0
pipe_reject_remote_clients = 0x8
pipe_unlimited_instances = 255
nmpwait_wait_forever = 0xFFFFFFFF
// the two not-an-errors below occur if a client connects to the pipe between
// the server's CreateNamedPipe and ConnectNamedPipe calls.
error_no_data syscall.Errno = 0xE8
error_pipe_connected syscall.Errno = 0x217
error_pipe_busy syscall.Errno = 0xE7
error_sem_timeout syscall.Errno = 0x79
error_bad_pathname syscall.Errno = 0xA1
error_invalid_name syscall.Errno = 0x7B
error_io_incomplete syscall.Errno = 0x3e4
)
var _ net.Conn = (*PipeConn)(nil)
var _ net.Listener = (*PipeListener)(nil)
// ErrClosed is the error returned by PipeListener.Accept when Close is called
// on the PipeListener.
var ErrClosed = PipeError{"Pipe has been closed.", false}
// PipeError is an error related to a call to a pipe
type PipeError struct {
msg string
timeout bool
}
// Error implements the error interface
func (e PipeError) Error() string {
return e.msg
}
// Timeout implements net.AddrError.Timeout()
func (e PipeError) Timeout() bool {
return e.timeout
}
// Temporary implements net.AddrError.Temporary()
func (e PipeError) Temporary() bool {
return false
}
// Dial connects to a named pipe with the given address. If the specified pipe is not available,
// it will wait indefinitely for the pipe to become available.
//
// The address must be of the form \\.\\pipe\<name> for local pipes and \\<computer>\pipe\<name>
// for remote pipes.
//
// Dial will return a PipeError if you pass in a badly formatted pipe name.
//
// Examples:
// // local pipe
// conn, err := Dial(`\\.\pipe\mypipename`)
//
// // remote pipe
// conn, err := Dial(`\\othercomp\pipe\mypipename`)
func Dial(address string) (*PipeConn, error) {
for {
conn, err := dial(address, nmpwait_wait_forever)
if err == nil {
return conn, nil
}
if isPipeNotReady(err) {
<-time.After(100 * time.Millisecond)
continue
}
return nil, err
}
}
// DialTimeout acts like Dial, but will time out after the duration of timeout
func DialTimeout(address string, timeout time.Duration) (*PipeConn, error) {
deadline := time.Now().Add(timeout)
now := time.Now()
for now.Before(deadline) {
millis := uint32(deadline.Sub(now) / time.Millisecond)
conn, err := dial(address, millis)
if err == nil {
return conn, nil
}
if err == error_sem_timeout {
// This is WaitNamedPipe's timeout error, so we know we're done
return nil, PipeError{fmt.Sprintf(
"Timed out waiting for pipe '%s' to come available", address), true}
}
if isPipeNotReady(err) {
left := deadline.Sub(time.Now())
retry := 100 * time.Millisecond
if left > retry {
<-time.After(retry)
} else {
<-time.After(left - time.Millisecond)
}
now = time.Now()
continue
}
return nil, err
}
return nil, PipeError{fmt.Sprintf(
"Timed out waiting for pipe '%s' to come available", address), true}
}
// isPipeNotReady checks the error to see if it indicates the pipe is not ready
func isPipeNotReady(err error) bool {
// Pipe Busy means another client just grabbed the open pipe end,
// and the server hasn't made a new one yet.
// File Not Found means the server hasn't created the pipe yet.
// Neither is a fatal error.
return err == syscall.ERROR_FILE_NOT_FOUND || err == error_pipe_busy
}
// newOverlapped creates a structure used to track asynchronous
// I/O requests that have been issued.
func newOverlapped() (*syscall.Overlapped, error) {
event, err := createEvent(nil, true, true, nil)
if err != nil {
return nil, err
}
return &syscall.Overlapped{HEvent: event}, nil
}
// waitForCompletion waits for an asynchronous I/O request referred to by overlapped to complete.
// This function returns the number of bytes transferred by the operation and an error code if
// applicable (nil otherwise).
func waitForCompletion(handle syscall.Handle, overlapped *syscall.Overlapped) (uint32, error) {
_, err := syscall.WaitForSingleObject(overlapped.HEvent, syscall.INFINITE)
if err != nil {
return 0, err
}
var transferred uint32
err = getOverlappedResult(handle, overlapped, &transferred, true)
return transferred, err
}
// dial is a helper to initiate a connection to a named pipe that has been started by a server.
// The timeout is only enforced if the pipe server has already created the pipe, otherwise
// this function will return immediately.
func dial(address string, timeout uint32) (*PipeConn, error) {
name, err := syscall.UTF16PtrFromString(string(address))
if err != nil {
return nil, err
}
// If at least one instance of the pipe has been created, this function
// will wait timeout milliseconds for it to become available.
// It will return immediately regardless of timeout, if no instances
// of the named pipe have been created yet.
// If this returns with no error, there is a pipe available.
if err := waitNamedPipe(name, timeout); err != nil {
if err == error_bad_pathname {
// badly formatted pipe name
return nil, badAddr(address)
}
return nil, err
}
pathp, err := syscall.UTF16PtrFromString(address)
if err != nil {
return nil, err
}
handle, err := syscall.CreateFile(pathp, syscall.GENERIC_READ|syscall.GENERIC_WRITE,
uint32(syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE), nil, syscall.OPEN_EXISTING,
syscall.FILE_FLAG_OVERLAPPED, 0)
if err != nil {
return nil, err
}
return &PipeConn{handle: handle, addr: PipeAddr(address)}, nil
}
// Listen returns a new PipeListener that will listen on a pipe with the given
// address. The address must be of the form \\.\pipe\<name>
//
// Listen will return a PipeError for an incorrectly formatted pipe name.
func Listen(address string) (*PipeListener, error) {
handle, err := createPipe(address, true)
if err == error_invalid_name {
return nil, badAddr(address)
}
if err != nil {
return nil, err
}
return &PipeListener{
addr: PipeAddr(address),
handle: handle,
}, nil
}
// PipeListener is a named pipe listener. Clients should typically
// use variables of type net.Listener instead of assuming named pipe.
type PipeListener struct {
addr PipeAddr
handle syscall.Handle
closed bool
// acceptHandle contains the current handle waiting for
// an incoming connection or nil.
acceptHandle syscall.Handle
// acceptOverlapped is set before waiting on a connection.
// If not waiting, it is nil.
acceptOverlapped *syscall.Overlapped
// acceptMutex protects the handle and overlapped structure.
acceptMutex sync.Mutex
}
// Accept implements the Accept method in the net.Listener interface; it
// waits for the next call and returns a generic net.Conn.
func (l *PipeListener) Accept() (net.Conn, error) {
c, err := l.AcceptPipe()
for err == error_no_data {
// Ignore clients that connect and immediately disconnect.
c, err = l.AcceptPipe()
}
if err != nil {
return nil, err
}
return c, nil
}
// AcceptPipe accepts the next incoming call and returns the new connection.
// It might return an error if a client connected and immediately cancelled
// the connection.
func (l *PipeListener) AcceptPipe() (*PipeConn, error) {
if l == nil || l.addr == "" || l.closed {
return nil, syscall.EINVAL
}
// the first time we call accept, the handle will have been created by the Listen
// call. This is to prevent race conditions where the client thinks the server
// isn't listening because it hasn't actually called create yet. After the first time, we'll
// have to create a new handle each time
handle := l.handle
if handle == 0 {
var err error
handle, err = createPipe(string(l.addr), false)
if err != nil {
return nil, err
}
} else {
l.handle = 0
}
overlapped, err := newOverlapped()
if err != nil {
return nil, err
}
defer syscall.CloseHandle(overlapped.HEvent)
if err := connectNamedPipe(handle, overlapped); err != nil && err != error_pipe_connected {
if err == error_io_incomplete || err == syscall.ERROR_IO_PENDING {
l.acceptMutex.Lock()
l.acceptOverlapped = overlapped
l.acceptHandle = handle
l.acceptMutex.Unlock()
defer func() {
l.acceptMutex.Lock()
l.acceptOverlapped = nil
l.acceptHandle = 0
l.acceptMutex.Unlock()
}()
_, err = waitForCompletion(handle, overlapped)
}
if err == syscall.ERROR_OPERATION_ABORTED {
// Return error compatible to net.Listener.Accept() in case the
// listener was closed.
return nil, ErrClosed
}
if err != nil {
return nil, err
}
}
return &PipeConn{handle: handle, addr: l.addr}, nil
}
// Close stops listening on the address.
// Already Accepted connections are not closed.
func (l *PipeListener) Close() error {
if l.closed {
return nil
}
l.closed = true
if l.handle != 0 {
err := disconnectNamedPipe(l.handle)
if err != nil {
return err
}
err = syscall.CloseHandle(l.handle)
if err != nil {
return err
}
l.handle = 0
}
l.acceptMutex.Lock()
defer l.acceptMutex.Unlock()
if l.acceptOverlapped != nil && l.acceptHandle != 0 {
// Cancel the pending IO. This call does not block, so it is safe
// to hold onto the mutex above.
if err := cancelIoEx(l.acceptHandle, l.acceptOverlapped); err != nil {
return err
}
err := syscall.CloseHandle(l.acceptOverlapped.HEvent)
if err != nil {
return err
}
l.acceptOverlapped.HEvent = 0
err = syscall.CloseHandle(l.acceptHandle)
if err != nil {
return err
}
l.acceptHandle = 0
}
return nil
}
// Addr returns the listener's network address, a PipeAddr.
func (l *PipeListener) Addr() net.Addr { return l.addr }
// PipeConn is the implementation of the net.Conn interface for named pipe connections.
type PipeConn struct {
handle syscall.Handle
addr PipeAddr
// these aren't actually used yet
readDeadline *time.Time
writeDeadline *time.Time
}
type iodata struct {
n uint32
err error
}
// completeRequest looks at iodata to see if a request is pending. If so, it waits for it to either complete or to
// abort due to hitting the specified deadline. Deadline may be set to nil to wait forever. If no request is pending,
// the content of iodata is returned.
func (c *PipeConn) completeRequest(data iodata, deadline *time.Time, overlapped *syscall.Overlapped) (int, error) {
if data.err == error_io_incomplete || data.err == syscall.ERROR_IO_PENDING {
var timer <-chan time.Time
if deadline != nil {
if timeDiff := deadline.Sub(time.Now()); timeDiff > 0 {
timer = time.After(timeDiff)
}
}
done := make(chan iodata)
go func() {
n, err := waitForCompletion(c.handle, overlapped)
done <- iodata{n, err}
}()
select {
case data = <-done:
case <-timer:
syscall.CancelIoEx(c.handle, overlapped)
data = iodata{0, timeout(c.addr.String())}
}
}
// Windows will produce ERROR_BROKEN_PIPE upon closing
// a handle on the other end of a connection. Go RPC
// expects an io.EOF error in this case.
if data.err == syscall.ERROR_BROKEN_PIPE {
data.err = io.EOF
}
return int(data.n), data.err
}
// Read implements the net.Conn Read method.
func (c *PipeConn) Read(b []byte) (int, error) {
// Use ReadFile() rather than Read() because the latter
// contains a workaround that eats ERROR_BROKEN_PIPE.
overlapped, err := newOverlapped()
if err != nil {
return 0, err
}
defer syscall.CloseHandle(overlapped.HEvent)
var n uint32
err = syscall.ReadFile(c.handle, b, &n, overlapped)
return c.completeRequest(iodata{n, err}, c.readDeadline, overlapped)
}
// Write implements the net.Conn Write method.
func (c *PipeConn) Write(b []byte) (int, error) {
overlapped, err := newOverlapped()
if err != nil {
return 0, err
}
defer syscall.CloseHandle(overlapped.HEvent)
var n uint32
err = syscall.WriteFile(c.handle, b, &n, overlapped)
return c.completeRequest(iodata{n, err}, c.writeDeadline, overlapped)
}
// Close closes the connection.
func (c *PipeConn) Close() error {
return syscall.CloseHandle(c.handle)
}
// LocalAddr returns the local network address.
func (c *PipeConn) LocalAddr() net.Addr {
return c.addr
}
// RemoteAddr returns the remote network address.
func (c *PipeConn) RemoteAddr() net.Addr {
// not sure what to do here, we don't have remote addr....
return c.addr
}
// SetDeadline implements the net.Conn SetDeadline method.
// Note that timeouts are only supported on Windows Vista/Server 2008 and above
func (c *PipeConn) SetDeadline(t time.Time) error {
c.SetReadDeadline(t)
c.SetWriteDeadline(t)
return nil
}
// SetReadDeadline implements the net.Conn SetReadDeadline method.
// Note that timeouts are only supported on Windows Vista/Server 2008 and above
func (c *PipeConn) SetReadDeadline(t time.Time) error {
c.readDeadline = &t
return nil
}
// SetWriteDeadline implements the net.Conn SetWriteDeadline method.
// Note that timeouts are only supported on Windows Vista/Server 2008 and above
func (c *PipeConn) SetWriteDeadline(t time.Time) error {
c.writeDeadline = &t
return nil
}
// PipeAddr represents the address of a named pipe.
type PipeAddr string
// Network returns the address's network name, "pipe".
func (a PipeAddr) Network() string { return "pipe" }
// String returns the address of the pipe
func (a PipeAddr) String() string {
return string(a)
}
// createPipe is a helper function to make sure we always create pipes
// with the same arguments, since subsequent calls to create pipe need
// to use the same arguments as the first one. If first is set, fail
// if the pipe already exists.
func createPipe(address string, first bool) (syscall.Handle, error) {
n, err := syscall.UTF16PtrFromString(address)
if err != nil {
return 0, err
}
mode := uint32(pipe_access_duplex | syscall.FILE_FLAG_OVERLAPPED)
if first {
mode |= file_flag_first_pipe_instance
}
return createNamedPipe(n,
mode,
pipe_type_byte,
pipe_unlimited_instances,
512, 512, 0, nil)
}
func badAddr(addr string) PipeError {
return PipeError{fmt.Sprintf("Invalid pipe address '%s'.", addr), false}
}
func timeout(addr string) PipeError {
return PipeError{fmt.Sprintf("Pipe IO timed out waiting for '%s'", addr), true}
}

View file

@ -1,124 +0,0 @@
// +build windows
// go build mksyscall_windows.go && ./mksyscall_windows npipe_windows.go
// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
package npipe
import "unsafe"
import "syscall"
var (
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW")
procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe")
procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe")
procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW")
procCreateEventW = modkernel32.NewProc("CreateEventW")
procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult")
procCancelIoEx = modkernel32.NewProc("CancelIoEx")
)
func createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) {
r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(openMode), uintptr(pipeMode), uintptr(maxInstances), uintptr(outBufSize), uintptr(inBufSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0)
handle = syscall.Handle(r0)
if handle == syscall.InvalidHandle {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func disconnectNamedPipe(handle syscall.Handle) (err error) {
r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(handle), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func waitNamedPipe(name *uint16, timeout uint32) (err error) {
r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) {
var _p0 uint32
if manualReset {
_p0 = 1
} else {
_p0 = 0
}
var _p1 uint32
if initialState {
_p1 = 1
} else {
_p1 = 0
}
r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(sa)), uintptr(_p0), uintptr(_p1), uintptr(unsafe.Pointer(name)), 0, 0)
handle = syscall.Handle(r0)
if handle == syscall.InvalidHandle {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) {
var _p0 uint32
if wait {
_p0 = 1
} else {
_p0 = 0
}
r1, _, e1 := syscall.Syscall6(procGetOverlappedResult.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transferred)), uintptr(_p0), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}

View file

@ -1,124 +0,0 @@
// +build windows
// go build mksyscall_windows.go && ./mksyscall_windows npipe_windows.go
// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
package npipe
import "unsafe"
import "syscall"
var (
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW")
procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe")
procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe")
procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW")
procCreateEventW = modkernel32.NewProc("CreateEventW")
procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult")
procCancelIoEx = modkernel32.NewProc("CancelIoEx")
)
func createNamedPipe(name *uint16, openMode uint32, pipeMode uint32, maxInstances uint32, outBufSize uint32, inBufSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) {
r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(openMode), uintptr(pipeMode), uintptr(maxInstances), uintptr(outBufSize), uintptr(inBufSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0)
handle = syscall.Handle(r0)
if handle == syscall.InvalidHandle {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func cancelIoEx(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func connectNamedPipe(handle syscall.Handle, overlapped *syscall.Overlapped) (err error) {
r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func disconnectNamedPipe(handle syscall.Handle) (err error) {
r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(handle), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func waitNamedPipe(name *uint16, timeout uint32) (err error) {
r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) {
var _p0 uint32
if manualReset {
_p0 = 1
} else {
_p0 = 0
}
var _p1 uint32
if initialState {
_p1 = 1
} else {
_p1 = 0
}
r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(sa)), uintptr(_p0), uintptr(_p1), uintptr(unsafe.Pointer(name)), 0, 0)
handle = syscall.Handle(r0)
if handle == syscall.InvalidHandle {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func getOverlappedResult(handle syscall.Handle, overlapped *syscall.Overlapped, transferred *uint32, wait bool) (err error) {
var _p0 uint32
if wait {
_p0 = 1
} else {
_p0 = 0
}
r1, _, e1 := syscall.Syscall6(procGetOverlappedResult.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transferred)), uintptr(_p0), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}