Skip to content

Commit

Permalink
Use x/sys/windows for all windows constants
Browse files Browse the repository at this point in the history
This replaces the use of either syscall or hard-coded magic numbers.

Signed-off-by: Paul "TBBle" Hampson <[email protected]>
  • Loading branch information
TBBle committed Apr 21, 2021
1 parent 17250b5 commit bb021fd
Show file tree
Hide file tree
Showing 10 changed files with 53 additions and 41 deletions.
10 changes: 6 additions & 4 deletions backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"runtime"
"syscall"
"unicode/utf16"

"golang.org/x/sys/windows"
)

//sys backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupRead
Expand All @@ -35,9 +37,9 @@ const (
)

const (
WRITE_DAC = 0x40000
WRITE_OWNER = 0x80000
ACCESS_SYSTEM_SECURITY = 0x1000000
WRITE_DAC = windows.WRITE_DAC
WRITE_OWNER = windows.WRITE_OWNER
ACCESS_SYSTEM_SECURITY = windows.ACCESS_SYSTEM_SECURITY
)

// BackupHeader represents a backup stream of a file.
Expand Down Expand Up @@ -271,7 +273,7 @@ func OpenForBackup(path string, access uint32, share uint32, createmode uint32)
if err != nil {
return nil, err
}
h, err := syscall.CreateFile(&winPath[0], access, share, nil, createmode, syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, 0)
h, err := syscall.CreateFile(&winPath[0], access, share, nil, createmode, windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)
if err != nil {
err = &os.PathError{Op: "open", Path: path, Err: err}
return nil, err
Expand Down
5 changes: 2 additions & 3 deletions backuptar/tar.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"path/filepath"
"strconv"
"strings"
"syscall"
"time"

"github.com/Microsoft/go-winio"
Expand Down Expand Up @@ -101,7 +100,7 @@ func BasicInfoHeader(name string, size int64, fileInfo *winio.FileBasicInfo) *ta
hdr.PAXRecords[hdrFileAttributes] = fmt.Sprintf("%d", fileInfo.FileAttributes)
hdr.PAXRecords[hdrCreationTime] = formatPAXTime(time.Unix(0, fileInfo.CreationTime.Nanoseconds()))

if (fileInfo.FileAttributes & syscall.FILE_ATTRIBUTE_DIRECTORY) != 0 {
if (fileInfo.FileAttributes & windows.FILE_ATTRIBUTE_DIRECTORY) != 0 {
hdr.Mode |= c_ISDIR
hdr.Size = 0
hdr.Typeflag = tar.TypeDir
Expand Down Expand Up @@ -312,7 +311,7 @@ func FileInfoFromHeader(hdr *tar.Header) (name string, size int64, fileInfo *win
fileInfo.FileAttributes = uint32(attr)
} else {
if hdr.Typeflag == tar.TypeDir {
fileInfo.FileAttributes |= syscall.FILE_ATTRIBUTE_DIRECTORY
fileInfo.FileAttributes |= windows.FILE_ATTRIBUTE_DIRECTORY
}
}
if creationTimeStr, ok := hdr.PAXRecords[hdrCreationTime]; ok {
Expand Down
16 changes: 9 additions & 7 deletions file.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"sync/atomic"
"syscall"
"time"

"golang.org/x/sys/windows"
)

//sys cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) = CancelIoEx
Expand All @@ -32,8 +34,8 @@ func (b *atomicBool) swap(new bool) bool {
}

const (
cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1
cFILE_SKIP_SET_EVENT_ON_HANDLE = 2
cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS = windows.FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
cFILE_SKIP_SET_EVENT_ON_HANDLE = windows.FILE_SKIP_SET_EVENT_ON_HANDLE
)

var (
Expand Down Expand Up @@ -164,7 +166,7 @@ func ioCompletionProcessor(h syscall.Handle) {
var bytes uint32
var key uintptr
var op *ioOperation
err := getQueuedCompletionStatus(h, &bytes, &key, &op, syscall.INFINITE)
err := getQueuedCompletionStatus(h, &bytes, &key, &op, windows.INFINITE)
if op == nil {
panic(err)
}
Expand All @@ -175,7 +177,7 @@ func ioCompletionProcessor(h syscall.Handle) {
// asyncIo processes the return value from ReadFile or WriteFile, blocking until
// the operation has actually completed.
func (f *win32File) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, err error) (int, error) {
if err != syscall.ERROR_IO_PENDING {
if err != windows.ERROR_IO_PENDING {
return int(bytes), err
}

Expand All @@ -194,7 +196,7 @@ func (f *win32File) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, er
select {
case r = <-c.ch:
err = r.err
if err == syscall.ERROR_OPERATION_ABORTED {
if err == windows.ERROR_OPERATION_ABORTED {
if f.closing.isSet() {
err = ErrFileClosed
}
Expand All @@ -207,7 +209,7 @@ func (f *win32File) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, er
cancelIoEx(f.handle, &c.o)
r = <-c.ch
err = r.err
if err == syscall.ERROR_OPERATION_ABORTED {
if err == windows.ERROR_OPERATION_ABORTED {
err = ErrTimeout
}
}
Expand Down Expand Up @@ -239,7 +241,7 @@ func (f *win32File) Read(b []byte) (int, error) {
// Handle EOF conditions.
if err == nil && n == 0 && len(b) != 0 {
return 0, io.EOF
} else if err == syscall.ERROR_BROKEN_PIPE {
} else if err == windows.ERROR_BROKEN_PIPE {
return 0, io.EOF
} else {
return n, err
Expand Down
9 changes: 5 additions & 4 deletions hvsock.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"unsafe"

"github.com/Microsoft/go-winio/pkg/guid"
"golang.org/x/sys/windows"
)

//sys bind(s syscall.Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socketError] = ws2_32.bind
Expand Down Expand Up @@ -77,7 +78,7 @@ type HvsockConn struct {
}

func newHvSocket() (*win32File, error) {
fd, err := syscall.Socket(afHvSock, syscall.SOCK_STREAM, 1)
fd, err := syscall.Socket(afHvSock, windows.SOCK_STREAM, 1)
if err != nil {
return nil, os.NewSyscallError("socket", err)
}
Expand Down Expand Up @@ -253,7 +254,7 @@ func (conn *HvsockConn) Close() error {
}

func (conn *HvsockConn) shutdown(how int) error {
err := syscall.Shutdown(conn.sock.handle, syscall.SHUT_RD)
err := syscall.Shutdown(conn.sock.handle, windows.SHUT_RD)
if err != nil {
return os.NewSyscallError("shutdown", err)
}
Expand All @@ -262,7 +263,7 @@ func (conn *HvsockConn) shutdown(how int) error {

// CloseRead shuts down the read end of the socket.
func (conn *HvsockConn) CloseRead() error {
err := conn.shutdown(syscall.SHUT_RD)
err := conn.shutdown(windows.SHUT_RD)
if err != nil {
return conn.opErr("close", err)
}
Expand All @@ -272,7 +273,7 @@ func (conn *HvsockConn) CloseRead() error {
// CloseWrite shuts down the write end of the socket, notifying the other endpoint that
// no more data will be written.
func (conn *HvsockConn) CloseWrite() error {
err := conn.shutdown(syscall.SHUT_WR)
err := conn.shutdown(windows.SHUT_WR)
if err != nil {
return conn.opErr("close", err)
}
Expand Down
22 changes: 12 additions & 10 deletions pipe.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"syscall"
"time"
"unsafe"

"golang.org/x/sys/windows"
)

//sys connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) = ConnectNamedPipe
Expand Down Expand Up @@ -65,10 +67,10 @@ func (status ntstatus) Err() error {
}

const (
cERROR_PIPE_BUSY = syscall.Errno(231)
cERROR_NO_DATA = syscall.Errno(232)
cERROR_PIPE_CONNECTED = syscall.Errno(535)
cERROR_SEM_TIMEOUT = syscall.Errno(121)
cERROR_PIPE_BUSY = windows.ERROR_PIPE_BUSY
cERROR_NO_DATA = windows.ERROR_NO_DATA
cERROR_PIPE_CONNECTED = windows.ERROR_PIPE_CONNECTED
cERROR_SEM_TIMEOUT = windows.ERROR_SEM_TIMEOUT

cSECURITY_SQOS_PRESENT = 0x100000
cSECURITY_ANONYMOUS = 0
Expand Down Expand Up @@ -164,7 +166,7 @@ func (f *win32MessageBytePipe) Read(b []byte) (int, error) {
// zero-byte message, ensure that all future Read() calls
// also return EOF.
f.readEOF = true
} else if err == syscall.ERROR_MORE_DATA {
} else if err == windows.ERROR_MORE_DATA {
// ERROR_MORE_DATA indicates that the pipe's read mode is message mode
// and the message still has more bytes. Treat this as a success, since
// this package presents all named pipes as byte streams.
Expand All @@ -189,7 +191,7 @@ func tryDialPipe(ctx context.Context, path *string, access uint32) (syscall.Hand
case <-ctx.Done():
return syscall.Handle(0), ctx.Err()
default:
h, err := createFile(*path, access, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0)
h, err := createFile(*path, access, 0, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0)
if err == nil {
return h, nil
}
Expand Down Expand Up @@ -224,7 +226,7 @@ func DialPipe(path string, timeout *time.Duration) (net.Conn, error) {
// DialPipeContext attempts to connect to a named pipe by `path` until `ctx`
// cancellation or timeout.
func DialPipeContext(ctx context.Context, path string) (net.Conn, error) {
return DialPipeAccess(ctx, path, syscall.GENERIC_READ|syscall.GENERIC_WRITE)
return DialPipeAccess(ctx, path, windows.GENERIC_READ|windows.GENERIC_WRITE)
}

// DialPipeAccess attempts to connect to a named pipe by `path` with `access` until `ctx`
Expand Down Expand Up @@ -320,13 +322,13 @@ func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (sy
}

disposition := uint32(cFILE_OPEN)
access := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE | syscall.SYNCHRONIZE)
access := uint32(windows.GENERIC_READ | windows.GENERIC_WRITE | windows.SYNCHRONIZE)
if first {
disposition = cFILE_CREATE
// By not asking for read or write access, the named pipe file system
// will put this pipe into an initially disconnected state, blocking
// client connections until the next call with first == false.
access = syscall.SYNCHRONIZE
access = windows.SYNCHRONIZE
}

timeout := int64(-50 * 10000) // 50ms
Expand All @@ -335,7 +337,7 @@ func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (sy
h syscall.Handle
iosb ioStatusBlock
)
err = ntCreateNamedPipeFile(&h, access, &oa, &iosb, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE, disposition, 0, typ, 0, 0, 0xffffffff, uint32(c.InputBufferSize), uint32(c.OutputBufferSize), &timeout).Err()
err = ntCreateNamedPipeFile(&h, access, &oa, &iosb, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, disposition, 0, typ, 0, 0, 0xffffffff, uint32(c.InputBufferSize), uint32(c.OutputBufferSize), &timeout).Err()
if err != nil {
return 0, &os.PathError{Op: "open", Path: path, Err: err}
}
Expand Down
6 changes: 4 additions & 2 deletions pipe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"testing"
"time"
"unsafe"

"golang.org/x/sys/windows"
)

var testPipeName = `\\.\pipe\winiotestpipe`
Expand All @@ -22,7 +24,7 @@ var aLongTimeAgo = time.Unix(1, 0)

func TestDialUnknownFailsImmediately(t *testing.T) {
_, err := DialPipe(testPipeName, nil)
if err.(*os.PathError).Err != syscall.ENOENT {
if err.(*os.PathError).Err != windows.ERROR_FILE_NOT_FOUND {
t.Fatalf("expected ENOENT got %v", err)
}
}
Expand Down Expand Up @@ -84,7 +86,7 @@ func TestDialAccessDeniedWithRestrictedSD(t *testing.T) {
}
defer l.Close()
_, err = DialPipe(testPipeName, nil)
if err.(*os.PathError).Err != syscall.ERROR_ACCESS_DENIED {
if err.(*os.PathError).Err != windows.ERROR_ACCESS_DENIED {
t.Fatalf("expected ERROR_ACCESS_DENIED, got %v", err)
}
}
Expand Down
7 changes: 4 additions & 3 deletions pkg/security/grantvmgroupaccess.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"unsafe"

"github.com/pkg/errors"
"golang.org/x/sys/windows"
)

type (
Expand Down Expand Up @@ -114,11 +115,11 @@ func createFile(name string, isDir bool) (syscall.Handle, error) {
namep := syscall.StringToUTF16(name)
da := uint32(desiredAccessReadControl | desiredAccessWriteDac)
sm := uint32(shareModeRead | shareModeWrite)
fa := uint32(syscall.FILE_ATTRIBUTE_NORMAL)
fa := uint32(windows.FILE_ATTRIBUTE_NORMAL)
if isDir {
fa = uint32(fa | syscall.FILE_FLAG_BACKUP_SEMANTICS)
fa = uint32(fa | windows.FILE_FLAG_BACKUP_SEMANTICS)
}
fd, err := syscall.CreateFile(&namep[0], da, sm, nil, syscall.OPEN_EXISTING, fa, 0)
fd, err := syscall.CreateFile(&namep[0], da, sm, nil, windows.OPEN_EXISTING, fa, 0)
if err != nil {
return 0, errors.Wrapf(err, "%s syscall.CreateFile %s", gvmga, name)
}
Expand Down
7 changes: 3 additions & 4 deletions privilege.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"fmt"
"runtime"
"sync"
"syscall"
"unicode/utf16"

"golang.org/x/sys/windows"
Expand All @@ -24,9 +23,9 @@ import (
//sys lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW

const (
SE_PRIVILEGE_ENABLED = 2
SE_PRIVILEGE_ENABLED = windows.SE_PRIVILEGE_ENABLED

ERROR_NOT_ALL_ASSIGNED syscall.Errno = 1300
ERROR_NOT_ALL_ASSIGNED = windows.ERROR_NOT_ALL_ASSIGNED

SeBackupPrivilege = "SeBackupPrivilege"
SeRestorePrivilege = "SeRestorePrivilege"
Expand Down Expand Up @@ -183,7 +182,7 @@ func newThreadToken() (windows.Token, error) {
}

var token windows.Token
err = openThreadToken(getCurrentThread(), syscall.TOKEN_ADJUST_PRIVILEGES|syscall.TOKEN_QUERY, false, &token)
err = openThreadToken(getCurrentThread(), windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, false, &token)
if err != nil {
rerr := revertToSelf()
if rerr != nil {
Expand Down
6 changes: 4 additions & 2 deletions reparse.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ import (
"strings"
"unicode/utf16"
"unsafe"

"golang.org/x/sys/windows"
)

const (
reparseTagMountPoint = 0xA0000003
reparseTagSymlink = 0xA000000C
reparseTagMountPoint = windows.IO_REPARSE_TAG_MOUNT_POINT
reparseTagSymlink = windows.IO_REPARSE_TAG_SYMLINK
)

type reparseDataBuffer struct {
Expand Down
6 changes: 4 additions & 2 deletions sd.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ package winio
import (
"syscall"
"unsafe"

"golang.org/x/sys/windows"
)

//sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW
Expand All @@ -15,7 +17,7 @@ import (
//sys getSecurityDescriptorLength(sd uintptr) (len uint32) = advapi32.GetSecurityDescriptorLength

const (
cERROR_NONE_MAPPED = syscall.Errno(1332)
cERROR_NONE_MAPPED = windows.ERROR_NONE_MAPPED
)

type AccountLookupError struct {
Expand Down Expand Up @@ -54,7 +56,7 @@ func LookupSidByName(name string) (sid string, err error) {

var sidSize, sidNameUse, refDomainSize uint32
err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse)
if err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER {
if err != nil && err != windows.ERROR_INSUFFICIENT_BUFFER {
return "", &AccountLookupError{name, err}
}
sidBuffer := make([]byte, sidSize)
Expand Down

0 comments on commit bb021fd

Please sign in to comment.