mirror of
https://gitea.com/gitea/runner.git
synced 2026-11-16 12:53:42 +00:00
fix build for windows
This commit is contained in:
1561 files changed
+11
-501961
No files matched your search
@@ -22,7 +22,6 @@ jobs:
|
|||||||
- run: go test -cover ./...
|
- run: go test -cover ./...
|
||||||
env:
|
env:
|
||||||
CGO_ENABLED: 0
|
CGO_ENABLED: 0
|
||||||
GOFLAGS: -mod=vendor
|
|
||||||
|
|
||||||
release:
|
release:
|
||||||
if: startsWith(github.ref, 'refs/tags/v')
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
builds:
|
builds:
|
||||||
- env:
|
- env:
|
||||||
- CGO_ENABLED=0
|
- CGO_ENABLED=0
|
||||||
- GOFLAGS=-mod=vendor
|
|
||||||
goos:
|
goos:
|
||||||
- darwin
|
- darwin
|
||||||
- linux
|
- linux
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ installer:
|
|||||||
@GO111MODULE=off go get github.com/goreleaser/godownloader
|
@GO111MODULE=off go get github.com/goreleaser/godownloader
|
||||||
godownloader -r nektos/act -o install.sh
|
godownloader -r nektos/act -o install.sh
|
||||||
|
|
||||||
promote: vendor
|
promote:
|
||||||
@git fetch --tags
|
@git fetch --tags
|
||||||
@echo "VERSION:$(VERSION) IS_SNAPSHOT:$(IS_SNAPSHOT) NEW_VERSION:$(NEW_VERSION)"
|
@echo "VERSION:$(VERSION) IS_SNAPSHOT:$(IS_SNAPSHOT) NEW_VERSION:$(NEW_VERSION)"
|
||||||
ifeq (false,$(IS_SNAPSHOT))
|
ifeq (false,$(IS_SNAPSHOT))
|
||||||
@@ -36,8 +36,3 @@ ifneq ($(shell git status -s),)
|
|||||||
endif
|
endif
|
||||||
git tag -a -m "releasing v$(NEW_VERSION)" v$(NEW_VERSION)
|
git tag -a -m "releasing v$(NEW_VERSION)" v$(NEW_VERSION)
|
||||||
git push origin v$(NEW_VERSION)
|
git push origin v$(NEW_VERSION)
|
||||||
|
|
||||||
vendor:
|
|
||||||
go mod vendor
|
|
||||||
|
|
||||||
.PHONY: vendor
|
|
||||||
@@ -9,7 +9,7 @@ require (
|
|||||||
github.com/andreaskoch/go-fswatch v1.0.0
|
github.com/andreaskoch/go-fswatch v1.0.0
|
||||||
github.com/containerd/containerd v1.3.3 // indirect
|
github.com/containerd/containerd v1.3.3 // indirect
|
||||||
github.com/docker/distribution v2.7.1+incompatible // indirect
|
github.com/docker/distribution v2.7.1+incompatible // indirect
|
||||||
github.com/docker/docker v1.4.2-0.20200229013735-71373c6105e3
|
github.com/docker/docker v0.0.0-20200229013735-71373c6105e3
|
||||||
github.com/docker/go-connections v0.4.0 // indirect
|
github.com/docker/go-connections v0.4.0 // indirect
|
||||||
github.com/emirpasic/gods v1.12.0 // indirect
|
github.com/emirpasic/gods v1.12.0 // indirect
|
||||||
github.com/go-ini/ini v1.41.0
|
github.com/go-ini/ini v1.41.0
|
||||||
@@ -49,3 +49,6 @@ require (
|
|||||||
gopkg.in/yaml.v3 v3.0.0-20200121175148-a6ecf24a6d71
|
gopkg.in/yaml.v3 v3.0.0-20200121175148-a6ecf24a6d71
|
||||||
gotest.tools v2.2.0+incompatible
|
gotest.tools v2.2.0+incompatible
|
||||||
)
|
)
|
||||||
|
|
||||||
|
replace github.com/docker/docker => github.com/docker/docker v0.0.0-20200229013735-71373c6105e3
|
||||||
|
replace golang.org/x/sys => golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a
|
||||||
@@ -33,8 +33,10 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
|||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug=
|
github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug=
|
||||||
github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
|
github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
|
||||||
github.com/docker/docker v1.4.2-0.20200229013735-71373c6105e3 h1:rQeprWgRziyxTHx4/mEhwjbAiFUbrk0Kqe9KlcWBnZU=
|
github.com/docker/docker v0.0.0-20200229013735-71373c6105e3 h1:hq9QaRK9JJOg7GItpuSSA3MrBoEN3c3llxQappEq9Zo=
|
||||||
github.com/docker/docker v1.4.2-0.20200229013735-71373c6105e3/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
github.com/docker/docker v0.0.0-20200229013735-71373c6105e3/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||||
|
github.com/docker/engine v0.0.0-20200229013735-71373c6105e3 h1:xs/w1ExeiC4z1BBprZxoNrSkBQ4B4CzGqPkH0c/o5xk=
|
||||||
|
github.com/docker/engine v0.0.0-20200229013735-71373c6105e3/go.mod h1:3CPr2caMgTHxxIAZgEMd3uLYPDlRvPqCpyeRf6ncPcY=
|
||||||
github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=
|
github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=
|
||||||
github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
|
github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
|
||||||
github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw=
|
github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw=
|
||||||
@@ -186,6 +188,8 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h
|
|||||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190514135907-3a4b5fb9f71f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190514135907-3a4b5fb9f71f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ=
|
||||||
|
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9 h1:ZBzSG/7F4eNKz2L3GE9o300RX0Az1Bw5HF7PDraD+qU=
|
golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9 h1:ZBzSG/7F4eNKz2L3GE9o300RX0Az1Bw5HF7PDraD+qU=
|
||||||
golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
|||||||
-25
@@ -1,25 +0,0 @@
|
|||||||
walk
|
|
||||||
====
|
|
||||||
|
|
||||||
Fast parallel version of golang filepath.Walk()
|
|
||||||
|
|
||||||
Performs traversals in parallel so set GOMAXPROCS appropriately. Vaues of 8 to 16 seem to work best on my
|
|
||||||
4-CPU plus 4 SMT pseudo-CPU MacBookPro. The result is about 4x-6x the traversal rate of the standard Walk().
|
|
||||||
The two are not identical since we are walking the file system in a tumult of asynchronous walkFunc calls by
|
|
||||||
a number of goroutines. So, take note of the following:
|
|
||||||
|
|
||||||
1. This walk honors all of the walkFunc error semantics but as multiple user-supplied walkFuncs may simultaneously encounter a traversal error or generate one to stop traversal, only the FIRST of these will be returned as the Walk() result.
|
|
||||||
|
|
||||||
2. Further, since there may be a few files in flight at the instant of error discovery, a few more walkFunc calls may happen after the first error-generating call has signaled its desire to stop. In general this is a non-issue but it could matter so pay attention when designing your walkFunc. (For example, if you accumulate results then you need to have your own means to know to stop accumulating once you signal an error.)
|
|
||||||
|
|
||||||
3. Because the walkFunc is called concurrently in multiple goroutines, it needs to be careful about what it does with external data to avoid collisions. Results may be printed using fmt, but generally the best plan is to send results over a channel or accumulate counts using a locked mutex.
|
|
||||||
|
|
||||||
These issues are illustrated/handled in the simple traversal programs supplied with walk. There is also a test file that is just the tests from filepath in the Go language's standard library. Walk passes these tests when run in single process mode, and passes most of them in concurrent mode (GOMAXPROCS > 1). The problem is not a real problem, but one of the test expecting a specific number of errors to be found based on presumed sequential traversals.
|
|
||||||
|
|
||||||
Copyright (c) 2016 Michael T Jones
|
|
||||||
|
|
||||||
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.
|
|
||||||
-30
@@ -1,30 +0,0 @@
|
|||||||
// Copyright 2010 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package walk
|
|
||||||
|
|
||||||
import "strings"
|
|
||||||
|
|
||||||
// IsAbs returns true if the path is absolute.
|
|
||||||
func IsAbs(path string) bool {
|
|
||||||
return strings.HasPrefix(path, "/") || strings.HasPrefix(path, "#")
|
|
||||||
}
|
|
||||||
|
|
||||||
// volumeNameLen returns length of the leading volume name on Windows.
|
|
||||||
// It returns 0 elsewhere.
|
|
||||||
func volumeNameLen(path string) int {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// HasPrefix exists for historical compatibility and should not be used.
|
|
||||||
func HasPrefix(p, prefix string) bool {
|
|
||||||
return strings.HasPrefix(p, prefix)
|
|
||||||
}
|
|
||||||
|
|
||||||
func splitList(path string) []string {
|
|
||||||
if path == "" {
|
|
||||||
return []string{}
|
|
||||||
}
|
|
||||||
return strings.Split(path, string(ListSeparator))
|
|
||||||
}
|
|
||||||
-32
@@ -1,32 +0,0 @@
|
|||||||
// Copyright 2010 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
|
|
||||||
|
|
||||||
package walk
|
|
||||||
|
|
||||||
import "strings"
|
|
||||||
|
|
||||||
// IsAbs returns true if the path is absolute.
|
|
||||||
func IsAbs(path string) bool {
|
|
||||||
return strings.HasPrefix(path, "/")
|
|
||||||
}
|
|
||||||
|
|
||||||
// volumeNameLen returns length of the leading volume name on Windows.
|
|
||||||
// It returns 0 elsewhere.
|
|
||||||
func volumeNameLen(path string) int {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// HasPrefix exists for historical compatibility and should not be used.
|
|
||||||
func HasPrefix(p, prefix string) bool {
|
|
||||||
return strings.HasPrefix(p, prefix)
|
|
||||||
}
|
|
||||||
|
|
||||||
func splitList(path string) []string {
|
|
||||||
if path == "" {
|
|
||||||
return []string{}
|
|
||||||
}
|
|
||||||
return strings.Split(path, string(ListSeparator))
|
|
||||||
}
|
|
||||||
-105
@@ -1,105 +0,0 @@
|
|||||||
// Copyright 2010 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package walk
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func isSlash(c uint8) bool {
|
|
||||||
return c == '\\' || c == '/'
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsAbs returns true if the path is absolute.
|
|
||||||
func IsAbs(path string) (b bool) {
|
|
||||||
l := volumeNameLen(path)
|
|
||||||
if l == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
path = path[l:]
|
|
||||||
if path == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return isSlash(path[0])
|
|
||||||
}
|
|
||||||
|
|
||||||
// volumeNameLen returns length of the leading volume name on Windows.
|
|
||||||
// It returns 0 elsewhere.
|
|
||||||
func volumeNameLen(path string) int {
|
|
||||||
if len(path) < 2 {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
// with drive letter
|
|
||||||
c := path[0]
|
|
||||||
if path[1] == ':' && ('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') {
|
|
||||||
return 2
|
|
||||||
}
|
|
||||||
// is it UNC
|
|
||||||
if l := len(path); l >= 5 && isSlash(path[0]) && isSlash(path[1]) &&
|
|
||||||
!isSlash(path[2]) && path[2] != '.' {
|
|
||||||
// first, leading `\\` and next shouldn't be `\`. its server name.
|
|
||||||
for n := 3; n < l-1; n++ {
|
|
||||||
// second, next '\' shouldn't be repeated.
|
|
||||||
if isSlash(path[n]) {
|
|
||||||
n++
|
|
||||||
// third, following something characters. its share name.
|
|
||||||
if !isSlash(path[n]) {
|
|
||||||
if path[n] == '.' {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
for ; n < l; n++ {
|
|
||||||
if isSlash(path[n]) {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// HasPrefix exists for historical compatibility and should not be used.
|
|
||||||
func HasPrefix(p, prefix string) bool {
|
|
||||||
if strings.HasPrefix(p, prefix) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return strings.HasPrefix(strings.ToLower(p), strings.ToLower(prefix))
|
|
||||||
}
|
|
||||||
|
|
||||||
func splitList(path string) []string {
|
|
||||||
// The same implementation is used in LookPath in os/exec;
|
|
||||||
// consider changing os/exec when changing this.
|
|
||||||
|
|
||||||
if path == "" {
|
|
||||||
return []string{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Split path, respecting but preserving quotes.
|
|
||||||
list := []string{}
|
|
||||||
start := 0
|
|
||||||
quo := false
|
|
||||||
for i := 0; i < len(path); i++ {
|
|
||||||
switch c := path[i]; {
|
|
||||||
case c == '"':
|
|
||||||
quo = !quo
|
|
||||||
case c == ListSeparator && !quo:
|
|
||||||
list = append(list, path[start:i])
|
|
||||||
start = i + 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
list = append(list, path[start:])
|
|
||||||
|
|
||||||
// Remove quotes.
|
|
||||||
for i, s := range list {
|
|
||||||
if strings.Contains(s, `"`) {
|
|
||||||
list[i] = strings.Replace(s, `"`, ``, -1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return list
|
|
||||||
}
|
|
||||||
-67
@@ -1,67 +0,0 @@
|
|||||||
// Copyright 2012 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
// +build !windows
|
|
||||||
|
|
||||||
package walk
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"errors"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func evalSymlinks(path string) (string, error) {
|
|
||||||
const maxIter = 255
|
|
||||||
originalPath := path
|
|
||||||
// consume path by taking each frontmost path element,
|
|
||||||
// expanding it if it's a symlink, and appending it to b
|
|
||||||
var b bytes.Buffer
|
|
||||||
for n := 0; path != ""; n++ {
|
|
||||||
if n > maxIter {
|
|
||||||
return "", errors.New("EvalSymlinks: too many links in " + originalPath)
|
|
||||||
}
|
|
||||||
|
|
||||||
// find next path component, p
|
|
||||||
i := strings.IndexRune(path, Separator)
|
|
||||||
var p string
|
|
||||||
if i == -1 {
|
|
||||||
p, path = path, ""
|
|
||||||
} else {
|
|
||||||
p, path = path[:i], path[i+1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
if p == "" {
|
|
||||||
if b.Len() == 0 {
|
|
||||||
// must be absolute path
|
|
||||||
b.WriteRune(Separator)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
fi, err := os.Lstat(b.String() + p)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if fi.Mode()&os.ModeSymlink == 0 {
|
|
||||||
b.WriteString(p)
|
|
||||||
if path != "" {
|
|
||||||
b.WriteRune(Separator)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// it's a symlink, put it at the front of path
|
|
||||||
dest, err := os.Readlink(b.String() + p)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if IsAbs(dest) {
|
|
||||||
b.Reset()
|
|
||||||
}
|
|
||||||
path = dest + string(Separator) + path
|
|
||||||
}
|
|
||||||
return Clean(b.String()), nil
|
|
||||||
}
|
|
||||||
-69
@@ -1,69 +0,0 @@
|
|||||||
// Copyright 2012 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package walk
|
|
||||||
|
|
||||||
import (
|
|
||||||
"syscall"
|
|
||||||
)
|
|
||||||
|
|
||||||
func toShort(path string) (string, error) {
|
|
||||||
p, err := syscall.UTF16FromString(path)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
b := p // GetShortPathName says we can reuse buffer
|
|
||||||
n, err := syscall.GetShortPathName(&p[0], &b[0], uint32(len(b)))
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if n > uint32(len(b)) {
|
|
||||||
b = make([]uint16, n)
|
|
||||||
n, err = syscall.GetShortPathName(&p[0], &b[0], uint32(len(b)))
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return syscall.UTF16ToString(b), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func toLong(path string) (string, error) {
|
|
||||||
p, err := syscall.UTF16FromString(path)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
b := p // GetLongPathName says we can reuse buffer
|
|
||||||
n, err := syscall.GetLongPathName(&p[0], &b[0], uint32(len(b)))
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if n > uint32(len(b)) {
|
|
||||||
b = make([]uint16, n)
|
|
||||||
n, err = syscall.GetLongPathName(&p[0], &b[0], uint32(len(b)))
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
b = b[:n]
|
|
||||||
return syscall.UTF16ToString(b), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func evalSymlinks(path string) (string, error) {
|
|
||||||
p, err := toShort(path)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
p, err = toLong(p)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
// syscall.GetLongPathName does not change the case of the drive letter,
|
|
||||||
// but the result of EvalSymlinks must be unique, so we have
|
|
||||||
// EvalSymlinks(`c:\a`) == EvalSymlinks(`C:\a`).
|
|
||||||
// Make drive letter upper case.
|
|
||||||
if len(p) >= 2 && p[1] == ':' && 'a' <= p[0] && p[0] <= 'z' {
|
|
||||||
p = string(p[0]+'A'-'a') + p[1:]
|
|
||||||
}
|
|
||||||
return Clean(p), nil
|
|
||||||
}
|
|
||||||
-444
@@ -1,444 +0,0 @@
|
|||||||
// Copyright 2009 The Go Authors. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
// Package filepath implements utility routines for manipulating filename paths
|
|
||||||
// in a way compatible with the target operating system-defined file paths.
|
|
||||||
package walk
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"os"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SkipDir is used as a return value from WalkFuncs to indicate that
|
|
||||||
// the directory named in the call is to be skipped. It is not returned
|
|
||||||
// as an error by any function.
|
|
||||||
var SkipDir = errors.New("skip this directory")
|
|
||||||
|
|
||||||
// WalkFunc is the type of the function called for each file or directory
|
|
||||||
// visited by Walk. The path argument contains the argument to Walk as a
|
|
||||||
// prefix; that is, if Walk is called with "dir", which is a directory
|
|
||||||
// containing the file "a", the walk function will be called with argument
|
|
||||||
// "dir/a". The info argument is the os.FileInfo for the named path.
|
|
||||||
//
|
|
||||||
// If there was a problem walking to the file or directory named by path, the
|
|
||||||
// incoming error will describe the problem and the function can decide how
|
|
||||||
// to handle that error (and Walk will not descend into that directory). If
|
|
||||||
// an error is returned, processing stops. The sole exception is that if path
|
|
||||||
// is a directory and the function returns the special value SkipDir, the
|
|
||||||
// contents of the directory are skipped and processing continues as usual on
|
|
||||||
// the next file.
|
|
||||||
type WalkFunc func(path string, info os.FileInfo, err error) error
|
|
||||||
|
|
||||||
var lstat = os.Lstat // for testing
|
|
||||||
var LstatP = &lstat
|
|
||||||
|
|
||||||
type VisitData struct {
|
|
||||||
path string
|
|
||||||
info os.FileInfo
|
|
||||||
}
|
|
||||||
|
|
||||||
type WalkState struct {
|
|
||||||
walkFn WalkFunc
|
|
||||||
v chan VisitData // files to be processed
|
|
||||||
active sync.WaitGroup // number of files to process
|
|
||||||
lock sync.RWMutex
|
|
||||||
firstError error // accessed using lock
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WalkState) terminated() bool {
|
|
||||||
ws.lock.RLock()
|
|
||||||
done := ws.firstError != nil
|
|
||||||
ws.lock.RUnlock()
|
|
||||||
return done
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WalkState) setTerminated(err error) {
|
|
||||||
ws.lock.Lock()
|
|
||||||
if ws.firstError == nil {
|
|
||||||
ws.firstError = err
|
|
||||||
}
|
|
||||||
ws.lock.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WalkState) visitChannel() {
|
|
||||||
for file := range ws.v {
|
|
||||||
ws.visitFile(file)
|
|
||||||
ws.active.Add(-1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WalkState) visitFile(file VisitData) {
|
|
||||||
if ws.terminated() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err := ws.walkFn(file.path, file.info, nil)
|
|
||||||
if err != nil {
|
|
||||||
if !(file.info.IsDir() && err == SkipDir) {
|
|
||||||
ws.setTerminated(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !file.info.IsDir() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
names, err := readDirNames(file.path)
|
|
||||||
if err != nil {
|
|
||||||
err = ws.walkFn(file.path, file.info, err)
|
|
||||||
if err != nil {
|
|
||||||
ws.setTerminated(err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
here := file.path
|
|
||||||
for _, name := range names {
|
|
||||||
file.path = Join(here, name)
|
|
||||||
file.info, err = lstat(file.path)
|
|
||||||
if err != nil {
|
|
||||||
err = ws.walkFn(file.path, file.info, err)
|
|
||||||
if err != nil && (!file.info.IsDir() || err != SkipDir) {
|
|
||||||
ws.setTerminated(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
switch file.info.IsDir() {
|
|
||||||
case true:
|
|
||||||
ws.active.Add(1) // presume channel send will succeed
|
|
||||||
select {
|
|
||||||
case ws.v <- file:
|
|
||||||
// push directory info to queue for concurrent traversal
|
|
||||||
default:
|
|
||||||
// undo increment when send fails and handle now
|
|
||||||
ws.active.Add(-1)
|
|
||||||
ws.visitFile(file)
|
|
||||||
}
|
|
||||||
case false:
|
|
||||||
err = ws.walkFn(file.path, file.info, nil)
|
|
||||||
if err != nil {
|
|
||||||
ws.setTerminated(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Walk walks the file tree rooted at root, calling walkFn for each file or
|
|
||||||
// directory in the tree, including root. All errors that arise visiting files
|
|
||||||
// and directories are filtered by walkFn. The files are walked in a random
|
|
||||||
// order. Walk does not follow symbolic links.
|
|
||||||
|
|
||||||
func Walk(root string, walkFn WalkFunc) error {
|
|
||||||
info, err := os.Lstat(root)
|
|
||||||
if err != nil {
|
|
||||||
return walkFn(root, nil, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ws := &WalkState{
|
|
||||||
walkFn: walkFn,
|
|
||||||
v: make(chan VisitData, 1024),
|
|
||||||
}
|
|
||||||
defer close(ws.v)
|
|
||||||
|
|
||||||
ws.active.Add(1)
|
|
||||||
ws.v <- VisitData{root, info}
|
|
||||||
|
|
||||||
walkers := 16
|
|
||||||
for i := 0; i < walkers; i++ {
|
|
||||||
go ws.visitChannel()
|
|
||||||
}
|
|
||||||
ws.active.Wait()
|
|
||||||
|
|
||||||
return ws.firstError
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
// THE REMAINDER IS UNCHANGED FROM THE ORGINAL GO LIBRARY ORIGINAL
|
|
||||||
//
|
|
||||||
|
|
||||||
// readDirNames reads the directory named by dirname and returns
|
|
||||||
// a sorted list of directory entries.
|
|
||||||
func readDirNames(dirname string) ([]string, error) {
|
|
||||||
f, err := os.Open(dirname)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
names, err := f.Readdirnames(-1)
|
|
||||||
f.Close()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
sort.Strings(names) // omit sort to save 1-2%
|
|
||||||
return names, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// A lazybuf is a lazily constructed path buffer.
|
|
||||||
// It supports append, reading previously appended bytes,
|
|
||||||
// and retrieving the final string. It does not allocate a buffer
|
|
||||||
// to hold the output until that output diverges from s.
|
|
||||||
type lazybuf struct {
|
|
||||||
path string
|
|
||||||
buf []byte
|
|
||||||
w int
|
|
||||||
volAndPath string
|
|
||||||
volLen int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *lazybuf) index(i int) byte {
|
|
||||||
if b.buf != nil {
|
|
||||||
return b.buf[i]
|
|
||||||
}
|
|
||||||
return b.path[i]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *lazybuf) append(c byte) {
|
|
||||||
if b.buf == nil {
|
|
||||||
if b.w < len(b.path) && b.path[b.w] == c {
|
|
||||||
b.w++
|
|
||||||
return
|
|
||||||
}
|
|
||||||
b.buf = make([]byte, len(b.path))
|
|
||||||
copy(b.buf, b.path[:b.w])
|
|
||||||
}
|
|
||||||
b.buf[b.w] = c
|
|
||||||
b.w++
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *lazybuf) string() string {
|
|
||||||
if b.buf == nil {
|
|
||||||
return b.volAndPath[:b.volLen+b.w]
|
|
||||||
}
|
|
||||||
return b.volAndPath[:b.volLen] + string(b.buf[:b.w])
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
Separator = os.PathSeparator
|
|
||||||
ListSeparator = os.PathListSeparator
|
|
||||||
)
|
|
||||||
|
|
||||||
// Clean returns the shortest path name equivalent to path
|
|
||||||
// by purely lexical processing. It applies the following rules
|
|
||||||
// iteratively until no further processing can be done:
|
|
||||||
//
|
|
||||||
// 1. Replace multiple Separator elements with a single one.
|
|
||||||
// 2. Eliminate each . path name element (the current directory).
|
|
||||||
// 3. Eliminate each inner .. path name element (the parent directory)
|
|
||||||
// along with the non-.. element that precedes it.
|
|
||||||
// 4. Eliminate .. elements that begin a rooted path:
|
|
||||||
// that is, replace "/.." by "/" at the beginning of a path,
|
|
||||||
// assuming Separator is '/'.
|
|
||||||
//
|
|
||||||
// The returned path ends in a slash only if it represents a root directory,
|
|
||||||
// such as "/" on Unix or `C:\` on Windows.
|
|
||||||
//
|
|
||||||
// If the result of this process is an empty string, Clean
|
|
||||||
// returns the string ".".
|
|
||||||
//
|
|
||||||
// See also Rob Pike, ``Lexical File Names in Plan 9 or
|
|
||||||
// Getting Dot-Dot Right,''
|
|
||||||
// http://plan9.bell-labs.com/sys/doc/lexnames.html
|
|
||||||
func Clean(path string) string {
|
|
||||||
originalPath := path
|
|
||||||
volLen := volumeNameLen(path)
|
|
||||||
path = path[volLen:]
|
|
||||||
if path == "" {
|
|
||||||
if volLen > 1 && originalPath[1] != ':' {
|
|
||||||
// should be UNC
|
|
||||||
return FromSlash(originalPath)
|
|
||||||
}
|
|
||||||
return originalPath + "."
|
|
||||||
}
|
|
||||||
rooted := os.IsPathSeparator(path[0])
|
|
||||||
|
|
||||||
// Invariants:
|
|
||||||
// reading from path; r is index of next byte to process.
|
|
||||||
// writing to buf; w is index of next byte to write.
|
|
||||||
// dotdot is index in buf where .. must stop, either because
|
|
||||||
// it is the leading slash or it is a leading ../../.. prefix.
|
|
||||||
n := len(path)
|
|
||||||
out := lazybuf{path: path, volAndPath: originalPath, volLen: volLen}
|
|
||||||
r, dotdot := 0, 0
|
|
||||||
if rooted {
|
|
||||||
out.append(Separator)
|
|
||||||
r, dotdot = 1, 1
|
|
||||||
}
|
|
||||||
|
|
||||||
for r < n {
|
|
||||||
switch {
|
|
||||||
case os.IsPathSeparator(path[r]):
|
|
||||||
// empty path element
|
|
||||||
r++
|
|
||||||
case path[r] == '.' && (r+1 == n || os.IsPathSeparator(path[r+1])):
|
|
||||||
// . element
|
|
||||||
r++
|
|
||||||
case path[r] == '.' && path[r+1] == '.' && (r+2 == n || os.IsPathSeparator(path[r+2])):
|
|
||||||
// .. element: remove to last separator
|
|
||||||
r += 2
|
|
||||||
switch {
|
|
||||||
case out.w > dotdot:
|
|
||||||
// can backtrack
|
|
||||||
out.w--
|
|
||||||
for out.w > dotdot && !os.IsPathSeparator(out.index(out.w)) {
|
|
||||||
out.w--
|
|
||||||
}
|
|
||||||
case !rooted:
|
|
||||||
// cannot backtrack, but not rooted, so append .. element.
|
|
||||||
if out.w > 0 {
|
|
||||||
out.append(Separator)
|
|
||||||
}
|
|
||||||
out.append('.')
|
|
||||||
out.append('.')
|
|
||||||
dotdot = out.w
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
// real path element.
|
|
||||||
// add slash if needed
|
|
||||||
if rooted && out.w != 1 || !rooted && out.w != 0 {
|
|
||||||
out.append(Separator)
|
|
||||||
}
|
|
||||||
// copy element
|
|
||||||
for ; r < n && !os.IsPathSeparator(path[r]); r++ {
|
|
||||||
out.append(path[r])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Turn empty string into "."
|
|
||||||
if out.w == 0 {
|
|
||||||
out.append('.')
|
|
||||||
}
|
|
||||||
|
|
||||||
return FromSlash(out.string())
|
|
||||||
}
|
|
||||||
|
|
||||||
// ToSlash returns the result of replacing each separator character
|
|
||||||
// in path with a slash ('/') character. Multiple separators are
|
|
||||||
// replaced by multiple slashes.
|
|
||||||
func ToSlash(path string) string {
|
|
||||||
if Separator == '/' {
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
return strings.Replace(path, string(Separator), "/", -1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// FromSlash returns the result of replacing each slash ('/') character
|
|
||||||
// in path with a separator character. Multiple slashes are replaced
|
|
||||||
// by multiple separators.
|
|
||||||
func FromSlash(path string) string {
|
|
||||||
if Separator == '/' {
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
return strings.Replace(path, "/", string(Separator), -1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Join joins any number of path elements into a single path, adding
|
|
||||||
// a Separator if necessary. The result is Cleaned, in particular
|
|
||||||
// all empty strings are ignored.
|
|
||||||
func Join(elem ...string) string {
|
|
||||||
for i, e := range elem {
|
|
||||||
if e != "" {
|
|
||||||
return Clean(strings.Join(elem[i:], string(Separator)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// Rel returns a relative path that is lexically equivalent to targpath when
|
|
||||||
// joined to basepath with an intervening separator. That is,
|
|
||||||
// Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself.
|
|
||||||
// On success, the returned path will always be relative to basepath,
|
|
||||||
// even if basepath and targpath share no elements.
|
|
||||||
// An error is returned if targpath can't be made relative to basepath or if
|
|
||||||
// knowing the current working directory would be necessary to compute it.
|
|
||||||
func Rel(basepath, targpath string) (string, error) {
|
|
||||||
baseVol := VolumeName(basepath)
|
|
||||||
targVol := VolumeName(targpath)
|
|
||||||
base := Clean(basepath)
|
|
||||||
targ := Clean(targpath)
|
|
||||||
if targ == base {
|
|
||||||
return ".", nil
|
|
||||||
}
|
|
||||||
base = base[len(baseVol):]
|
|
||||||
targ = targ[len(targVol):]
|
|
||||||
if base == "." {
|
|
||||||
base = ""
|
|
||||||
}
|
|
||||||
// Can't use IsAbs - `\a` and `a` are both relative in Windows.
|
|
||||||
baseSlashed := len(base) > 0 && base[0] == Separator
|
|
||||||
targSlashed := len(targ) > 0 && targ[0] == Separator
|
|
||||||
if baseSlashed != targSlashed || baseVol != targVol {
|
|
||||||
return "", errors.New("Rel: can't make " + targ + " relative to " + base)
|
|
||||||
}
|
|
||||||
// Position base[b0:bi] and targ[t0:ti] at the first differing elements.
|
|
||||||
bl := len(base)
|
|
||||||
tl := len(targ)
|
|
||||||
var b0, bi, t0, ti int
|
|
||||||
for {
|
|
||||||
for bi < bl && base[bi] != Separator {
|
|
||||||
bi++
|
|
||||||
}
|
|
||||||
for ti < tl && targ[ti] != Separator {
|
|
||||||
ti++
|
|
||||||
}
|
|
||||||
if targ[t0:ti] != base[b0:bi] {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if bi < bl {
|
|
||||||
bi++
|
|
||||||
}
|
|
||||||
if ti < tl {
|
|
||||||
ti++
|
|
||||||
}
|
|
||||||
b0 = bi
|
|
||||||
t0 = ti
|
|
||||||
}
|
|
||||||
if base[b0:bi] == ".." {
|
|
||||||
return "", errors.New("Rel: can't make " + targ + " relative to " + base)
|
|
||||||
}
|
|
||||||
if b0 != bl {
|
|
||||||
// Base elements left. Must go up before going down.
|
|
||||||
seps := strings.Count(base[b0:bl], string(Separator))
|
|
||||||
size := 2 + seps*3
|
|
||||||
if tl != t0 {
|
|
||||||
size += 1 + tl - t0
|
|
||||||
}
|
|
||||||
buf := make([]byte, size)
|
|
||||||
n := copy(buf, "..")
|
|
||||||
for i := 0; i < seps; i++ {
|
|
||||||
buf[n] = Separator
|
|
||||||
copy(buf[n+1:], "..")
|
|
||||||
n += 3
|
|
||||||
}
|
|
||||||
if t0 != tl {
|
|
||||||
buf[n] = Separator
|
|
||||||
copy(buf[n+1:], targ[t0:])
|
|
||||||
}
|
|
||||||
return string(buf), nil
|
|
||||||
}
|
|
||||||
return targ[t0:], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// VolumeName returns leading volume name.
|
|
||||||
// Given "C:\foo\bar" it returns "C:" under windows.
|
|
||||||
// Given "\\host\share\foo" it returns "\\host\share".
|
|
||||||
// On other platforms it returns "".
|
|
||||||
func VolumeName(path string) (v string) {
|
|
||||||
return path[:volumeNameLen(path)]
|
|
||||||
}
|
|
||||||
|
|
||||||
// EvalSymlinks returns the path name after the evaluation of any symbolic
|
|
||||||
// links.
|
|
||||||
// If path is relative the result will be relative to the current directory,
|
|
||||||
// unless one of the components is an absolute symbolic link.
|
|
||||||
func EvalSymlinks(path string) (string, error) {
|
|
||||||
return evalSymlinks(path)
|
|
||||||
}
|
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
*.exe
|
|
||||||
-22
@@ -1,22 +0,0 @@
|
|||||||
The MIT License (MIT)
|
|
||||||
|
|
||||||
Copyright (c) 2015 Microsoft
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
-22
@@ -1,22 +0,0 @@
|
|||||||
# go-winio
|
|
||||||
|
|
||||||
This repository contains utilities for efficiently performing Win32 IO operations in
|
|
||||||
Go. Currently, this is focused on accessing named pipes and other file handles, and
|
|
||||||
for using named pipes as a net transport.
|
|
||||||
|
|
||||||
This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go
|
|
||||||
to reuse the thread to schedule another goroutine. This limits support to Windows Vista and
|
|
||||||
newer operating systems. This is similar to the implementation of network sockets in Go's net
|
|
||||||
package.
|
|
||||||
|
|
||||||
Please see the LICENSE file for licensing information.
|
|
||||||
|
|
||||||
This project has adopted the [Microsoft Open Source Code of
|
|
||||||
Conduct](https://opensource.microsoft.com/codeofconduct/). For more information
|
|
||||||
see the [Code of Conduct
|
|
||||||
FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact
|
|
||||||
[[email protected]](mailto:[email protected]) with any additional
|
|
||||||
questions or comments.
|
|
||||||
|
|
||||||
Thanks to natefinch for the inspiration for this library. See https://github.com/natefinch/npipe
|
|
||||||
for another named pipe implementation.
|
|
||||||
-280
@@ -1,280 +0,0 @@
|
|||||||
// +build windows
|
|
||||||
|
|
||||||
package winio
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
|
||||||
"runtime"
|
|
||||||
"syscall"
|
|
||||||
"unicode/utf16"
|
|
||||||
)
|
|
||||||
|
|
||||||
//sys backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupRead
|
|
||||||
//sys backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupWrite
|
|
||||||
|
|
||||||
const (
|
|
||||||
BackupData = uint32(iota + 1)
|
|
||||||
BackupEaData
|
|
||||||
BackupSecurity
|
|
||||||
BackupAlternateData
|
|
||||||
BackupLink
|
|
||||||
BackupPropertyData
|
|
||||||
BackupObjectId
|
|
||||||
BackupReparseData
|
|
||||||
BackupSparseBlock
|
|
||||||
BackupTxfsData
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
StreamSparseAttributes = uint32(8)
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
WRITE_DAC = 0x40000
|
|
||||||
WRITE_OWNER = 0x80000
|
|
||||||
ACCESS_SYSTEM_SECURITY = 0x1000000
|
|
||||||
)
|
|
||||||
|
|
||||||
// BackupHeader represents a backup stream of a file.
|
|
||||||
type BackupHeader struct {
|
|
||||||
Id uint32 // The backup stream ID
|
|
||||||
Attributes uint32 // Stream attributes
|
|
||||||
Size int64 // The size of the stream in bytes
|
|
||||||
Name string // The name of the stream (for BackupAlternateData only).
|
|
||||||
Offset int64 // The offset of the stream in the file (for BackupSparseBlock only).
|
|
||||||
}
|
|
||||||
|
|
||||||
type win32StreamId struct {
|
|
||||||
StreamId uint32
|
|
||||||
Attributes uint32
|
|
||||||
Size uint64
|
|
||||||
NameSize uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
// BackupStreamReader reads from a stream produced by the BackupRead Win32 API and produces a series
|
|
||||||
// of BackupHeader values.
|
|
||||||
type BackupStreamReader struct {
|
|
||||||
r io.Reader
|
|
||||||
bytesLeft int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewBackupStreamReader produces a BackupStreamReader from any io.Reader.
|
|
||||||
func NewBackupStreamReader(r io.Reader) *BackupStreamReader {
|
|
||||||
return &BackupStreamReader{r, 0}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Next returns the next backup stream and prepares for calls to Read(). It skips the remainder of the current stream if
|
|
||||||
// it was not completely read.
|
|
||||||
func (r *BackupStreamReader) Next() (*BackupHeader, error) {
|
|
||||||
if r.bytesLeft > 0 {
|
|
||||||
if s, ok := r.r.(io.Seeker); ok {
|
|
||||||
// Make sure Seek on io.SeekCurrent sometimes succeeds
|
|
||||||
// before trying the actual seek.
|
|
||||||
if _, err := s.Seek(0, io.SeekCurrent); err == nil {
|
|
||||||
if _, err = s.Seek(r.bytesLeft, io.SeekCurrent); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
r.bytesLeft = 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if _, err := io.Copy(ioutil.Discard, r); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var wsi win32StreamId
|
|
||||||
if err := binary.Read(r.r, binary.LittleEndian, &wsi); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
hdr := &BackupHeader{
|
|
||||||
Id: wsi.StreamId,
|
|
||||||
Attributes: wsi.Attributes,
|
|
||||||
Size: int64(wsi.Size),
|
|
||||||
}
|
|
||||||
if wsi.NameSize != 0 {
|
|
||||||
name := make([]uint16, int(wsi.NameSize/2))
|
|
||||||
if err := binary.Read(r.r, binary.LittleEndian, name); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
hdr.Name = syscall.UTF16ToString(name)
|
|
||||||
}
|
|
||||||
if wsi.StreamId == BackupSparseBlock {
|
|
||||||
if err := binary.Read(r.r, binary.LittleEndian, &hdr.Offset); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
hdr.Size -= 8
|
|
||||||
}
|
|
||||||
r.bytesLeft = hdr.Size
|
|
||||||
return hdr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read reads from the current backup stream.
|
|
||||||
func (r *BackupStreamReader) Read(b []byte) (int, error) {
|
|
||||||
if r.bytesLeft == 0 {
|
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
if int64(len(b)) > r.bytesLeft {
|
|
||||||
b = b[:r.bytesLeft]
|
|
||||||
}
|
|
||||||
n, err := r.r.Read(b)
|
|
||||||
r.bytesLeft -= int64(n)
|
|
||||||
if err == io.EOF {
|
|
||||||
err = io.ErrUnexpectedEOF
|
|
||||||
} else if r.bytesLeft == 0 && err == nil {
|
|
||||||
err = io.EOF
|
|
||||||
}
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// BackupStreamWriter writes a stream compatible with the BackupWrite Win32 API.
|
|
||||||
type BackupStreamWriter struct {
|
|
||||||
w io.Writer
|
|
||||||
bytesLeft int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewBackupStreamWriter produces a BackupStreamWriter on top of an io.Writer.
|
|
||||||
func NewBackupStreamWriter(w io.Writer) *BackupStreamWriter {
|
|
||||||
return &BackupStreamWriter{w, 0}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WriteHeader writes the next backup stream header and prepares for calls to Write().
|
|
||||||
func (w *BackupStreamWriter) WriteHeader(hdr *BackupHeader) error {
|
|
||||||
if w.bytesLeft != 0 {
|
|
||||||
return fmt.Errorf("missing %d bytes", w.bytesLeft)
|
|
||||||
}
|
|
||||||
name := utf16.Encode([]rune(hdr.Name))
|
|
||||||
wsi := win32StreamId{
|
|
||||||
StreamId: hdr.Id,
|
|
||||||
Attributes: hdr.Attributes,
|
|
||||||
Size: uint64(hdr.Size),
|
|
||||||
NameSize: uint32(len(name) * 2),
|
|
||||||
}
|
|
||||||
if hdr.Id == BackupSparseBlock {
|
|
||||||
// Include space for the int64 block offset
|
|
||||||
wsi.Size += 8
|
|
||||||
}
|
|
||||||
if err := binary.Write(w.w, binary.LittleEndian, &wsi); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if len(name) != 0 {
|
|
||||||
if err := binary.Write(w.w, binary.LittleEndian, name); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if hdr.Id == BackupSparseBlock {
|
|
||||||
if err := binary.Write(w.w, binary.LittleEndian, hdr.Offset); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
w.bytesLeft = hdr.Size
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write writes to the current backup stream.
|
|
||||||
func (w *BackupStreamWriter) Write(b []byte) (int, error) {
|
|
||||||
if w.bytesLeft < int64(len(b)) {
|
|
||||||
return 0, fmt.Errorf("too many bytes by %d", int64(len(b))-w.bytesLeft)
|
|
||||||
}
|
|
||||||
n, err := w.w.Write(b)
|
|
||||||
w.bytesLeft -= int64(n)
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// BackupFileReader provides an io.ReadCloser interface on top of the BackupRead Win32 API.
|
|
||||||
type BackupFileReader struct {
|
|
||||||
f *os.File
|
|
||||||
includeSecurity bool
|
|
||||||
ctx uintptr
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewBackupFileReader returns a new BackupFileReader from a file handle. If includeSecurity is true,
|
|
||||||
// Read will attempt to read the security descriptor of the file.
|
|
||||||
func NewBackupFileReader(f *os.File, includeSecurity bool) *BackupFileReader {
|
|
||||||
r := &BackupFileReader{f, includeSecurity, 0}
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read reads a backup stream from the file by calling the Win32 API BackupRead().
|
|
||||||
func (r *BackupFileReader) Read(b []byte) (int, error) {
|
|
||||||
var bytesRead uint32
|
|
||||||
err := backupRead(syscall.Handle(r.f.Fd()), b, &bytesRead, false, r.includeSecurity, &r.ctx)
|
|
||||||
if err != nil {
|
|
||||||
return 0, &os.PathError{"BackupRead", r.f.Name(), err}
|
|
||||||
}
|
|
||||||
runtime.KeepAlive(r.f)
|
|
||||||
if bytesRead == 0 {
|
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
return int(bytesRead), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close frees Win32 resources associated with the BackupFileReader. It does not close
|
|
||||||
// the underlying file.
|
|
||||||
func (r *BackupFileReader) Close() error {
|
|
||||||
if r.ctx != 0 {
|
|
||||||
backupRead(syscall.Handle(r.f.Fd()), nil, nil, true, false, &r.ctx)
|
|
||||||
runtime.KeepAlive(r.f)
|
|
||||||
r.ctx = 0
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// BackupFileWriter provides an io.WriteCloser interface on top of the BackupWrite Win32 API.
|
|
||||||
type BackupFileWriter struct {
|
|
||||||
f *os.File
|
|
||||||
includeSecurity bool
|
|
||||||
ctx uintptr
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewBackupFileWriter returns a new BackupFileWriter from a file handle. If includeSecurity is true,
|
|
||||||
// Write() will attempt to restore the security descriptor from the stream.
|
|
||||||
func NewBackupFileWriter(f *os.File, includeSecurity bool) *BackupFileWriter {
|
|
||||||
w := &BackupFileWriter{f, includeSecurity, 0}
|
|
||||||
return w
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write restores a portion of the file using the provided backup stream.
|
|
||||||
func (w *BackupFileWriter) Write(b []byte) (int, error) {
|
|
||||||
var bytesWritten uint32
|
|
||||||
err := backupWrite(syscall.Handle(w.f.Fd()), b, &bytesWritten, false, w.includeSecurity, &w.ctx)
|
|
||||||
if err != nil {
|
|
||||||
return 0, &os.PathError{"BackupWrite", w.f.Name(), err}
|
|
||||||
}
|
|
||||||
runtime.KeepAlive(w.f)
|
|
||||||
if int(bytesWritten) != len(b) {
|
|
||||||
return int(bytesWritten), errors.New("not all bytes could be written")
|
|
||||||
}
|
|
||||||
return len(b), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close frees Win32 resources associated with the BackupFileWriter. It does not
|
|
||||||
// close the underlying file.
|
|
||||||
func (w *BackupFileWriter) Close() error {
|
|
||||||
if w.ctx != 0 {
|
|
||||||
backupWrite(syscall.Handle(w.f.Fd()), nil, nil, true, false, &w.ctx)
|
|
||||||
runtime.KeepAlive(w.f)
|
|
||||||
w.ctx = 0
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// OpenForBackup opens a file or directory, potentially skipping access checks if the backup
|
|
||||||
// or restore privileges have been acquired.
|
|
||||||
//
|
|
||||||
// If the file opened was a directory, it cannot be used with Readdir().
|
|
||||||
func OpenForBackup(path string, access uint32, share uint32, createmode uint32) (*os.File, error) {
|
|
||||||
winPath, err := syscall.UTF16FromString(path)
|
|
||||||
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)
|
|
||||||
if err != nil {
|
|
||||||
err = &os.PathError{Op: "open", Path: path, Err: err}
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return os.NewFile(uintptr(h), path), nil
|
|
||||||
}
|
|
||||||
-137
@@ -1,137 +0,0 @@
|
|||||||
package winio
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type fileFullEaInformation struct {
|
|
||||||
NextEntryOffset uint32
|
|
||||||
Flags uint8
|
|
||||||
NameLength uint8
|
|
||||||
ValueLength uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
fileFullEaInformationSize = binary.Size(&fileFullEaInformation{})
|
|
||||||
|
|
||||||
errInvalidEaBuffer = errors.New("invalid extended attribute buffer")
|
|
||||||
errEaNameTooLarge = errors.New("extended attribute name too large")
|
|
||||||
errEaValueTooLarge = errors.New("extended attribute value too large")
|
|
||||||
)
|
|
||||||
|
|
||||||
// ExtendedAttribute represents a single Windows EA.
|
|
||||||
type ExtendedAttribute struct {
|
|
||||||
Name string
|
|
||||||
Value []byte
|
|
||||||
Flags uint8
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseEa(b []byte) (ea ExtendedAttribute, nb []byte, err error) {
|
|
||||||
var info fileFullEaInformation
|
|
||||||
err = binary.Read(bytes.NewReader(b), binary.LittleEndian, &info)
|
|
||||||
if err != nil {
|
|
||||||
err = errInvalidEaBuffer
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
nameOffset := fileFullEaInformationSize
|
|
||||||
nameLen := int(info.NameLength)
|
|
||||||
valueOffset := nameOffset + int(info.NameLength) + 1
|
|
||||||
valueLen := int(info.ValueLength)
|
|
||||||
nextOffset := int(info.NextEntryOffset)
|
|
||||||
if valueLen+valueOffset > len(b) || nextOffset < 0 || nextOffset > len(b) {
|
|
||||||
err = errInvalidEaBuffer
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ea.Name = string(b[nameOffset : nameOffset+nameLen])
|
|
||||||
ea.Value = b[valueOffset : valueOffset+valueLen]
|
|
||||||
ea.Flags = info.Flags
|
|
||||||
if info.NextEntryOffset != 0 {
|
|
||||||
nb = b[info.NextEntryOffset:]
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeExtendedAttributes decodes a list of EAs from a FILE_FULL_EA_INFORMATION
|
|
||||||
// buffer retrieved from BackupRead, ZwQueryEaFile, etc.
|
|
||||||
func DecodeExtendedAttributes(b []byte) (eas []ExtendedAttribute, err error) {
|
|
||||||
for len(b) != 0 {
|
|
||||||
ea, nb, err := parseEa(b)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
eas = append(eas, ea)
|
|
||||||
b = nb
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeEa(buf *bytes.Buffer, ea *ExtendedAttribute, last bool) error {
|
|
||||||
if int(uint8(len(ea.Name))) != len(ea.Name) {
|
|
||||||
return errEaNameTooLarge
|
|
||||||
}
|
|
||||||
if int(uint16(len(ea.Value))) != len(ea.Value) {
|
|
||||||
return errEaValueTooLarge
|
|
||||||
}
|
|
||||||
entrySize := uint32(fileFullEaInformationSize + len(ea.Name) + 1 + len(ea.Value))
|
|
||||||
withPadding := (entrySize + 3) &^ 3
|
|
||||||
nextOffset := uint32(0)
|
|
||||||
if !last {
|
|
||||||
nextOffset = withPadding
|
|
||||||
}
|
|
||||||
info := fileFullEaInformation{
|
|
||||||
NextEntryOffset: nextOffset,
|
|
||||||
Flags: ea.Flags,
|
|
||||||
NameLength: uint8(len(ea.Name)),
|
|
||||||
ValueLength: uint16(len(ea.Value)),
|
|
||||||
}
|
|
||||||
|
|
||||||
err := binary.Write(buf, binary.LittleEndian, &info)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = buf.Write([]byte(ea.Name))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = buf.WriteByte(0)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = buf.Write(ea.Value)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = buf.Write([]byte{0, 0, 0}[0 : withPadding-entrySize])
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeExtendedAttributes encodes a list of EAs into a FILE_FULL_EA_INFORMATION
|
|
||||||
// buffer for use with BackupWrite, ZwSetEaFile, etc.
|
|
||||||
func EncodeExtendedAttributes(eas []ExtendedAttribute) ([]byte, error) {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
for i := range eas {
|
|
||||||
last := false
|
|
||||||
if i == len(eas)-1 {
|
|
||||||
last = true
|
|
||||||
}
|
|
||||||
|
|
||||||
err := writeEa(&buf, &eas[i], last)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return buf.Bytes(), nil
|
|
||||||
}
|
|
||||||
-323
@@ -1,323 +0,0 @@
|
|||||||
// +build windows
|
|
||||||
|
|
||||||
package winio
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
//sys cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) = CancelIoEx
|
|
||||||
//sys createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) = CreateIoCompletionPort
|
|
||||||
//sys getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) = GetQueuedCompletionStatus
|
|
||||||
//sys setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) = SetFileCompletionNotificationModes
|
|
||||||
//sys wsaGetOverlappedResult(h syscall.Handle, o *syscall.Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) = ws2_32.WSAGetOverlappedResult
|
|
||||||
|
|
||||||
type atomicBool int32
|
|
||||||
|
|
||||||
func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 }
|
|
||||||
func (b *atomicBool) setFalse() { atomic.StoreInt32((*int32)(b), 0) }
|
|
||||||
func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) }
|
|
||||||
func (b *atomicBool) swap(new bool) bool {
|
|
||||||
var newInt int32
|
|
||||||
if new {
|
|
||||||
newInt = 1
|
|
||||||
}
|
|
||||||
return atomic.SwapInt32((*int32)(b), newInt) == 1
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1
|
|
||||||
cFILE_SKIP_SET_EVENT_ON_HANDLE = 2
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrFileClosed = errors.New("file has already been closed")
|
|
||||||
ErrTimeout = &timeoutError{}
|
|
||||||
)
|
|
||||||
|
|
||||||
type timeoutError struct{}
|
|
||||||
|
|
||||||
func (e *timeoutError) Error() string { return "i/o timeout" }
|
|
||||||
func (e *timeoutError) Timeout() bool { return true }
|
|
||||||
func (e *timeoutError) Temporary() bool { return true }
|
|
||||||
|
|
||||||
type timeoutChan chan struct{}
|
|
||||||
|
|
||||||
var ioInitOnce sync.Once
|
|
||||||
var ioCompletionPort syscall.Handle
|
|
||||||
|
|
||||||
// ioResult contains the result of an asynchronous IO operation
|
|
||||||
type ioResult struct {
|
|
||||||
bytes uint32
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
// ioOperation represents an outstanding asynchronous Win32 IO
|
|
||||||
type ioOperation struct {
|
|
||||||
o syscall.Overlapped
|
|
||||||
ch chan ioResult
|
|
||||||
}
|
|
||||||
|
|
||||||
func initIo() {
|
|
||||||
h, err := createIoCompletionPort(syscall.InvalidHandle, 0, 0, 0xffffffff)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
ioCompletionPort = h
|
|
||||||
go ioCompletionProcessor(h)
|
|
||||||
}
|
|
||||||
|
|
||||||
// win32File implements Reader, Writer, and Closer on a Win32 handle without blocking in a syscall.
|
|
||||||
// It takes ownership of this handle and will close it if it is garbage collected.
|
|
||||||
type win32File struct {
|
|
||||||
handle syscall.Handle
|
|
||||||
wg sync.WaitGroup
|
|
||||||
wgLock sync.RWMutex
|
|
||||||
closing atomicBool
|
|
||||||
socket bool
|
|
||||||
readDeadline deadlineHandler
|
|
||||||
writeDeadline deadlineHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
type deadlineHandler struct {
|
|
||||||
setLock sync.Mutex
|
|
||||||
channel timeoutChan
|
|
||||||
channelLock sync.RWMutex
|
|
||||||
timer *time.Timer
|
|
||||||
timedout atomicBool
|
|
||||||
}
|
|
||||||
|
|
||||||
// makeWin32File makes a new win32File from an existing file handle
|
|
||||||
func makeWin32File(h syscall.Handle) (*win32File, error) {
|
|
||||||
f := &win32File{handle: h}
|
|
||||||
ioInitOnce.Do(initIo)
|
|
||||||
_, err := createIoCompletionPort(h, ioCompletionPort, 0, 0xffffffff)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
err = setFileCompletionNotificationModes(h, cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS|cFILE_SKIP_SET_EVENT_ON_HANDLE)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
f.readDeadline.channel = make(timeoutChan)
|
|
||||||
f.writeDeadline.channel = make(timeoutChan)
|
|
||||||
return f, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func MakeOpenFile(h syscall.Handle) (io.ReadWriteCloser, error) {
|
|
||||||
// If we return the result of makeWin32File directly, it can result in an
|
|
||||||
// interface-wrapped nil, rather than a nil interface value.
|
|
||||||
f, err := makeWin32File(h)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return f, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// closeHandle closes the resources associated with a Win32 handle
|
|
||||||
func (f *win32File) closeHandle() {
|
|
||||||
f.wgLock.Lock()
|
|
||||||
// Atomically set that we are closing, releasing the resources only once.
|
|
||||||
if !f.closing.swap(true) {
|
|
||||||
f.wgLock.Unlock()
|
|
||||||
// cancel all IO and wait for it to complete
|
|
||||||
cancelIoEx(f.handle, nil)
|
|
||||||
f.wg.Wait()
|
|
||||||
// at this point, no new IO can start
|
|
||||||
syscall.Close(f.handle)
|
|
||||||
f.handle = 0
|
|
||||||
} else {
|
|
||||||
f.wgLock.Unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close closes a win32File.
|
|
||||||
func (f *win32File) Close() error {
|
|
||||||
f.closeHandle()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// prepareIo prepares for a new IO operation.
|
|
||||||
// The caller must call f.wg.Done() when the IO is finished, prior to Close() returning.
|
|
||||||
func (f *win32File) prepareIo() (*ioOperation, error) {
|
|
||||||
f.wgLock.RLock()
|
|
||||||
if f.closing.isSet() {
|
|
||||||
f.wgLock.RUnlock()
|
|
||||||
return nil, ErrFileClosed
|
|
||||||
}
|
|
||||||
f.wg.Add(1)
|
|
||||||
f.wgLock.RUnlock()
|
|
||||||
c := &ioOperation{}
|
|
||||||
c.ch = make(chan ioResult)
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ioCompletionProcessor processes completed async IOs forever
|
|
||||||
func ioCompletionProcessor(h syscall.Handle) {
|
|
||||||
for {
|
|
||||||
var bytes uint32
|
|
||||||
var key uintptr
|
|
||||||
var op *ioOperation
|
|
||||||
err := getQueuedCompletionStatus(h, &bytes, &key, &op, syscall.INFINITE)
|
|
||||||
if op == nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
op.ch <- ioResult{bytes, err}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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 {
|
|
||||||
return int(bytes), err
|
|
||||||
}
|
|
||||||
|
|
||||||
if f.closing.isSet() {
|
|
||||||
cancelIoEx(f.handle, &c.o)
|
|
||||||
}
|
|
||||||
|
|
||||||
var timeout timeoutChan
|
|
||||||
if d != nil {
|
|
||||||
d.channelLock.Lock()
|
|
||||||
timeout = d.channel
|
|
||||||
d.channelLock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
var r ioResult
|
|
||||||
select {
|
|
||||||
case r = <-c.ch:
|
|
||||||
err = r.err
|
|
||||||
if err == syscall.ERROR_OPERATION_ABORTED {
|
|
||||||
if f.closing.isSet() {
|
|
||||||
err = ErrFileClosed
|
|
||||||
}
|
|
||||||
} else if err != nil && f.socket {
|
|
||||||
// err is from Win32. Query the overlapped structure to get the winsock error.
|
|
||||||
var bytes, flags uint32
|
|
||||||
err = wsaGetOverlappedResult(f.handle, &c.o, &bytes, false, &flags)
|
|
||||||
}
|
|
||||||
case <-timeout:
|
|
||||||
cancelIoEx(f.handle, &c.o)
|
|
||||||
r = <-c.ch
|
|
||||||
err = r.err
|
|
||||||
if err == syscall.ERROR_OPERATION_ABORTED {
|
|
||||||
err = ErrTimeout
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// runtime.KeepAlive is needed, as c is passed via native
|
|
||||||
// code to ioCompletionProcessor, c must remain alive
|
|
||||||
// until the channel read is complete.
|
|
||||||
runtime.KeepAlive(c)
|
|
||||||
return int(r.bytes), err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read reads from a file handle.
|
|
||||||
func (f *win32File) Read(b []byte) (int, error) {
|
|
||||||
c, err := f.prepareIo()
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
defer f.wg.Done()
|
|
||||||
|
|
||||||
if f.readDeadline.timedout.isSet() {
|
|
||||||
return 0, ErrTimeout
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes uint32
|
|
||||||
err = syscall.ReadFile(f.handle, b, &bytes, &c.o)
|
|
||||||
n, err := f.asyncIo(c, &f.readDeadline, bytes, err)
|
|
||||||
runtime.KeepAlive(b)
|
|
||||||
|
|
||||||
// Handle EOF conditions.
|
|
||||||
if err == nil && n == 0 && len(b) != 0 {
|
|
||||||
return 0, io.EOF
|
|
||||||
} else if err == syscall.ERROR_BROKEN_PIPE {
|
|
||||||
return 0, io.EOF
|
|
||||||
} else {
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write writes to a file handle.
|
|
||||||
func (f *win32File) Write(b []byte) (int, error) {
|
|
||||||
c, err := f.prepareIo()
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
defer f.wg.Done()
|
|
||||||
|
|
||||||
if f.writeDeadline.timedout.isSet() {
|
|
||||||
return 0, ErrTimeout
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes uint32
|
|
||||||
err = syscall.WriteFile(f.handle, b, &bytes, &c.o)
|
|
||||||
n, err := f.asyncIo(c, &f.writeDeadline, bytes, err)
|
|
||||||
runtime.KeepAlive(b)
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *win32File) SetReadDeadline(deadline time.Time) error {
|
|
||||||
return f.readDeadline.set(deadline)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *win32File) SetWriteDeadline(deadline time.Time) error {
|
|
||||||
return f.writeDeadline.set(deadline)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *win32File) Flush() error {
|
|
||||||
return syscall.FlushFileBuffers(f.handle)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *win32File) Fd() uintptr {
|
|
||||||
return uintptr(f.handle)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *deadlineHandler) set(deadline time.Time) error {
|
|
||||||
d.setLock.Lock()
|
|
||||||
defer d.setLock.Unlock()
|
|
||||||
|
|
||||||
if d.timer != nil {
|
|
||||||
if !d.timer.Stop() {
|
|
||||||
<-d.channel
|
|
||||||
}
|
|
||||||
d.timer = nil
|
|
||||||
}
|
|
||||||
d.timedout.setFalse()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-d.channel:
|
|
||||||
d.channelLock.Lock()
|
|
||||||
d.channel = make(chan struct{})
|
|
||||||
d.channelLock.Unlock()
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
|
|
||||||
if deadline.IsZero() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
timeoutIO := func() {
|
|
||||||
d.timedout.setTrue()
|
|
||||||
close(d.channel)
|
|
||||||
}
|
|
||||||
|
|
||||||
now := time.Now()
|
|
||||||
duration := deadline.Sub(now)
|
|
||||||
if deadline.After(now) {
|
|
||||||
// Deadline is in the future, set a timer to wait
|
|
||||||
d.timer = time.AfterFunc(duration, timeoutIO)
|
|
||||||
} else {
|
|
||||||
// Deadline is in the past. Cancel all pending IO now.
|
|
||||||
timeoutIO()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
-61
@@ -1,61 +0,0 @@
|
|||||||
// +build windows
|
|
||||||
|
|
||||||
package winio
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"runtime"
|
|
||||||
"syscall"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
//sys getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = GetFileInformationByHandleEx
|
|
||||||
//sys setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = SetFileInformationByHandle
|
|
||||||
|
|
||||||
const (
|
|
||||||
fileBasicInfo = 0
|
|
||||||
fileIDInfo = 0x12
|
|
||||||
)
|
|
||||||
|
|
||||||
// FileBasicInfo contains file access time and file attributes information.
|
|
||||||
type FileBasicInfo struct {
|
|
||||||
CreationTime, LastAccessTime, LastWriteTime, ChangeTime syscall.Filetime
|
|
||||||
FileAttributes uint32
|
|
||||||
pad uint32 // padding
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetFileBasicInfo retrieves times and attributes for a file.
|
|
||||||
func GetFileBasicInfo(f *os.File) (*FileBasicInfo, error) {
|
|
||||||
bi := &FileBasicInfo{}
|
|
||||||
if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil {
|
|
||||||
return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err}
|
|
||||||
}
|
|
||||||
runtime.KeepAlive(f)
|
|
||||||
return bi, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetFileBasicInfo sets times and attributes for a file.
|
|
||||||
func SetFileBasicInfo(f *os.File, bi *FileBasicInfo) error {
|
|
||||||
if err := setFileInformationByHandle(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil {
|
|
||||||
return &os.PathError{Op: "SetFileInformationByHandle", Path: f.Name(), Err: err}
|
|
||||||
}
|
|
||||||
runtime.KeepAlive(f)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// FileIDInfo contains the volume serial number and file ID for a file. This pair should be
|
|
||||||
// unique on a system.
|
|
||||||
type FileIDInfo struct {
|
|
||||||
VolumeSerialNumber uint64
|
|
||||||
FileID [16]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetFileID retrieves the unique (volume, file ID) pair for a file.
|
|
||||||
func GetFileID(f *os.File) (*FileIDInfo, error) {
|
|
||||||
fileID := &FileIDInfo{}
|
|
||||||
if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileIDInfo, (*byte)(unsafe.Pointer(fileID)), uint32(unsafe.Sizeof(*fileID))); err != nil {
|
|
||||||
return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err}
|
|
||||||
}
|
|
||||||
runtime.KeepAlive(f)
|
|
||||||
return fileID, nil
|
|
||||||
}
|
|
||||||
-9
@@ -1,9 +0,0 @@
|
|||||||
module github.com/Microsoft/go-winio
|
|
||||||
|
|
||||||
go 1.12
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/pkg/errors v0.8.1
|
|
||||||
github.com/sirupsen/logrus v1.4.1
|
|
||||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3
|
|
||||||
)
|
|
||||||
-18
@@ -1,18 +0,0 @@
|
|||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
|
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
|
||||||
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
|
|
||||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
|
||||||
github.com/sirupsen/logrus v1.4.1 h1:GL2rEmy6nsikmW0r8opw9JIRScdMF5hA8cOYLH7In1k=
|
|
||||||
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
|
|
||||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
|
||||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
|
||||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
|
||||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
|
||||||
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b h1:ag/x1USPSsqHud38I9BAC88qdNLDHHtQ4mlgQIZPPNA=
|
|
||||||
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3 h1:7TYNF4UdlohbFwpNH04CoPMp1cHUZgO1Ebq5r2hIjfo=
|
|
||||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
-305
@@ -1,305 +0,0 @@
|
|||||||
package winio
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
|
||||||
"unsafe"
|
|
||||||
|
|
||||||
"github.com/Microsoft/go-winio/pkg/guid"
|
|
||||||
)
|
|
||||||
|
|
||||||
//sys bind(s syscall.Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socketError] = ws2_32.bind
|
|
||||||
|
|
||||||
const (
|
|
||||||
afHvSock = 34 // AF_HYPERV
|
|
||||||
|
|
||||||
socketError = ^uintptr(0)
|
|
||||||
)
|
|
||||||
|
|
||||||
// An HvsockAddr is an address for a AF_HYPERV socket.
|
|
||||||
type HvsockAddr struct {
|
|
||||||
VMID guid.GUID
|
|
||||||
ServiceID guid.GUID
|
|
||||||
}
|
|
||||||
|
|
||||||
type rawHvsockAddr struct {
|
|
||||||
Family uint16
|
|
||||||
_ uint16
|
|
||||||
VMID guid.GUID
|
|
||||||
ServiceID guid.GUID
|
|
||||||
}
|
|
||||||
|
|
||||||
// Network returns the address's network name, "hvsock".
|
|
||||||
func (addr *HvsockAddr) Network() string {
|
|
||||||
return "hvsock"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (addr *HvsockAddr) String() string {
|
|
||||||
return fmt.Sprintf("%s:%s", &addr.VMID, &addr.ServiceID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// VsockServiceID returns an hvsock service ID corresponding to the specified AF_VSOCK port.
|
|
||||||
func VsockServiceID(port uint32) guid.GUID {
|
|
||||||
g, _ := guid.FromString("00000000-facb-11e6-bd58-64006a7986d3")
|
|
||||||
g.Data1 = port
|
|
||||||
return g
|
|
||||||
}
|
|
||||||
|
|
||||||
func (addr *HvsockAddr) raw() rawHvsockAddr {
|
|
||||||
return rawHvsockAddr{
|
|
||||||
Family: afHvSock,
|
|
||||||
VMID: addr.VMID,
|
|
||||||
ServiceID: addr.ServiceID,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (addr *HvsockAddr) fromRaw(raw *rawHvsockAddr) {
|
|
||||||
addr.VMID = raw.VMID
|
|
||||||
addr.ServiceID = raw.ServiceID
|
|
||||||
}
|
|
||||||
|
|
||||||
// HvsockListener is a socket listener for the AF_HYPERV address family.
|
|
||||||
type HvsockListener struct {
|
|
||||||
sock *win32File
|
|
||||||
addr HvsockAddr
|
|
||||||
}
|
|
||||||
|
|
||||||
// HvsockConn is a connected socket of the AF_HYPERV address family.
|
|
||||||
type HvsockConn struct {
|
|
||||||
sock *win32File
|
|
||||||
local, remote HvsockAddr
|
|
||||||
}
|
|
||||||
|
|
||||||
func newHvSocket() (*win32File, error) {
|
|
||||||
fd, err := syscall.Socket(afHvSock, syscall.SOCK_STREAM, 1)
|
|
||||||
if err != nil {
|
|
||||||
return nil, os.NewSyscallError("socket", err)
|
|
||||||
}
|
|
||||||
f, err := makeWin32File(fd)
|
|
||||||
if err != nil {
|
|
||||||
syscall.Close(fd)
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
f.socket = true
|
|
||||||
return f, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenHvsock listens for connections on the specified hvsock address.
|
|
||||||
func ListenHvsock(addr *HvsockAddr) (_ *HvsockListener, err error) {
|
|
||||||
l := &HvsockListener{addr: *addr}
|
|
||||||
sock, err := newHvSocket()
|
|
||||||
if err != nil {
|
|
||||||
return nil, l.opErr("listen", err)
|
|
||||||
}
|
|
||||||
sa := addr.raw()
|
|
||||||
err = bind(sock.handle, unsafe.Pointer(&sa), int32(unsafe.Sizeof(sa)))
|
|
||||||
if err != nil {
|
|
||||||
return nil, l.opErr("listen", os.NewSyscallError("socket", err))
|
|
||||||
}
|
|
||||||
err = syscall.Listen(sock.handle, 16)
|
|
||||||
if err != nil {
|
|
||||||
return nil, l.opErr("listen", os.NewSyscallError("listen", err))
|
|
||||||
}
|
|
||||||
return &HvsockListener{sock: sock, addr: *addr}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *HvsockListener) opErr(op string, err error) error {
|
|
||||||
return &net.OpError{Op: op, Net: "hvsock", Addr: &l.addr, Err: err}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Addr returns the listener's network address.
|
|
||||||
func (l *HvsockListener) Addr() net.Addr {
|
|
||||||
return &l.addr
|
|
||||||
}
|
|
||||||
|
|
||||||
// Accept waits for the next connection and returns it.
|
|
||||||
func (l *HvsockListener) Accept() (_ net.Conn, err error) {
|
|
||||||
sock, err := newHvSocket()
|
|
||||||
if err != nil {
|
|
||||||
return nil, l.opErr("accept", err)
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if sock != nil {
|
|
||||||
sock.Close()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
c, err := l.sock.prepareIo()
|
|
||||||
if err != nil {
|
|
||||||
return nil, l.opErr("accept", err)
|
|
||||||
}
|
|
||||||
defer l.sock.wg.Done()
|
|
||||||
|
|
||||||
// AcceptEx, per documentation, requires an extra 16 bytes per address.
|
|
||||||
const addrlen = uint32(16 + unsafe.Sizeof(rawHvsockAddr{}))
|
|
||||||
var addrbuf [addrlen * 2]byte
|
|
||||||
|
|
||||||
var bytes uint32
|
|
||||||
err = syscall.AcceptEx(l.sock.handle, sock.handle, &addrbuf[0], 0, addrlen, addrlen, &bytes, &c.o)
|
|
||||||
_, err = l.sock.asyncIo(c, nil, bytes, err)
|
|
||||||
if err != nil {
|
|
||||||
return nil, l.opErr("accept", os.NewSyscallError("acceptex", err))
|
|
||||||
}
|
|
||||||
conn := &HvsockConn{
|
|
||||||
sock: sock,
|
|
||||||
}
|
|
||||||
conn.local.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[0])))
|
|
||||||
conn.remote.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[addrlen])))
|
|
||||||
sock = nil
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close closes the listener, causing any pending Accept calls to fail.
|
|
||||||
func (l *HvsockListener) Close() error {
|
|
||||||
return l.sock.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Need to finish ConnectEx handling
|
|
||||||
func DialHvsock(ctx context.Context, addr *HvsockAddr) (*HvsockConn, error) {
|
|
||||||
sock, err := newHvSocket()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
if sock != nil {
|
|
||||||
sock.Close()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
c, err := sock.prepareIo()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer sock.wg.Done()
|
|
||||||
var bytes uint32
|
|
||||||
err = windows.ConnectEx(windows.Handle(sock.handle), sa, nil, 0, &bytes, &c.o)
|
|
||||||
_, err = sock.asyncIo(ctx, c, nil, bytes, err)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
conn := &HvsockConn{
|
|
||||||
sock: sock,
|
|
||||||
remote: *addr,
|
|
||||||
}
|
|
||||||
sock = nil
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
func (conn *HvsockConn) opErr(op string, err error) error {
|
|
||||||
return &net.OpError{Op: op, Net: "hvsock", Source: &conn.local, Addr: &conn.remote, Err: err}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *HvsockConn) Read(b []byte) (int, error) {
|
|
||||||
c, err := conn.sock.prepareIo()
|
|
||||||
if err != nil {
|
|
||||||
return 0, conn.opErr("read", err)
|
|
||||||
}
|
|
||||||
defer conn.sock.wg.Done()
|
|
||||||
buf := syscall.WSABuf{Buf: &b[0], Len: uint32(len(b))}
|
|
||||||
var flags, bytes uint32
|
|
||||||
err = syscall.WSARecv(conn.sock.handle, &buf, 1, &bytes, &flags, &c.o, nil)
|
|
||||||
n, err := conn.sock.asyncIo(c, &conn.sock.readDeadline, bytes, err)
|
|
||||||
if err != nil {
|
|
||||||
if _, ok := err.(syscall.Errno); ok {
|
|
||||||
err = os.NewSyscallError("wsarecv", err)
|
|
||||||
}
|
|
||||||
return 0, conn.opErr("read", err)
|
|
||||||
} else if n == 0 {
|
|
||||||
err = io.EOF
|
|
||||||
}
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *HvsockConn) Write(b []byte) (int, error) {
|
|
||||||
t := 0
|
|
||||||
for len(b) != 0 {
|
|
||||||
n, err := conn.write(b)
|
|
||||||
if err != nil {
|
|
||||||
return t + n, err
|
|
||||||
}
|
|
||||||
t += n
|
|
||||||
b = b[n:]
|
|
||||||
}
|
|
||||||
return t, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *HvsockConn) write(b []byte) (int, error) {
|
|
||||||
c, err := conn.sock.prepareIo()
|
|
||||||
if err != nil {
|
|
||||||
return 0, conn.opErr("write", err)
|
|
||||||
}
|
|
||||||
defer conn.sock.wg.Done()
|
|
||||||
buf := syscall.WSABuf{Buf: &b[0], Len: uint32(len(b))}
|
|
||||||
var bytes uint32
|
|
||||||
err = syscall.WSASend(conn.sock.handle, &buf, 1, &bytes, 0, &c.o, nil)
|
|
||||||
n, err := conn.sock.asyncIo(c, &conn.sock.writeDeadline, bytes, err)
|
|
||||||
if err != nil {
|
|
||||||
if _, ok := err.(syscall.Errno); ok {
|
|
||||||
err = os.NewSyscallError("wsasend", err)
|
|
||||||
}
|
|
||||||
return 0, conn.opErr("write", err)
|
|
||||||
}
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close closes the socket connection, failing any pending read or write calls.
|
|
||||||
func (conn *HvsockConn) Close() error {
|
|
||||||
return conn.sock.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (conn *HvsockConn) shutdown(how int) error {
|
|
||||||
err := syscall.Shutdown(conn.sock.handle, syscall.SHUT_RD)
|
|
||||||
if err != nil {
|
|
||||||
return os.NewSyscallError("shutdown", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CloseRead shuts down the read end of the socket.
|
|
||||||
func (conn *HvsockConn) CloseRead() error {
|
|
||||||
err := conn.shutdown(syscall.SHUT_RD)
|
|
||||||
if err != nil {
|
|
||||||
return conn.opErr("close", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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)
|
|
||||||
if err != nil {
|
|
||||||
return conn.opErr("close", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LocalAddr returns the local address of the connection.
|
|
||||||
func (conn *HvsockConn) LocalAddr() net.Addr {
|
|
||||||
return &conn.local
|
|
||||||
}
|
|
||||||
|
|
||||||
// RemoteAddr returns the remote address of the connection.
|
|
||||||
func (conn *HvsockConn) RemoteAddr() net.Addr {
|
|
||||||
return &conn.remote
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetDeadline implements the net.Conn SetDeadline method.
|
|
||||||
func (conn *HvsockConn) SetDeadline(t time.Time) error {
|
|
||||||
conn.SetReadDeadline(t)
|
|
||||||
conn.SetWriteDeadline(t)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetReadDeadline implements the net.Conn SetReadDeadline method.
|
|
||||||
func (conn *HvsockConn) SetReadDeadline(t time.Time) error {
|
|
||||||
return conn.sock.SetReadDeadline(t)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetWriteDeadline implements the net.Conn SetWriteDeadline method.
|
|
||||||
func (conn *HvsockConn) SetWriteDeadline(t time.Time) error {
|
|
||||||
return conn.sock.SetWriteDeadline(t)
|
|
||||||
}
|
|
||||||
-510
File diff suppressed because it is too large.
Load diff
-235
@@ -1,235 +0,0 @@
|
|||||||
// Package guid provides a GUID type. The backing structure for a GUID is
|
|
||||||
// identical to that used by the golang.org/x/sys/windows GUID type.
|
|
||||||
// There are two main binary encodings used for a GUID, the big-endian encoding,
|
|
||||||
// and the Windows (mixed-endian) encoding. See here for details:
|
|
||||||
// https://en.wikipedia.org/wiki/Universally_unique_identifier#Encoding
|
|
||||||
package guid
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/sha1"
|
|
||||||
"encoding"
|
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"golang.org/x/sys/windows"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Variant specifies which GUID variant (or "type") of the GUID. It determines
|
|
||||||
// how the entirety of the rest of the GUID is interpreted.
|
|
||||||
type Variant uint8
|
|
||||||
|
|
||||||
// The variants specified by RFC 4122.
|
|
||||||
const (
|
|
||||||
// VariantUnknown specifies a GUID variant which does not conform to one of
|
|
||||||
// the variant encodings specified in RFC 4122.
|
|
||||||
VariantUnknown Variant = iota
|
|
||||||
VariantNCS
|
|
||||||
VariantRFC4122
|
|
||||||
VariantMicrosoft
|
|
||||||
VariantFuture
|
|
||||||
)
|
|
||||||
|
|
||||||
// Version specifies how the bits in the GUID were generated. For instance, a
|
|
||||||
// version 4 GUID is randomly generated, and a version 5 is generated from the
|
|
||||||
// hash of an input string.
|
|
||||||
type Version uint8
|
|
||||||
|
|
||||||
var _ = (encoding.TextMarshaler)(GUID{})
|
|
||||||
var _ = (encoding.TextUnmarshaler)(&GUID{})
|
|
||||||
|
|
||||||
// GUID represents a GUID/UUID. It has the same structure as
|
|
||||||
// golang.org/x/sys/windows.GUID so that it can be used with functions expecting
|
|
||||||
// that type. It is defined as its own type so that stringification and
|
|
||||||
// marshaling can be supported. The representation matches that used by native
|
|
||||||
// Windows code.
|
|
||||||
type GUID windows.GUID
|
|
||||||
|
|
||||||
// NewV4 returns a new version 4 (pseudorandom) GUID, as defined by RFC 4122.
|
|
||||||
func NewV4() (GUID, error) {
|
|
||||||
var b [16]byte
|
|
||||||
if _, err := rand.Read(b[:]); err != nil {
|
|
||||||
return GUID{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
g := FromArray(b)
|
|
||||||
g.setVersion(4) // Version 4 means randomly generated.
|
|
||||||
g.setVariant(VariantRFC4122)
|
|
||||||
|
|
||||||
return g, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewV5 returns a new version 5 (generated from a string via SHA-1 hashing)
|
|
||||||
// GUID, as defined by RFC 4122. The RFC is unclear on the encoding of the name,
|
|
||||||
// and the sample code treats it as a series of bytes, so we do the same here.
|
|
||||||
//
|
|
||||||
// Some implementations, such as those found on Windows, treat the name as a
|
|
||||||
// big-endian UTF16 stream of bytes. If that is desired, the string can be
|
|
||||||
// encoded as such before being passed to this function.
|
|
||||||
func NewV5(namespace GUID, name []byte) (GUID, error) {
|
|
||||||
b := sha1.New()
|
|
||||||
namespaceBytes := namespace.ToArray()
|
|
||||||
b.Write(namespaceBytes[:])
|
|
||||||
b.Write(name)
|
|
||||||
|
|
||||||
a := [16]byte{}
|
|
||||||
copy(a[:], b.Sum(nil))
|
|
||||||
|
|
||||||
g := FromArray(a)
|
|
||||||
g.setVersion(5) // Version 5 means generated from a string.
|
|
||||||
g.setVariant(VariantRFC4122)
|
|
||||||
|
|
||||||
return g, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func fromArray(b [16]byte, order binary.ByteOrder) GUID {
|
|
||||||
var g GUID
|
|
||||||
g.Data1 = order.Uint32(b[0:4])
|
|
||||||
g.Data2 = order.Uint16(b[4:6])
|
|
||||||
g.Data3 = order.Uint16(b[6:8])
|
|
||||||
copy(g.Data4[:], b[8:16])
|
|
||||||
return g
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g GUID) toArray(order binary.ByteOrder) [16]byte {
|
|
||||||
b := [16]byte{}
|
|
||||||
order.PutUint32(b[0:4], g.Data1)
|
|
||||||
order.PutUint16(b[4:6], g.Data2)
|
|
||||||
order.PutUint16(b[6:8], g.Data3)
|
|
||||||
copy(b[8:16], g.Data4[:])
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
// FromArray constructs a GUID from a big-endian encoding array of 16 bytes.
|
|
||||||
func FromArray(b [16]byte) GUID {
|
|
||||||
return fromArray(b, binary.BigEndian)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ToArray returns an array of 16 bytes representing the GUID in big-endian
|
|
||||||
// encoding.
|
|
||||||
func (g GUID) ToArray() [16]byte {
|
|
||||||
return g.toArray(binary.BigEndian)
|
|
||||||
}
|
|
||||||
|
|
||||||
// FromWindowsArray constructs a GUID from a Windows encoding array of bytes.
|
|
||||||
func FromWindowsArray(b [16]byte) GUID {
|
|
||||||
return fromArray(b, binary.LittleEndian)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ToWindowsArray returns an array of 16 bytes representing the GUID in Windows
|
|
||||||
// encoding.
|
|
||||||
func (g GUID) ToWindowsArray() [16]byte {
|
|
||||||
return g.toArray(binary.LittleEndian)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g GUID) String() string {
|
|
||||||
return fmt.Sprintf(
|
|
||||||
"%08x-%04x-%04x-%04x-%012x",
|
|
||||||
g.Data1,
|
|
||||||
g.Data2,
|
|
||||||
g.Data3,
|
|
||||||
g.Data4[:2],
|
|
||||||
g.Data4[2:])
|
|
||||||
}
|
|
||||||
|
|
||||||
// FromString parses a string containing a GUID and returns the GUID. The only
|
|
||||||
// format currently supported is the `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`
|
|
||||||
// format.
|
|
||||||
func FromString(s string) (GUID, error) {
|
|
||||||
if len(s) != 36 {
|
|
||||||
return GUID{}, fmt.Errorf("invalid GUID %q", s)
|
|
||||||
}
|
|
||||||
if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
|
|
||||||
return GUID{}, fmt.Errorf("invalid GUID %q", s)
|
|
||||||
}
|
|
||||||
|
|
||||||
var g GUID
|
|
||||||
|
|
||||||
data1, err := strconv.ParseUint(s[0:8], 16, 32)
|
|
||||||
if err != nil {
|
|
||||||
return GUID{}, fmt.Errorf("invalid GUID %q", s)
|
|
||||||
}
|
|
||||||
g.Data1 = uint32(data1)
|
|
||||||
|
|
||||||
data2, err := strconv.ParseUint(s[9:13], 16, 16)
|
|
||||||
if err != nil {
|
|
||||||
return GUID{}, fmt.Errorf("invalid GUID %q", s)
|
|
||||||
}
|
|
||||||
g.Data2 = uint16(data2)
|
|
||||||
|
|
||||||
data3, err := strconv.ParseUint(s[14:18], 16, 16)
|
|
||||||
if err != nil {
|
|
||||||
return GUID{}, fmt.Errorf("invalid GUID %q", s)
|
|
||||||
}
|
|
||||||
g.Data3 = uint16(data3)
|
|
||||||
|
|
||||||
for i, x := range []int{19, 21, 24, 26, 28, 30, 32, 34} {
|
|
||||||
v, err := strconv.ParseUint(s[x:x+2], 16, 8)
|
|
||||||
if err != nil {
|
|
||||||
return GUID{}, fmt.Errorf("invalid GUID %q", s)
|
|
||||||
}
|
|
||||||
g.Data4[i] = uint8(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
return g, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *GUID) setVariant(v Variant) {
|
|
||||||
d := g.Data4[0]
|
|
||||||
switch v {
|
|
||||||
case VariantNCS:
|
|
||||||
d = (d & 0x7f)
|
|
||||||
case VariantRFC4122:
|
|
||||||
d = (d & 0x3f) | 0x80
|
|
||||||
case VariantMicrosoft:
|
|
||||||
d = (d & 0x1f) | 0xc0
|
|
||||||
case VariantFuture:
|
|
||||||
d = (d & 0x0f) | 0xe0
|
|
||||||
case VariantUnknown:
|
|
||||||
fallthrough
|
|
||||||
default:
|
|
||||||
panic(fmt.Sprintf("invalid variant: %d", v))
|
|
||||||
}
|
|
||||||
g.Data4[0] = d
|
|
||||||
}
|
|
||||||
|
|
||||||
// Variant returns the GUID variant, as defined in RFC 4122.
|
|
||||||
func (g GUID) Variant() Variant {
|
|
||||||
b := g.Data4[0]
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
return VariantNCS
|
|
||||||
} else if b&0xc0 == 0x80 {
|
|
||||||
return VariantRFC4122
|
|
||||||
} else if b&0xe0 == 0xc0 {
|
|
||||||
return VariantMicrosoft
|
|
||||||
} else if b&0xe0 == 0xe0 {
|
|
||||||
return VariantFuture
|
|
||||||
}
|
|
||||||
return VariantUnknown
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *GUID) setVersion(v Version) {
|
|
||||||
g.Data3 = (g.Data3 & 0x0fff) | (uint16(v) << 12)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Version returns the GUID version, as defined in RFC 4122.
|
|
||||||
func (g GUID) Version() Version {
|
|
||||||
return Version((g.Data3 & 0xF000) >> 12)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalText returns the textual representation of the GUID.
|
|
||||||
func (g GUID) MarshalText() ([]byte, error) {
|
|
||||||
return []byte(g.String()), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnmarshalText takes the textual representation of a GUID, and unmarhals it
|
|
||||||
// into this GUID.
|
|
||||||
func (g *GUID) UnmarshalText(text []byte) error {
|
|
||||||
g2, err := FromString(string(text))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
*g = g2
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
-202
@@ -1,202 +0,0 @@
|
|||||||
// +build windows
|
|
||||||
|
|
||||||
package winio
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
|
||||||
"syscall"
|
|
||||||
"unicode/utf16"
|
|
||||||
|
|
||||||
"golang.org/x/sys/windows"
|
|
||||||
)
|
|
||||||
|
|
||||||
//sys adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges
|
|
||||||
//sys impersonateSelf(level uint32) (err error) = advapi32.ImpersonateSelf
|
|
||||||
//sys revertToSelf() (err error) = advapi32.RevertToSelf
|
|
||||||
//sys openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) = advapi32.OpenThreadToken
|
|
||||||
//sys getCurrentThread() (h syscall.Handle) = GetCurrentThread
|
|
||||||
//sys lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) = advapi32.LookupPrivilegeValueW
|
|
||||||
//sys lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW
|
|
||||||
//sys lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW
|
|
||||||
|
|
||||||
const (
|
|
||||||
SE_PRIVILEGE_ENABLED = 2
|
|
||||||
|
|
||||||
ERROR_NOT_ALL_ASSIGNED syscall.Errno = 1300
|
|
||||||
|
|
||||||
SeBackupPrivilege = "SeBackupPrivilege"
|
|
||||||
SeRestorePrivilege = "SeRestorePrivilege"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
securityAnonymous = iota
|
|
||||||
securityIdentification
|
|
||||||
securityImpersonation
|
|
||||||
securityDelegation
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
privNames = make(map[string]uint64)
|
|
||||||
privNameMutex sync.Mutex
|
|
||||||
)
|
|
||||||
|
|
||||||
// PrivilegeError represents an error enabling privileges.
|
|
||||||
type PrivilegeError struct {
|
|
||||||
privileges []uint64
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *PrivilegeError) Error() string {
|
|
||||||
s := ""
|
|
||||||
if len(e.privileges) > 1 {
|
|
||||||
s = "Could not enable privileges "
|
|
||||||
} else {
|
|
||||||
s = "Could not enable privilege "
|
|
||||||
}
|
|
||||||
for i, p := range e.privileges {
|
|
||||||
if i != 0 {
|
|
||||||
s += ", "
|
|
||||||
}
|
|
||||||
s += `"`
|
|
||||||
s += getPrivilegeName(p)
|
|
||||||
s += `"`
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// RunWithPrivilege enables a single privilege for a function call.
|
|
||||||
func RunWithPrivilege(name string, fn func() error) error {
|
|
||||||
return RunWithPrivileges([]string{name}, fn)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RunWithPrivileges enables privileges for a function call.
|
|
||||||
func RunWithPrivileges(names []string, fn func() error) error {
|
|
||||||
privileges, err := mapPrivileges(names)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
runtime.LockOSThread()
|
|
||||||
defer runtime.UnlockOSThread()
|
|
||||||
token, err := newThreadToken()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer releaseThreadToken(token)
|
|
||||||
err = adjustPrivileges(token, privileges, SE_PRIVILEGE_ENABLED)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return fn()
|
|
||||||
}
|
|
||||||
|
|
||||||
func mapPrivileges(names []string) ([]uint64, error) {
|
|
||||||
var privileges []uint64
|
|
||||||
privNameMutex.Lock()
|
|
||||||
defer privNameMutex.Unlock()
|
|
||||||
for _, name := range names {
|
|
||||||
p, ok := privNames[name]
|
|
||||||
if !ok {
|
|
||||||
err := lookupPrivilegeValue("", name, &p)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
privNames[name] = p
|
|
||||||
}
|
|
||||||
privileges = append(privileges, p)
|
|
||||||
}
|
|
||||||
return privileges, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// EnableProcessPrivileges enables privileges globally for the process.
|
|
||||||
func EnableProcessPrivileges(names []string) error {
|
|
||||||
return enableDisableProcessPrivilege(names, SE_PRIVILEGE_ENABLED)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DisableProcessPrivileges disables privileges globally for the process.
|
|
||||||
func DisableProcessPrivileges(names []string) error {
|
|
||||||
return enableDisableProcessPrivilege(names, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
func enableDisableProcessPrivilege(names []string, action uint32) error {
|
|
||||||
privileges, err := mapPrivileges(names)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
p, _ := windows.GetCurrentProcess()
|
|
||||||
var token windows.Token
|
|
||||||
err = windows.OpenProcessToken(p, windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, &token)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
defer token.Close()
|
|
||||||
return adjustPrivileges(token, privileges, action)
|
|
||||||
}
|
|
||||||
|
|
||||||
func adjustPrivileges(token windows.Token, privileges []uint64, action uint32) error {
|
|
||||||
var b bytes.Buffer
|
|
||||||
binary.Write(&b, binary.LittleEndian, uint32(len(privileges)))
|
|
||||||
for _, p := range privileges {
|
|
||||||
binary.Write(&b, binary.LittleEndian, p)
|
|
||||||
binary.Write(&b, binary.LittleEndian, action)
|
|
||||||
}
|
|
||||||
prevState := make([]byte, b.Len())
|
|
||||||
reqSize := uint32(0)
|
|
||||||
success, err := adjustTokenPrivileges(token, false, &b.Bytes()[0], uint32(len(prevState)), &prevState[0], &reqSize)
|
|
||||||
if !success {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err == ERROR_NOT_ALL_ASSIGNED {
|
|
||||||
return &PrivilegeError{privileges}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func getPrivilegeName(luid uint64) string {
|
|
||||||
var nameBuffer [256]uint16
|
|
||||||
bufSize := uint32(len(nameBuffer))
|
|
||||||
err := lookupPrivilegeName("", &luid, &nameBuffer[0], &bufSize)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Sprintf("<unknown privilege %d>", luid)
|
|
||||||
}
|
|
||||||
|
|
||||||
var displayNameBuffer [256]uint16
|
|
||||||
displayBufSize := uint32(len(displayNameBuffer))
|
|
||||||
var langID uint32
|
|
||||||
err = lookupPrivilegeDisplayName("", &nameBuffer[0], &displayNameBuffer[0], &displayBufSize, &langID)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Sprintf("<unknown privilege %s>", string(utf16.Decode(nameBuffer[:bufSize])))
|
|
||||||
}
|
|
||||||
|
|
||||||
return string(utf16.Decode(displayNameBuffer[:displayBufSize]))
|
|
||||||
}
|
|
||||||
|
|
||||||
func newThreadToken() (windows.Token, error) {
|
|
||||||
err := impersonateSelf(securityImpersonation)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var token windows.Token
|
|
||||||
err = openThreadToken(getCurrentThread(), syscall.TOKEN_ADJUST_PRIVILEGES|syscall.TOKEN_QUERY, false, &token)
|
|
||||||
if err != nil {
|
|
||||||
rerr := revertToSelf()
|
|
||||||
if rerr != nil {
|
|
||||||
panic(rerr)
|
|
||||||
}
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return token, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func releaseThreadToken(h windows.Token) {
|
|
||||||
err := revertToSelf()
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
h.Close()
|
|
||||||
}
|
|
||||||
-128
@@ -1,128 +0,0 @@
|
|||||||
package winio
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
"unicode/utf16"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
reparseTagMountPoint = 0xA0000003
|
|
||||||
reparseTagSymlink = 0xA000000C
|
|
||||||
)
|
|
||||||
|
|
||||||
type reparseDataBuffer struct {
|
|
||||||
ReparseTag uint32
|
|
||||||
ReparseDataLength uint16
|
|
||||||
Reserved uint16
|
|
||||||
SubstituteNameOffset uint16
|
|
||||||
SubstituteNameLength uint16
|
|
||||||
PrintNameOffset uint16
|
|
||||||
PrintNameLength uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReparsePoint describes a Win32 symlink or mount point.
|
|
||||||
type ReparsePoint struct {
|
|
||||||
Target string
|
|
||||||
IsMountPoint bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnsupportedReparsePointError is returned when trying to decode a non-symlink or
|
|
||||||
// mount point reparse point.
|
|
||||||
type UnsupportedReparsePointError struct {
|
|
||||||
Tag uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *UnsupportedReparsePointError) Error() string {
|
|
||||||
return fmt.Sprintf("unsupported reparse point %x", e.Tag)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeReparsePoint decodes a Win32 REPARSE_DATA_BUFFER structure containing either a symlink
|
|
||||||
// or a mount point.
|
|
||||||
func DecodeReparsePoint(b []byte) (*ReparsePoint, error) {
|
|
||||||
tag := binary.LittleEndian.Uint32(b[0:4])
|
|
||||||
return DecodeReparsePointData(tag, b[8:])
|
|
||||||
}
|
|
||||||
|
|
||||||
func DecodeReparsePointData(tag uint32, b []byte) (*ReparsePoint, error) {
|
|
||||||
isMountPoint := false
|
|
||||||
switch tag {
|
|
||||||
case reparseTagMountPoint:
|
|
||||||
isMountPoint = true
|
|
||||||
case reparseTagSymlink:
|
|
||||||
default:
|
|
||||||
return nil, &UnsupportedReparsePointError{tag}
|
|
||||||
}
|
|
||||||
nameOffset := 8 + binary.LittleEndian.Uint16(b[4:6])
|
|
||||||
if !isMountPoint {
|
|
||||||
nameOffset += 4
|
|
||||||
}
|
|
||||||
nameLength := binary.LittleEndian.Uint16(b[6:8])
|
|
||||||
name := make([]uint16, nameLength/2)
|
|
||||||
err := binary.Read(bytes.NewReader(b[nameOffset:nameOffset+nameLength]), binary.LittleEndian, &name)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &ReparsePoint{string(utf16.Decode(name)), isMountPoint}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isDriveLetter(c byte) bool {
|
|
||||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeReparsePoint encodes a Win32 REPARSE_DATA_BUFFER structure describing a symlink or
|
|
||||||
// mount point.
|
|
||||||
func EncodeReparsePoint(rp *ReparsePoint) []byte {
|
|
||||||
// Generate an NT path and determine if this is a relative path.
|
|
||||||
var ntTarget string
|
|
||||||
relative := false
|
|
||||||
if strings.HasPrefix(rp.Target, `\\?\`) {
|
|
||||||
ntTarget = `\??\` + rp.Target[4:]
|
|
||||||
} else if strings.HasPrefix(rp.Target, `\\`) {
|
|
||||||
ntTarget = `\??\UNC\` + rp.Target[2:]
|
|
||||||
} else if len(rp.Target) >= 2 && isDriveLetter(rp.Target[0]) && rp.Target[1] == ':' {
|
|
||||||
ntTarget = `\??\` + rp.Target
|
|
||||||
} else {
|
|
||||||
ntTarget = rp.Target
|
|
||||||
relative = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// The paths must be NUL-terminated even though they are counted strings.
|
|
||||||
target16 := utf16.Encode([]rune(rp.Target + "\x00"))
|
|
||||||
ntTarget16 := utf16.Encode([]rune(ntTarget + "\x00"))
|
|
||||||
|
|
||||||
size := int(unsafe.Sizeof(reparseDataBuffer{})) - 8
|
|
||||||
size += len(ntTarget16)*2 + len(target16)*2
|
|
||||||
|
|
||||||
tag := uint32(reparseTagMountPoint)
|
|
||||||
if !rp.IsMountPoint {
|
|
||||||
tag = reparseTagSymlink
|
|
||||||
size += 4 // Add room for symlink flags
|
|
||||||
}
|
|
||||||
|
|
||||||
data := reparseDataBuffer{
|
|
||||||
ReparseTag: tag,
|
|
||||||
ReparseDataLength: uint16(size),
|
|
||||||
SubstituteNameOffset: 0,
|
|
||||||
SubstituteNameLength: uint16((len(ntTarget16) - 1) * 2),
|
|
||||||
PrintNameOffset: uint16(len(ntTarget16) * 2),
|
|
||||||
PrintNameLength: uint16((len(target16) - 1) * 2),
|
|
||||||
}
|
|
||||||
|
|
||||||
var b bytes.Buffer
|
|
||||||
binary.Write(&b, binary.LittleEndian, &data)
|
|
||||||
if !rp.IsMountPoint {
|
|
||||||
flags := uint32(0)
|
|
||||||
if relative {
|
|
||||||
flags |= 1
|
|
||||||
}
|
|
||||||
binary.Write(&b, binary.LittleEndian, flags)
|
|
||||||
}
|
|
||||||
|
|
||||||
binary.Write(&b, binary.LittleEndian, ntTarget16)
|
|
||||||
binary.Write(&b, binary.LittleEndian, target16)
|
|
||||||
return b.Bytes()
|
|
||||||
}
|
|
||||||
-98
@@ -1,98 +0,0 @@
|
|||||||
// +build windows
|
|
||||||
|
|
||||||
package winio
|
|
||||||
|
|
||||||
import (
|
|
||||||
"syscall"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
//sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW
|
|
||||||
//sys convertSidToStringSid(sid *byte, str **uint16) (err error) = advapi32.ConvertSidToStringSidW
|
|
||||||
//sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW
|
|
||||||
//sys convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW
|
|
||||||
//sys localFree(mem uintptr) = LocalFree
|
|
||||||
//sys getSecurityDescriptorLength(sd uintptr) (len uint32) = advapi32.GetSecurityDescriptorLength
|
|
||||||
|
|
||||||
const (
|
|
||||||
cERROR_NONE_MAPPED = syscall.Errno(1332)
|
|
||||||
)
|
|
||||||
|
|
||||||
type AccountLookupError struct {
|
|
||||||
Name string
|
|
||||||
Err error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *AccountLookupError) Error() string {
|
|
||||||
if e.Name == "" {
|
|
||||||
return "lookup account: empty account name specified"
|
|
||||||
}
|
|
||||||
var s string
|
|
||||||
switch e.Err {
|
|
||||||
case cERROR_NONE_MAPPED:
|
|
||||||
s = "not found"
|
|
||||||
default:
|
|
||||||
s = e.Err.Error()
|
|
||||||
}
|
|
||||||
return "lookup account " + e.Name + ": " + s
|
|
||||||
}
|
|
||||||
|
|
||||||
type SddlConversionError struct {
|
|
||||||
Sddl string
|
|
||||||
Err error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *SddlConversionError) Error() string {
|
|
||||||
return "convert " + e.Sddl + ": " + e.Err.Error()
|
|
||||||
}
|
|
||||||
|
|
||||||
// LookupSidByName looks up the SID of an account by name
|
|
||||||
func LookupSidByName(name string) (sid string, err error) {
|
|
||||||
if name == "" {
|
|
||||||
return "", &AccountLookupError{name, cERROR_NONE_MAPPED}
|
|
||||||
}
|
|
||||||
|
|
||||||
var sidSize, sidNameUse, refDomainSize uint32
|
|
||||||
err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse)
|
|
||||||
if err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER {
|
|
||||||
return "", &AccountLookupError{name, err}
|
|
||||||
}
|
|
||||||
sidBuffer := make([]byte, sidSize)
|
|
||||||
refDomainBuffer := make([]uint16, refDomainSize)
|
|
||||||
err = lookupAccountName(nil, name, &sidBuffer[0], &sidSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse)
|
|
||||||
if err != nil {
|
|
||||||
return "", &AccountLookupError{name, err}
|
|
||||||
}
|
|
||||||
var strBuffer *uint16
|
|
||||||
err = convertSidToStringSid(&sidBuffer[0], &strBuffer)
|
|
||||||
if err != nil {
|
|
||||||
return "", &AccountLookupError{name, err}
|
|
||||||
}
|
|
||||||
sid = syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(strBuffer))[:])
|
|
||||||
localFree(uintptr(unsafe.Pointer(strBuffer)))
|
|
||||||
return sid, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func SddlToSecurityDescriptor(sddl string) ([]byte, error) {
|
|
||||||
var sdBuffer uintptr
|
|
||||||
err := convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &sdBuffer, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, &SddlConversionError{sddl, err}
|
|
||||||
}
|
|
||||||
defer localFree(sdBuffer)
|
|
||||||
sd := make([]byte, getSecurityDescriptorLength(sdBuffer))
|
|
||||||
copy(sd, (*[0xffff]byte)(unsafe.Pointer(sdBuffer))[:len(sd)])
|
|
||||||
return sd, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func SecurityDescriptorToSddl(sd []byte) (string, error) {
|
|
||||||
var sddl *uint16
|
|
||||||
// The returned string length seems to including an aribtrary number of terminating NULs.
|
|
||||||
// Don't use it.
|
|
||||||
err := convertSecurityDescriptorToStringSecurityDescriptor(&sd[0], 1, 0xff, &sddl, nil)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
defer localFree(uintptr(unsafe.Pointer(sddl)))
|
|
||||||
return syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(sddl))[:]), nil
|
|
||||||
}
|
|
||||||
-3
@@ -1,3 +0,0 @@
|
|||||||
package winio
|
|
||||||
|
|
||||||
//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go file.go pipe.go sd.go fileinfo.go privilege.go backup.go hvsock.go
|
|
||||||
-562
File diff suppressed because it is too large.
Load diff
-21
@@ -1,21 +0,0 @@
|
|||||||
The MIT License (MIT)
|
|
||||||
|
|
||||||
Copyright (c) 2015 Microsoft
|
|
||||||
|
|
||||||
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.
|
|
||||||
-57
@@ -1,57 +0,0 @@
|
|||||||
package osversion
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"golang.org/x/sys/windows"
|
|
||||||
)
|
|
||||||
|
|
||||||
// OSVersion is a wrapper for Windows version information
|
|
||||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx
|
|
||||||
type OSVersion struct {
|
|
||||||
Version uint32
|
|
||||||
MajorVersion uint8
|
|
||||||
MinorVersion uint8
|
|
||||||
Build uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx
|
|
||||||
type osVersionInfoEx struct {
|
|
||||||
OSVersionInfoSize uint32
|
|
||||||
MajorVersion uint32
|
|
||||||
MinorVersion uint32
|
|
||||||
BuildNumber uint32
|
|
||||||
PlatformID uint32
|
|
||||||
CSDVersion [128]uint16
|
|
||||||
ServicePackMajor uint16
|
|
||||||
ServicePackMinor uint16
|
|
||||||
SuiteMask uint16
|
|
||||||
ProductType byte
|
|
||||||
Reserve byte
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get gets the operating system version on Windows.
|
|
||||||
// The calling application must be manifested to get the correct version information.
|
|
||||||
func Get() OSVersion {
|
|
||||||
var err error
|
|
||||||
osv := OSVersion{}
|
|
||||||
osv.Version, err = windows.GetVersion()
|
|
||||||
if err != nil {
|
|
||||||
// GetVersion never fails.
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
osv.MajorVersion = uint8(osv.Version & 0xFF)
|
|
||||||
osv.MinorVersion = uint8(osv.Version >> 8 & 0xFF)
|
|
||||||
osv.Build = uint16(osv.Version >> 16)
|
|
||||||
return osv
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build gets the build-number on Windows
|
|
||||||
// The calling application must be manifested to get the correct version information.
|
|
||||||
func Build() uint16 {
|
|
||||||
return Get().Build
|
|
||||||
}
|
|
||||||
|
|
||||||
func (osv OSVersion) ToString() string {
|
|
||||||
return fmt.Sprintf("%d.%d.%d", osv.MajorVersion, osv.MinorVersion, osv.Build)
|
|
||||||
}
|
|
||||||
-27
@@ -1,27 +0,0 @@
|
|||||||
package osversion
|
|
||||||
|
|
||||||
const (
|
|
||||||
// RS1 (version 1607, codename "Redstone 1") corresponds to Windows Server
|
|
||||||
// 2016 (ltsc2016) and Windows 10 (Anniversary Update).
|
|
||||||
RS1 = 14393
|
|
||||||
|
|
||||||
// RS2 (version 1703, codename "Redstone 2") was a client-only update, and
|
|
||||||
// corresponds to Windows 10 (Creators Update).
|
|
||||||
RS2 = 15063
|
|
||||||
|
|
||||||
// RS3 (version 1709, codename "Redstone 3") corresponds to Windows Server
|
|
||||||
// 1709 (Semi-Annual Channel (SAC)), and Windows 10 (Fall Creators Update).
|
|
||||||
RS3 = 16299
|
|
||||||
|
|
||||||
// RS4 (version 1803, codename "Redstone 4") corresponds to Windows Server
|
|
||||||
// 1803 (Semi-Annual Channel (SAC)), and Windows 10 (April 2018 Update).
|
|
||||||
RS4 = 17134
|
|
||||||
|
|
||||||
// RS5 (version 1809, codename "Redstone 5") corresponds to Windows Server
|
|
||||||
// 2019 (ltsc2019), and Windows 10 (October 2018 Update).
|
|
||||||
RS5 = 17763
|
|
||||||
|
|
||||||
// V19H1 (version 1903) corresponds to Windows Server 1903 (semi-annual
|
|
||||||
// channel).
|
|
||||||
V19H1 = 18362
|
|
||||||
)
|
|
||||||
-2
@@ -1,2 +0,0 @@
|
|||||||
language: go
|
|
||||||
go: 1.1
|
|
||||||
-27
@@ -1,27 +0,0 @@
|
|||||||
"New BSD License"
|
|
||||||
|
|
||||||
Copyright (c) 2013, Andreas Koch "Andyk"
|
|
||||||
All rights reserved.
|
|
||||||
|
|
||||||
Redistribution and use in source and binary forms, with or without
|
|
||||||
modification, are permitted provided that the following conditions are met:
|
|
||||||
|
|
||||||
* Redistributions of source code must retain the above copyright
|
|
||||||
notice, this list of conditions and the following disclaimer.
|
|
||||||
* Redistributions in binary form must reproduce the above copyright
|
|
||||||
notice, this list of conditions and the following disclaimer in the
|
|
||||||
documentation and/or other materials provided with the distribution.
|
|
||||||
* Neither the name of the author nor the
|
|
||||||
names of its contributors may be used to endorse or promote products
|
|
||||||
derived from this software without specific prior written permission.
|
|
||||||
|
|
||||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
||||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
||||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
||||||
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
|
|
||||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
||||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
||||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
|
||||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
||||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
-90
@@ -1,90 +0,0 @@
|
|||||||
# fswatch
|
|
||||||
|
|
||||||
fswatch is a go library for watching file system changes to **does not** depend on inotify.
|
|
||||||
|
|
||||||
## Motivation
|
|
||||||
|
|
||||||
Why not use [inotify](http://en.wikipedia.org/wiki/Inotify)? Even though there are great libraries like [fsnotify](https://github.com/howeyc/fsnotify) that offer cross platform file system change notifications - the approach breaks when you want to watch a lot of files or folder.
|
|
||||||
|
|
||||||
For example the default ulimit for Mac OS is set to 512. If you need to watch more files you have to increase the ulimit for open files per process. And this sucks.
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
### Watching a single file
|
|
||||||
|
|
||||||
If you want to watch a single file use the `NewFileWatcher` function to create a new file watcher:
|
|
||||||
|
|
||||||
```go
|
|
||||||
go func() {
|
|
||||||
fileWatcher := fswatch.NewFileWatcher("Some-file").Start()
|
|
||||||
|
|
||||||
for fileWatcher.IsRunning() {
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-fileWatcher.Modified:
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
// file changed. do something.
|
|
||||||
}()
|
|
||||||
|
|
||||||
case <-fileWatcher.Moved:
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
// file moved. do something.
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
```
|
|
||||||
|
|
||||||
### Watching a folder
|
|
||||||
|
|
||||||
To watch a whole folder for new, modified or deleted files you can use the `NewFolderWatcher` function.
|
|
||||||
|
|
||||||
Parameters:
|
|
||||||
|
|
||||||
1. The directory path
|
|
||||||
2. A flag indicating whether the folder shall be watched recursively
|
|
||||||
3. An expression which decides which files are skipped
|
|
||||||
|
|
||||||
|
|
||||||
```go
|
|
||||||
go func() {
|
|
||||||
|
|
||||||
recurse := true
|
|
||||||
|
|
||||||
skipNoFile := func(path string) bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
folderWatcher := fswatch.NewFolderWatcher("some-directory", recurse, skipNoFile).Start()
|
|
||||||
|
|
||||||
for folderWatcher.IsRunning() {
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-folderWatcher.Change:
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
// some file changed, was added, moved or deleted.
|
|
||||||
}()
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}()
|
|
||||||
```
|
|
||||||
|
|
||||||
## Build Status
|
|
||||||
|
|
||||||
[](https://travis-ci.org/andreaskoch/go-fswatch)
|
|
||||||
|
|
||||||
## Contribute
|
|
||||||
|
|
||||||
If you have an idea
|
|
||||||
|
|
||||||
- how to reliably increase the limit for the maximum number of open files from within the application
|
|
||||||
- how to overcome the limitations of inotify without having to resort to checking the files for changes over and over again
|
|
||||||
- or how to make the existing code more efficient
|
|
||||||
|
|
||||||
please send me a message or a pull request. All contributions are welcome.
|
|
||||||
-33
@@ -1,33 +0,0 @@
|
|||||||
// Copyright 2013 Andreas Koch. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package fswatch
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
debugIsEnabled = false
|
|
||||||
debugMessages chan string
|
|
||||||
)
|
|
||||||
|
|
||||||
func EnableDebug() chan string {
|
|
||||||
debugIsEnabled = true
|
|
||||||
debugMessages = make(chan string, 10)
|
|
||||||
return debugMessages
|
|
||||||
}
|
|
||||||
|
|
||||||
func DisableDebug() {
|
|
||||||
debugIsEnabled = false
|
|
||||||
close(debugMessages)
|
|
||||||
}
|
|
||||||
|
|
||||||
func log(format string, v ...interface{}) {
|
|
||||||
if !debugIsEnabled {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
debugMessages <- fmt.Sprint(fmt.Sprintf(format, v...))
|
|
||||||
}
|
|
||||||
-192
@@ -1,192 +0,0 @@
|
|||||||
// Copyright 2013 Andreas Koch. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package fswatch
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var numberOfFileWatchers int
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
numberOfFolderWatchers = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func NumberOfFileWatchers() int {
|
|
||||||
return numberOfFileWatchers
|
|
||||||
}
|
|
||||||
|
|
||||||
type FileWatcher struct {
|
|
||||||
modified chan bool
|
|
||||||
moved chan bool
|
|
||||||
stopped chan bool
|
|
||||||
|
|
||||||
file string
|
|
||||||
running bool
|
|
||||||
wasStopped bool
|
|
||||||
checkInterval time.Duration
|
|
||||||
|
|
||||||
previousModTime time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFileWatcher(filePath string, checkIntervalInSeconds int) *FileWatcher {
|
|
||||||
|
|
||||||
if checkIntervalInSeconds < 1 {
|
|
||||||
panic(fmt.Sprintf("Cannot create a file watcher with a check interval of %v seconds.", checkIntervalInSeconds))
|
|
||||||
}
|
|
||||||
|
|
||||||
return &FileWatcher{
|
|
||||||
modified: make(chan bool),
|
|
||||||
moved: make(chan bool),
|
|
||||||
stopped: make(chan bool),
|
|
||||||
|
|
||||||
file: filePath,
|
|
||||||
checkInterval: time.Duration(checkIntervalInSeconds),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fileWatcher *FileWatcher) String() string {
|
|
||||||
return fmt.Sprintf("Filewatcher %q", fileWatcher.file)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fileWatcher *FileWatcher) SetFile(filePath string) {
|
|
||||||
fileWatcher.file = filePath
|
|
||||||
}
|
|
||||||
|
|
||||||
func (filewatcher *FileWatcher) Modified() chan bool {
|
|
||||||
return filewatcher.modified
|
|
||||||
}
|
|
||||||
|
|
||||||
func (filewatcher *FileWatcher) Moved() chan bool {
|
|
||||||
return filewatcher.moved
|
|
||||||
}
|
|
||||||
|
|
||||||
func (filewatcher *FileWatcher) Stopped() chan bool {
|
|
||||||
return filewatcher.stopped
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fileWatcher *FileWatcher) Start() {
|
|
||||||
fileWatcher.running = true
|
|
||||||
sleepInterval := time.Second * fileWatcher.checkInterval
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
|
|
||||||
// increment watcher count
|
|
||||||
numberOfFileWatchers++
|
|
||||||
|
|
||||||
var modTime time.Time
|
|
||||||
previousModTime := fileWatcher.getPreviousModTime()
|
|
||||||
|
|
||||||
if timeIsSet(previousModTime) {
|
|
||||||
modTime = previousModTime
|
|
||||||
} else {
|
|
||||||
currentModTime, err := getLastModTimeFromFile(fileWatcher.file)
|
|
||||||
if err != nil {
|
|
||||||
|
|
||||||
// send out the notification
|
|
||||||
log("File %q has been moved or is inaccessible.", fileWatcher.file)
|
|
||||||
go func() {
|
|
||||||
fileWatcher.moved <- true
|
|
||||||
}()
|
|
||||||
|
|
||||||
// stop this file watcher
|
|
||||||
fileWatcher.Stop()
|
|
||||||
|
|
||||||
} else {
|
|
||||||
|
|
||||||
modTime = currentModTime
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
for fileWatcher.wasStopped == false {
|
|
||||||
|
|
||||||
newModTime, err := getLastModTimeFromFile(fileWatcher.file)
|
|
||||||
if err != nil {
|
|
||||||
|
|
||||||
// send out the notification
|
|
||||||
log("File %q has been moved.", fileWatcher.file)
|
|
||||||
go func() {
|
|
||||||
fileWatcher.moved <- true
|
|
||||||
}()
|
|
||||||
|
|
||||||
// stop this file watcher
|
|
||||||
fileWatcher.Stop()
|
|
||||||
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// detect changes
|
|
||||||
if modTime.Before(newModTime) {
|
|
||||||
|
|
||||||
// send out the notification
|
|
||||||
log("File %q has been modified.", fileWatcher.file)
|
|
||||||
go func() {
|
|
||||||
fileWatcher.modified <- true
|
|
||||||
}()
|
|
||||||
|
|
||||||
} else {
|
|
||||||
|
|
||||||
log("File %q has not changed.", fileWatcher.file)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// assign the new modtime
|
|
||||||
modTime = newModTime
|
|
||||||
|
|
||||||
time.Sleep(sleepInterval)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
fileWatcher.running = false
|
|
||||||
|
|
||||||
// capture the entry list for a restart
|
|
||||||
fileWatcher.captureModTime(modTime)
|
|
||||||
|
|
||||||
// inform channel-subscribers
|
|
||||||
go func() {
|
|
||||||
fileWatcher.stopped <- true
|
|
||||||
}()
|
|
||||||
|
|
||||||
// decrement the watch counter
|
|
||||||
numberOfFileWatchers--
|
|
||||||
|
|
||||||
// final log message
|
|
||||||
log("Stopped file watcher %q", fileWatcher.String())
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fileWatcher *FileWatcher) Stop() {
|
|
||||||
log("Stopping file watcher %q", fileWatcher.String())
|
|
||||||
fileWatcher.wasStopped = true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fileWatcher *FileWatcher) IsRunning() bool {
|
|
||||||
return fileWatcher.running
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fileWatcher *FileWatcher) getPreviousModTime() time.Time {
|
|
||||||
return fileWatcher.previousModTime
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remember the last mod time for a later restart
|
|
||||||
func (fileWatcher *FileWatcher) captureModTime(modTime time.Time) {
|
|
||||||
fileWatcher.previousModTime = modTime
|
|
||||||
}
|
|
||||||
|
|
||||||
func getLastModTimeFromFile(file string) (time.Time, error) {
|
|
||||||
fileInfo, err := os.Stat(file)
|
|
||||||
if err != nil {
|
|
||||||
return time.Time{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return fileInfo.ModTime(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func timeIsSet(t time.Time) bool {
|
|
||||||
return time.Time{} == t
|
|
||||||
}
|
|
||||||
-250
@@ -1,250 +0,0 @@
|
|||||||
// Copyright 2013 Andreas Koch. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package fswatch
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io/ioutil"
|
|
||||||
"path/filepath"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var numberOfFolderWatchers int
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
numberOfFolderWatchers = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func NumberOfFolderWatchers() int {
|
|
||||||
return numberOfFolderWatchers
|
|
||||||
}
|
|
||||||
|
|
||||||
type FolderWatcher struct {
|
|
||||||
changeDetails chan *FolderChange
|
|
||||||
|
|
||||||
modified chan bool
|
|
||||||
moved chan bool
|
|
||||||
stopped chan bool
|
|
||||||
|
|
||||||
recurse bool
|
|
||||||
skipFile func(path string) bool
|
|
||||||
|
|
||||||
debug bool
|
|
||||||
folder string
|
|
||||||
running bool
|
|
||||||
wasStopped bool
|
|
||||||
checkInterval time.Duration
|
|
||||||
|
|
||||||
previousEntries []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFolderWatcher(folderPath string, recurse bool, skipFile func(path string) bool, checkIntervalInSeconds int) *FolderWatcher {
|
|
||||||
|
|
||||||
if checkIntervalInSeconds < 1 {
|
|
||||||
panic(fmt.Sprintf("Cannot create a folder watcher with a check interval of %v seconds.", checkIntervalInSeconds))
|
|
||||||
}
|
|
||||||
|
|
||||||
return &FolderWatcher{
|
|
||||||
|
|
||||||
modified: make(chan bool),
|
|
||||||
moved: make(chan bool),
|
|
||||||
stopped: make(chan bool),
|
|
||||||
|
|
||||||
changeDetails: make(chan *FolderChange),
|
|
||||||
|
|
||||||
recurse: recurse,
|
|
||||||
skipFile: skipFile,
|
|
||||||
|
|
||||||
debug: true,
|
|
||||||
folder: folderPath,
|
|
||||||
checkInterval: time.Duration(checkIntervalInSeconds),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderWatcher *FolderWatcher) String() string {
|
|
||||||
return fmt.Sprintf("Folderwatcher %q", folderWatcher.folder)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderWatcher *FolderWatcher) Modified() chan bool {
|
|
||||||
return folderWatcher.modified
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderWatcher *FolderWatcher) Moved() chan bool {
|
|
||||||
return folderWatcher.moved
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderWatcher *FolderWatcher) Stopped() chan bool {
|
|
||||||
return folderWatcher.stopped
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderWatcher *FolderWatcher) ChangeDetails() chan *FolderChange {
|
|
||||||
return folderWatcher.changeDetails
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderWatcher *FolderWatcher) Start() {
|
|
||||||
folderWatcher.running = true
|
|
||||||
sleepInterval := time.Second * folderWatcher.checkInterval
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
|
|
||||||
// get existing entries
|
|
||||||
var entryList []string
|
|
||||||
directory := folderWatcher.folder
|
|
||||||
|
|
||||||
previousEntryList := folderWatcher.getPreviousEntryList()
|
|
||||||
|
|
||||||
if previousEntryList != nil {
|
|
||||||
|
|
||||||
// use the entry list from a previous run
|
|
||||||
entryList = previousEntryList
|
|
||||||
|
|
||||||
} else {
|
|
||||||
|
|
||||||
// use a new entry list
|
|
||||||
newEntryList, _ := getFolderEntries(directory, folderWatcher.recurse, folderWatcher.skipFile)
|
|
||||||
entryList = newEntryList
|
|
||||||
}
|
|
||||||
|
|
||||||
// increment watcher count
|
|
||||||
numberOfFolderWatchers++
|
|
||||||
|
|
||||||
for folderWatcher.wasStopped == false {
|
|
||||||
|
|
||||||
// get new entries
|
|
||||||
updatedEntryList, _ := getFolderEntries(directory, folderWatcher.recurse, folderWatcher.skipFile)
|
|
||||||
|
|
||||||
// check for new items
|
|
||||||
newItems := make([]string, 0)
|
|
||||||
modifiedItems := make([]string, 0)
|
|
||||||
|
|
||||||
for _, entry := range updatedEntryList {
|
|
||||||
|
|
||||||
if isNewItem := !sliceContainsElement(entryList, entry); isNewItem {
|
|
||||||
// entry is new
|
|
||||||
newItems = append(newItems, entry)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// check if the file changed
|
|
||||||
if newModTime, err := getLastModTimeFromFile(entry); err == nil {
|
|
||||||
|
|
||||||
// check if file has been modified
|
|
||||||
timeOfLastCheck := time.Now().Add(sleepInterval * -1)
|
|
||||||
|
|
||||||
if timeOfLastCheck.Before(newModTime) {
|
|
||||||
|
|
||||||
// existing entry has been modified
|
|
||||||
modifiedItems = append(modifiedItems, entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// check for moved items
|
|
||||||
movedItems := make([]string, 0)
|
|
||||||
for _, entry := range entryList {
|
|
||||||
isMoved := !sliceContainsElement(updatedEntryList, entry)
|
|
||||||
if isMoved {
|
|
||||||
movedItems = append(movedItems, entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// assign the new list
|
|
||||||
entryList = updatedEntryList
|
|
||||||
|
|
||||||
// sleep
|
|
||||||
time.Sleep(sleepInterval)
|
|
||||||
|
|
||||||
// check if something happened
|
|
||||||
if len(newItems) > 0 || len(movedItems) > 0 || len(modifiedItems) > 0 {
|
|
||||||
|
|
||||||
// send out change
|
|
||||||
go func() {
|
|
||||||
folderWatcher.modified <- true
|
|
||||||
}()
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
log("Folder %q changed", directory)
|
|
||||||
folderWatcher.changeDetails <- newFolderChange(newItems, movedItems, modifiedItems)
|
|
||||||
}()
|
|
||||||
} else {
|
|
||||||
log("No change in folder %q", directory)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
folderWatcher.running = false
|
|
||||||
|
|
||||||
// capture the entry list for a restart
|
|
||||||
folderWatcher.captureEntryList(entryList)
|
|
||||||
|
|
||||||
// inform channel-subscribers
|
|
||||||
go func() {
|
|
||||||
folderWatcher.stopped <- true
|
|
||||||
}()
|
|
||||||
|
|
||||||
// decrement the watch counter
|
|
||||||
numberOfFolderWatchers--
|
|
||||||
|
|
||||||
// final log message
|
|
||||||
log("Stopped folder watcher %q", folderWatcher.String())
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderWatcher *FolderWatcher) Stop() {
|
|
||||||
log("Stopping folder watcher %q", folderWatcher.String())
|
|
||||||
folderWatcher.wasStopped = true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderWatcher *FolderWatcher) IsRunning() bool {
|
|
||||||
return folderWatcher.running
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderWatcher *FolderWatcher) getPreviousEntryList() []string {
|
|
||||||
return folderWatcher.previousEntries
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remember the entry list for a later restart
|
|
||||||
func (folderWatcher *FolderWatcher) captureEntryList(list []string) {
|
|
||||||
folderWatcher.previousEntries = list
|
|
||||||
}
|
|
||||||
|
|
||||||
func getFolderEntries(directory string, recurse bool, skipFile func(path string) bool) ([]string, error) {
|
|
||||||
|
|
||||||
// the return array
|
|
||||||
entries := make([]string, 0)
|
|
||||||
|
|
||||||
// read the entries of the specified directory
|
|
||||||
directoryEntries, err := ioutil.ReadDir(directory)
|
|
||||||
if err != nil {
|
|
||||||
return entries, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, entry := range directoryEntries {
|
|
||||||
|
|
||||||
// get the full path
|
|
||||||
subEntryPath := filepath.Join(directory, entry.Name())
|
|
||||||
|
|
||||||
// recurse or append
|
|
||||||
if recurse && entry.IsDir() {
|
|
||||||
|
|
||||||
// recurse (ignore errors, unreadable sub directories don't hurt much)
|
|
||||||
subFolderEntries, _ := getFolderEntries(subEntryPath, recurse, skipFile)
|
|
||||||
entries = append(entries, subFolderEntries...)
|
|
||||||
|
|
||||||
} else {
|
|
||||||
|
|
||||||
// check if the enty shall be ignored
|
|
||||||
if skipFile(subEntryPath) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// append entry
|
|
||||||
entries = append(entries, subEntryPath)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return entries, nil
|
|
||||||
}
|
|
||||||
-46
@@ -1,46 +0,0 @@
|
|||||||
// Copyright 2013 Andreas Koch. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package fswatch
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type FolderChange struct {
|
|
||||||
timeStamp time.Time
|
|
||||||
newItems []string
|
|
||||||
movedItems []string
|
|
||||||
modifiedItems []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func newFolderChange(newItems, movedItems, modifiedItems []string) *FolderChange {
|
|
||||||
return &FolderChange{
|
|
||||||
timeStamp: time.Now(),
|
|
||||||
newItems: newItems,
|
|
||||||
movedItems: movedItems,
|
|
||||||
modifiedItems: modifiedItems,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderChange *FolderChange) String() string {
|
|
||||||
return fmt.Sprintf("Folderchange (timestamp: %s, new: %d, moved: %d)", folderChange.timeStamp, len(folderChange.New()), len(folderChange.Moved()))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderChange *FolderChange) TimeStamp() time.Time {
|
|
||||||
return folderChange.timeStamp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderChange *FolderChange) New() []string {
|
|
||||||
return folderChange.newItems
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderChange *FolderChange) Moved() []string {
|
|
||||||
return folderChange.movedItems
|
|
||||||
}
|
|
||||||
|
|
||||||
func (folderChange *FolderChange) Modified() []string {
|
|
||||||
return folderChange.modifiedItems
|
|
||||||
}
|
|
||||||
-14
@@ -1,14 +0,0 @@
|
|||||||
// Copyright 2013 Andreas Koch. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package fswatch
|
|
||||||
|
|
||||||
func sliceContainsElement(list []string, elem string) bool {
|
|
||||||
for _, t := range list {
|
|
||||||
if t == elem {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
-15
@@ -1,15 +0,0 @@
|
|||||||
// Copyright 2013 Andreas Koch. All rights reserved.
|
|
||||||
// Use of this source code is governed by a BSD-style
|
|
||||||
// license that can be found in the LICENSE file.
|
|
||||||
|
|
||||||
package fswatch
|
|
||||||
|
|
||||||
type Watcher interface {
|
|
||||||
Modified() chan bool
|
|
||||||
Moved() chan bool
|
|
||||||
Stopped() chan bool
|
|
||||||
|
|
||||||
Start()
|
|
||||||
Stop()
|
|
||||||
IsRunning() bool
|
|
||||||
}
|
|
||||||
-191
@@ -1,191 +0,0 @@
|
|||||||
|
|
||||||
Apache License
|
|
||||||
Version 2.0, January 2004
|
|
||||||
https://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
||||||
|
|
||||||
1. Definitions.
|
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction,
|
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
|
||||||
the copyright owner that is granting the License.
|
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
|
||||||
other entities that control, are controlled by, or are under common
|
|
||||||
control with that entity. For the purposes of this definition,
|
|
||||||
"control" means (i) the power, direct or indirect, to cause the
|
|
||||||
direction or management of such entity, whether by contract or
|
|
||||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
||||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
|
||||||
exercising permissions granted by this License.
|
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
|
||||||
including but not limited to software source code, documentation
|
|
||||||
source, and configuration files.
|
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
|
||||||
transformation or translation of a Source form, including but
|
|
||||||
not limited to compiled object code, generated documentation,
|
|
||||||
and conversions to other media types.
|
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
|
||||||
Object form, made available under the License, as indicated by a
|
|
||||||
copyright notice that is included in or attached to the work
|
|
||||||
(an example is provided in the Appendix below).
|
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
|
||||||
form, that is based on (or derived from) the Work and for which the
|
|
||||||
editorial revisions, annotations, elaborations, or other modifications
|
|
||||||
represent, as a whole, an original work of authorship. For the purposes
|
|
||||||
of this License, Derivative Works shall not include works that remain
|
|
||||||
separable from, or merely link (or bind by name) to the interfaces of,
|
|
||||||
the Work and Derivative Works thereof.
|
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
|
||||||
the original version of the Work and any modifications or additions
|
|
||||||
to that Work or Derivative Works thereof, that is intentionally
|
|
||||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
||||||
or by an individual or Legal Entity authorized to submit on behalf of
|
|
||||||
the copyright owner. For the purposes of this definition, "submitted"
|
|
||||||
means any form of electronic, verbal, or written communication sent
|
|
||||||
to the Licensor or its representatives, including but not limited to
|
|
||||||
communication on electronic mailing lists, source code control systems,
|
|
||||||
and issue tracking systems that are managed by, or on behalf of, the
|
|
||||||
Licensor for the purpose of discussing and improving the Work, but
|
|
||||||
excluding communication that is conspicuously marked or otherwise
|
|
||||||
designated in writing by the copyright owner as "Not a Contribution."
|
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
|
||||||
subsequently incorporated within the Work.
|
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
copyright license to reproduce, prepare Derivative Works of,
|
|
||||||
publicly display, publicly perform, sublicense, and distribute the
|
|
||||||
Work and such Derivative Works in Source or Object form.
|
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
(except as stated in this section) patent license to make, have made,
|
|
||||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
||||||
where such license applies only to those patent claims licensable
|
|
||||||
by such Contributor that are necessarily infringed by their
|
|
||||||
Contribution(s) alone or by combination of their Contribution(s)
|
|
||||||
with the Work to which such Contribution(s) was submitted. If You
|
|
||||||
institute patent litigation against any entity (including a
|
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
||||||
or a Contribution incorporated within the Work constitutes direct
|
|
||||||
or contributory patent infringement, then any patent licenses
|
|
||||||
granted to You under this License for that Work shall terminate
|
|
||||||
as of the date such litigation is filed.
|
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the
|
|
||||||
Work or Derivative Works thereof in any medium, with or without
|
|
||||||
modifications, and in Source or Object form, provided that You
|
|
||||||
meet the following conditions:
|
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
|
||||||
Derivative Works a copy of this License; and
|
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices
|
|
||||||
stating that You changed the files; and
|
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
|
||||||
that You distribute, all copyright, patent, trademark, and
|
|
||||||
attribution notices from the Source form of the Work,
|
|
||||||
excluding those notices that do not pertain to any part of
|
|
||||||
the Derivative Works; and
|
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
|
||||||
distribution, then any Derivative Works that You distribute must
|
|
||||||
include a readable copy of the attribution notices contained
|
|
||||||
within such NOTICE file, excluding those notices that do not
|
|
||||||
pertain to any part of the Derivative Works, in at least one
|
|
||||||
of the following places: within a NOTICE text file distributed
|
|
||||||
as part of the Derivative Works; within the Source form or
|
|
||||||
documentation, if provided along with the Derivative Works; or,
|
|
||||||
within a display generated by the Derivative Works, if and
|
|
||||||
wherever such third-party notices normally appear. The contents
|
|
||||||
of the NOTICE file are for informational purposes only and
|
|
||||||
do not modify the License. You may add Your own attribution
|
|
||||||
notices within Derivative Works that You distribute, alongside
|
|
||||||
or as an addendum to the NOTICE text from the Work, provided
|
|
||||||
that such additional attribution notices cannot be construed
|
|
||||||
as modifying the License.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
|
||||||
may provide additional or different license terms and conditions
|
|
||||||
for use, reproduction, or distribution of Your modifications, or
|
|
||||||
for any such Derivative Works as a whole, provided Your use,
|
|
||||||
reproduction, and distribution of the Work otherwise complies with
|
|
||||||
the conditions stated in this License.
|
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
||||||
any Contribution intentionally submitted for inclusion in the Work
|
|
||||||
by You to the Licensor shall be under the terms and conditions of
|
|
||||||
this License, without any additional terms or conditions.
|
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify
|
|
||||||
the terms of any separate license agreement you may have executed
|
|
||||||
with Licensor regarding such Contributions.
|
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
|
||||||
names, trademarks, service marks, or product names of the Licensor,
|
|
||||||
except as required for reasonable and customary use in describing the
|
|
||||||
origin of the Work and reproducing the content of the NOTICE file.
|
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
||||||
agreed to in writing, Licensor provides the Work (and each
|
|
||||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
||||||
implied, including, without limitation, any warranties or conditions
|
|
||||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
||||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
||||||
appropriateness of using or redistributing the Work and assume any
|
|
||||||
risks associated with Your exercise of permissions under this License.
|
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory,
|
|
||||||
whether in tort (including negligence), contract, or otherwise,
|
|
||||||
unless required by applicable law (such as deliberate and grossly
|
|
||||||
negligent acts) or agreed to in writing, shall any Contributor be
|
|
||||||
liable to You for damages, including any direct, indirect, special,
|
|
||||||
incidental, or consequential damages of any character arising as a
|
|
||||||
result of this License or out of the use or inability to use the
|
|
||||||
Work (including but not limited to damages for loss of goodwill,
|
|
||||||
work stoppage, computer failure or malfunction, or any and all
|
|
||||||
other commercial damages or losses), even if such Contributor
|
|
||||||
has been advised of the possibility of such damages.
|
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing
|
|
||||||
the Work or Derivative Works thereof, You may choose to offer,
|
|
||||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
||||||
or other liability obligations and/or rights consistent with this
|
|
||||||
License. However, in accepting such obligations, You may act only
|
|
||||||
on Your own behalf and on Your sole responsibility, not on behalf
|
|
||||||
of any other Contributor, and only if You agree to indemnify,
|
|
||||||
defend, and hold each Contributor harmless for any liability
|
|
||||||
incurred by, or claims asserted against, such Contributor by reason
|
|
||||||
of your accepting any such warranty or additional liability.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
Copyright The containerd Authors
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
-16
@@ -1,16 +0,0 @@
|
|||||||
Docker
|
|
||||||
Copyright 2012-2015 Docker, Inc.
|
|
||||||
|
|
||||||
This product includes software developed at Docker, Inc. (https://www.docker.com).
|
|
||||||
|
|
||||||
The following is courtesy of our legal counsel:
|
|
||||||
|
|
||||||
|
|
||||||
Use and transfer of Docker may be subject to certain restrictions by the
|
|
||||||
United States and other governments.
|
|
||||||
It is your responsibility to ensure that your use and/or transfer does not
|
|
||||||
violate applicable laws.
|
|
||||||
|
|
||||||
For more information, please see https://www.bis.doc.gov
|
|
||||||
|
|
||||||
See also https://www.apache.org/dev/crypto.html and/or seek legal counsel.
|
|
||||||
-93
@@ -1,93 +0,0 @@
|
|||||||
/*
|
|
||||||
Copyright The containerd Authors.
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Package errdefs defines the common errors used throughout containerd
|
|
||||||
// packages.
|
|
||||||
//
|
|
||||||
// Use with errors.Wrap and error.Wrapf to add context to an error.
|
|
||||||
//
|
|
||||||
// To detect an error class, use the IsXXX functions to tell whether an error
|
|
||||||
// is of a certain type.
|
|
||||||
//
|
|
||||||
// The functions ToGRPC and FromGRPC can be used to map server-side and
|
|
||||||
// client-side errors to the correct types.
|
|
||||||
package errdefs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Definitions of common error types used throughout containerd. All containerd
|
|
||||||
// errors returned by most packages will map into one of these errors classes.
|
|
||||||
// Packages should return errors of these types when they want to instruct a
|
|
||||||
// client to take a particular action.
|
|
||||||
//
|
|
||||||
// For the most part, we just try to provide local grpc errors. Most conditions
|
|
||||||
// map very well to those defined by grpc.
|
|
||||||
var (
|
|
||||||
ErrUnknown = errors.New("unknown") // used internally to represent a missed mapping.
|
|
||||||
ErrInvalidArgument = errors.New("invalid argument")
|
|
||||||
ErrNotFound = errors.New("not found")
|
|
||||||
ErrAlreadyExists = errors.New("already exists")
|
|
||||||
ErrFailedPrecondition = errors.New("failed precondition")
|
|
||||||
ErrUnavailable = errors.New("unavailable")
|
|
||||||
ErrNotImplemented = errors.New("not implemented") // represents not supported and unimplemented
|
|
||||||
)
|
|
||||||
|
|
||||||
// IsInvalidArgument returns true if the error is due to an invalid argument
|
|
||||||
func IsInvalidArgument(err error) bool {
|
|
||||||
return errors.Cause(err) == ErrInvalidArgument
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsNotFound returns true if the error is due to a missing object
|
|
||||||
func IsNotFound(err error) bool {
|
|
||||||
return errors.Cause(err) == ErrNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsAlreadyExists returns true if the error is due to an already existing
|
|
||||||
// metadata item
|
|
||||||
func IsAlreadyExists(err error) bool {
|
|
||||||
return errors.Cause(err) == ErrAlreadyExists
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsFailedPrecondition returns true if an operation could not proceed to the
|
|
||||||
// lack of a particular condition
|
|
||||||
func IsFailedPrecondition(err error) bool {
|
|
||||||
return errors.Cause(err) == ErrFailedPrecondition
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsUnavailable returns true if the error is due to a resource being unavailable
|
|
||||||
func IsUnavailable(err error) bool {
|
|
||||||
return errors.Cause(err) == ErrUnavailable
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsNotImplemented returns true if the error is due to not being implemented
|
|
||||||
func IsNotImplemented(err error) bool {
|
|
||||||
return errors.Cause(err) == ErrNotImplemented
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsCanceled returns true if the error is due to `context.Canceled`.
|
|
||||||
func IsCanceled(err error) bool {
|
|
||||||
return errors.Cause(err) == context.Canceled
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsDeadlineExceeded returns true if the error is due to
|
|
||||||
// `context.DeadlineExceeded`.
|
|
||||||
func IsDeadlineExceeded(err error) bool {
|
|
||||||
return errors.Cause(err) == context.DeadlineExceeded
|
|
||||||
}
|
|
||||||
-147
@@ -1,147 +0,0 @@
|
|||||||
/*
|
|
||||||
Copyright The containerd Authors.
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package errdefs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ToGRPC will attempt to map the backend containerd error into a grpc error,
|
|
||||||
// using the original error message as a description.
|
|
||||||
//
|
|
||||||
// Further information may be extracted from certain errors depending on their
|
|
||||||
// type.
|
|
||||||
//
|
|
||||||
// If the error is unmapped, the original error will be returned to be handled
|
|
||||||
// by the regular grpc error handling stack.
|
|
||||||
func ToGRPC(err error) error {
|
|
||||||
if err == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if isGRPCError(err) {
|
|
||||||
// error has already been mapped to grpc
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
switch {
|
|
||||||
case IsInvalidArgument(err):
|
|
||||||
return status.Errorf(codes.InvalidArgument, err.Error())
|
|
||||||
case IsNotFound(err):
|
|
||||||
return status.Errorf(codes.NotFound, err.Error())
|
|
||||||
case IsAlreadyExists(err):
|
|
||||||
return status.Errorf(codes.AlreadyExists, err.Error())
|
|
||||||
case IsFailedPrecondition(err):
|
|
||||||
return status.Errorf(codes.FailedPrecondition, err.Error())
|
|
||||||
case IsUnavailable(err):
|
|
||||||
return status.Errorf(codes.Unavailable, err.Error())
|
|
||||||
case IsNotImplemented(err):
|
|
||||||
return status.Errorf(codes.Unimplemented, err.Error())
|
|
||||||
case IsCanceled(err):
|
|
||||||
return status.Errorf(codes.Canceled, err.Error())
|
|
||||||
case IsDeadlineExceeded(err):
|
|
||||||
return status.Errorf(codes.DeadlineExceeded, err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// ToGRPCf maps the error to grpc error codes, assembling the formatting string
|
|
||||||
// and combining it with the target error string.
|
|
||||||
//
|
|
||||||
// This is equivalent to errors.ToGRPC(errors.Wrapf(err, format, args...))
|
|
||||||
func ToGRPCf(err error, format string, args ...interface{}) error {
|
|
||||||
return ToGRPC(errors.Wrapf(err, format, args...))
|
|
||||||
}
|
|
||||||
|
|
||||||
// FromGRPC returns the underlying error from a grpc service based on the grpc error code
|
|
||||||
func FromGRPC(err error) error {
|
|
||||||
if err == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var cls error // divide these into error classes, becomes the cause
|
|
||||||
|
|
||||||
switch code(err) {
|
|
||||||
case codes.InvalidArgument:
|
|
||||||
cls = ErrInvalidArgument
|
|
||||||
case codes.AlreadyExists:
|
|
||||||
cls = ErrAlreadyExists
|
|
||||||
case codes.NotFound:
|
|
||||||
cls = ErrNotFound
|
|
||||||
case codes.Unavailable:
|
|
||||||
cls = ErrUnavailable
|
|
||||||
case codes.FailedPrecondition:
|
|
||||||
cls = ErrFailedPrecondition
|
|
||||||
case codes.Unimplemented:
|
|
||||||
cls = ErrNotImplemented
|
|
||||||
case codes.Canceled:
|
|
||||||
cls = context.Canceled
|
|
||||||
case codes.DeadlineExceeded:
|
|
||||||
cls = context.DeadlineExceeded
|
|
||||||
default:
|
|
||||||
cls = ErrUnknown
|
|
||||||
}
|
|
||||||
|
|
||||||
msg := rebaseMessage(cls, err)
|
|
||||||
if msg != "" {
|
|
||||||
err = errors.Wrap(cls, msg)
|
|
||||||
} else {
|
|
||||||
err = errors.WithStack(cls)
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// rebaseMessage removes the repeats for an error at the end of an error
|
|
||||||
// string. This will happen when taking an error over grpc then remapping it.
|
|
||||||
//
|
|
||||||
// Effectively, we just remove the string of cls from the end of err if it
|
|
||||||
// appears there.
|
|
||||||
func rebaseMessage(cls error, err error) string {
|
|
||||||
desc := errDesc(err)
|
|
||||||
clss := cls.Error()
|
|
||||||
if desc == clss {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
return strings.TrimSuffix(desc, ": "+clss)
|
|
||||||
}
|
|
||||||
|
|
||||||
func isGRPCError(err error) bool {
|
|
||||||
_, ok := status.FromError(err)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func code(err error) codes.Code {
|
|
||||||
if s, ok := status.FromError(err); ok {
|
|
||||||
return s.Code()
|
|
||||||
}
|
|
||||||
return codes.Unknown
|
|
||||||
}
|
|
||||||
|
|
||||||
func errDesc(err error) string {
|
|
||||||
if s, ok := status.FromError(err); ok {
|
|
||||||
return s.Message()
|
|
||||||
}
|
|
||||||
return err.Error()
|
|
||||||
}
|
|
||||||
-16
@@ -1,16 +0,0 @@
|
|||||||
Aaron Lehmann <[email protected]>
|
|
||||||
Akash Gupta <[email protected]>
|
|
||||||
Akihiro Suda <[email protected]>
|
|
||||||
Andrew Pennebaker <[email protected]>
|
|
||||||
Brandon Philips <[email protected]>
|
|
||||||
Christopher Jones <[email protected]>
|
|
||||||
Daniel, Dao Quang Minh <[email protected]>
|
|
||||||
Derek McGowan <[email protected]>
|
|
||||||
Edward Pilatowicz <[email protected]>
|
|
||||||
Ian Campbell <[email protected]>
|
|
||||||
Justin Cormack <[email protected]>
|
|
||||||
Justin Cummins <[email protected]>
|
|
||||||
Phil Estes <[email protected]>
|
|
||||||
Stephen J Day <[email protected]>
|
|
||||||
Tobias Klauser <[email protected]>
|
|
||||||
Tonis Tiigi <[email protected]>
|
|
||||||
-191
@@ -1,191 +0,0 @@
|
|||||||
|
|
||||||
Apache License
|
|
||||||
Version 2.0, January 2004
|
|
||||||
https://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
||||||
|
|
||||||
1. Definitions.
|
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction,
|
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
|
||||||
the copyright owner that is granting the License.
|
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
|
||||||
other entities that control, are controlled by, or are under common
|
|
||||||
control with that entity. For the purposes of this definition,
|
|
||||||
"control" means (i) the power, direct or indirect, to cause the
|
|
||||||
direction or management of such entity, whether by contract or
|
|
||||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
||||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
|
||||||
exercising permissions granted by this License.
|
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
|
||||||
including but not limited to software source code, documentation
|
|
||||||
source, and configuration files.
|
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
|
||||||
transformation or translation of a Source form, including but
|
|
||||||
not limited to compiled object code, generated documentation,
|
|
||||||
and conversions to other media types.
|
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
|
||||||
Object form, made available under the License, as indicated by a
|
|
||||||
copyright notice that is included in or attached to the work
|
|
||||||
(an example is provided in the Appendix below).
|
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
|
||||||
form, that is based on (or derived from) the Work and for which the
|
|
||||||
editorial revisions, annotations, elaborations, or other modifications
|
|
||||||
represent, as a whole, an original work of authorship. For the purposes
|
|
||||||
of this License, Derivative Works shall not include works that remain
|
|
||||||
separable from, or merely link (or bind by name) to the interfaces of,
|
|
||||||
the Work and Derivative Works thereof.
|
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
|
||||||
the original version of the Work and any modifications or additions
|
|
||||||
to that Work or Derivative Works thereof, that is intentionally
|
|
||||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
||||||
or by an individual or Legal Entity authorized to submit on behalf of
|
|
||||||
the copyright owner. For the purposes of this definition, "submitted"
|
|
||||||
means any form of electronic, verbal, or written communication sent
|
|
||||||
to the Licensor or its representatives, including but not limited to
|
|
||||||
communication on electronic mailing lists, source code control systems,
|
|
||||||
and issue tracking systems that are managed by, or on behalf of, the
|
|
||||||
Licensor for the purpose of discussing and improving the Work, but
|
|
||||||
excluding communication that is conspicuously marked or otherwise
|
|
||||||
designated in writing by the copyright owner as "Not a Contribution."
|
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
|
||||||
subsequently incorporated within the Work.
|
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
copyright license to reproduce, prepare Derivative Works of,
|
|
||||||
publicly display, publicly perform, sublicense, and distribute the
|
|
||||||
Work and such Derivative Works in Source or Object form.
|
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
(except as stated in this section) patent license to make, have made,
|
|
||||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
||||||
where such license applies only to those patent claims licensable
|
|
||||||
by such Contributor that are necessarily infringed by their
|
|
||||||
Contribution(s) alone or by combination of their Contribution(s)
|
|
||||||
with the Work to which such Contribution(s) was submitted. If You
|
|
||||||
institute patent litigation against any entity (including a
|
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
||||||
or a Contribution incorporated within the Work constitutes direct
|
|
||||||
or contributory patent infringement, then any patent licenses
|
|
||||||
granted to You under this License for that Work shall terminate
|
|
||||||
as of the date such litigation is filed.
|
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the
|
|
||||||
Work or Derivative Works thereof in any medium, with or without
|
|
||||||
modifications, and in Source or Object form, provided that You
|
|
||||||
meet the following conditions:
|
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
|
||||||
Derivative Works a copy of this License; and
|
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices
|
|
||||||
stating that You changed the files; and
|
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
|
||||||
that You distribute, all copyright, patent, trademark, and
|
|
||||||
attribution notices from the Source form of the Work,
|
|
||||||
excluding those notices that do not pertain to any part of
|
|
||||||
the Derivative Works; and
|
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
|
||||||
distribution, then any Derivative Works that You distribute must
|
|
||||||
include a readable copy of the attribution notices contained
|
|
||||||
within such NOTICE file, excluding those notices that do not
|
|
||||||
pertain to any part of the Derivative Works, in at least one
|
|
||||||
of the following places: within a NOTICE text file distributed
|
|
||||||
as part of the Derivative Works; within the Source form or
|
|
||||||
documentation, if provided along with the Derivative Works; or,
|
|
||||||
within a display generated by the Derivative Works, if and
|
|
||||||
wherever such third-party notices normally appear. The contents
|
|
||||||
of the NOTICE file are for informational purposes only and
|
|
||||||
do not modify the License. You may add Your own attribution
|
|
||||||
notices within Derivative Works that You distribute, alongside
|
|
||||||
or as an addendum to the NOTICE text from the Work, provided
|
|
||||||
that such additional attribution notices cannot be construed
|
|
||||||
as modifying the License.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
|
||||||
may provide additional or different license terms and conditions
|
|
||||||
for use, reproduction, or distribution of Your modifications, or
|
|
||||||
for any such Derivative Works as a whole, provided Your use,
|
|
||||||
reproduction, and distribution of the Work otherwise complies with
|
|
||||||
the conditions stated in this License.
|
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
||||||
any Contribution intentionally submitted for inclusion in the Work
|
|
||||||
by You to the Licensor shall be under the terms and conditions of
|
|
||||||
this License, without any additional terms or conditions.
|
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify
|
|
||||||
the terms of any separate license agreement you may have executed
|
|
||||||
with Licensor regarding such Contributions.
|
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
|
||||||
names, trademarks, service marks, or product names of the Licensor,
|
|
||||||
except as required for reasonable and customary use in describing the
|
|
||||||
origin of the Work and reproducing the content of the NOTICE file.
|
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
||||||
agreed to in writing, Licensor provides the Work (and each
|
|
||||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
||||||
implied, including, without limitation, any warranties or conditions
|
|
||||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
||||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
||||||
appropriateness of using or redistributing the Work and assume any
|
|
||||||
risks associated with Your exercise of permissions under this License.
|
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory,
|
|
||||||
whether in tort (including negligence), contract, or otherwise,
|
|
||||||
unless required by applicable law (such as deliberate and grossly
|
|
||||||
negligent acts) or agreed to in writing, shall any Contributor be
|
|
||||||
liable to You for damages, including any direct, indirect, special,
|
|
||||||
incidental, or consequential damages of any character arising as a
|
|
||||||
result of this License or out of the use or inability to use the
|
|
||||||
Work (including but not limited to damages for loss of goodwill,
|
|
||||||
work stoppage, computer failure or malfunction, or any and all
|
|
||||||
other commercial damages or losses), even if such Contributor
|
|
||||||
has been advised of the possibility of such damages.
|
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing
|
|
||||||
the Work or Derivative Works thereof, You may choose to offer,
|
|
||||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
||||||
or other liability obligations and/or rights consistent with this
|
|
||||||
License. However, in accepting such obligations, You may act only
|
|
||||||
on Your own behalf and on Your sole responsibility, not on behalf
|
|
||||||
of any other Contributor, and only if You agree to indemnify,
|
|
||||||
defend, and hold each Contributor harmless for any liability
|
|
||||||
incurred by, or claims asserted against, such Contributor by reason
|
|
||||||
of your accepting any such warranty or additional liability.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
Copyright The containerd Authors
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
-172
@@ -1,172 +0,0 @@
|
|||||||
/*
|
|
||||||
Copyright The containerd Authors.
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package fs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
var bufferPool = &sync.Pool{
|
|
||||||
New: func() interface{} {
|
|
||||||
buffer := make([]byte, 32*1024)
|
|
||||||
return &buffer
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// XAttrErrorHandlers transform a non-nil xattr error.
|
|
||||||
// Return nil to ignore an error.
|
|
||||||
// xattrKey can be empty for listxattr operation.
|
|
||||||
type XAttrErrorHandler func(dst, src, xattrKey string, err error) error
|
|
||||||
|
|
||||||
type copyDirOpts struct {
|
|
||||||
xeh XAttrErrorHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
type CopyDirOpt func(*copyDirOpts) error
|
|
||||||
|
|
||||||
// WithXAttrErrorHandler allows specifying XAttrErrorHandler
|
|
||||||
// If nil XAttrErrorHandler is specified (default), CopyDir stops
|
|
||||||
// on a non-nil xattr error.
|
|
||||||
func WithXAttrErrorHandler(xeh XAttrErrorHandler) CopyDirOpt {
|
|
||||||
return func(o *copyDirOpts) error {
|
|
||||||
o.xeh = xeh
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithAllowXAttrErrors allows ignoring xattr errors.
|
|
||||||
func WithAllowXAttrErrors() CopyDirOpt {
|
|
||||||
xeh := func(dst, src, xattrKey string, err error) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return WithXAttrErrorHandler(xeh)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CopyDir copies the directory from src to dst.
|
|
||||||
// Most efficient copy of files is attempted.
|
|
||||||
func CopyDir(dst, src string, opts ...CopyDirOpt) error {
|
|
||||||
var o copyDirOpts
|
|
||||||
for _, opt := range opts {
|
|
||||||
if err := opt(&o); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
inodes := map[uint64]string{}
|
|
||||||
return copyDirectory(dst, src, inodes, &o)
|
|
||||||
}
|
|
||||||
|
|
||||||
func copyDirectory(dst, src string, inodes map[uint64]string, o *copyDirOpts) error {
|
|
||||||
stat, err := os.Stat(src)
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to stat %s", src)
|
|
||||||
}
|
|
||||||
if !stat.IsDir() {
|
|
||||||
return errors.Errorf("source is not directory")
|
|
||||||
}
|
|
||||||
|
|
||||||
if st, err := os.Stat(dst); err != nil {
|
|
||||||
if err := os.Mkdir(dst, stat.Mode()); err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to mkdir %s", dst)
|
|
||||||
}
|
|
||||||
} else if !st.IsDir() {
|
|
||||||
return errors.Errorf("cannot copy to non-directory: %s", dst)
|
|
||||||
} else {
|
|
||||||
if err := os.Chmod(dst, stat.Mode()); err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to chmod on %s", dst)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fis, err := ioutil.ReadDir(src)
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to read %s", src)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := copyFileInfo(stat, dst); err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to copy file info for %s", dst)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, fi := range fis {
|
|
||||||
source := filepath.Join(src, fi.Name())
|
|
||||||
target := filepath.Join(dst, fi.Name())
|
|
||||||
|
|
||||||
switch {
|
|
||||||
case fi.IsDir():
|
|
||||||
if err := copyDirectory(target, source, inodes, o); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
case (fi.Mode() & os.ModeType) == 0:
|
|
||||||
link, err := getLinkSource(target, fi, inodes)
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrap(err, "failed to get hardlink")
|
|
||||||
}
|
|
||||||
if link != "" {
|
|
||||||
if err := os.Link(link, target); err != nil {
|
|
||||||
return errors.Wrap(err, "failed to create hard link")
|
|
||||||
}
|
|
||||||
} else if err := CopyFile(target, source); err != nil {
|
|
||||||
return errors.Wrap(err, "failed to copy files")
|
|
||||||
}
|
|
||||||
case (fi.Mode() & os.ModeSymlink) == os.ModeSymlink:
|
|
||||||
link, err := os.Readlink(source)
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to read link: %s", source)
|
|
||||||
}
|
|
||||||
if err := os.Symlink(link, target); err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to create symlink: %s", target)
|
|
||||||
}
|
|
||||||
case (fi.Mode() & os.ModeDevice) == os.ModeDevice:
|
|
||||||
if err := copyDevice(target, fi); err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to create device")
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
// TODO: Support pipes and sockets
|
|
||||||
return errors.Wrapf(err, "unsupported mode %s", fi.Mode())
|
|
||||||
}
|
|
||||||
if err := copyFileInfo(fi, target); err != nil {
|
|
||||||
return errors.Wrap(err, "failed to copy file info")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := copyXAttrs(target, source, o.xeh); err != nil {
|
|
||||||
return errors.Wrap(err, "failed to copy xattrs")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CopyFile copies the source file to the target.
|
|
||||||
// The most efficient means of copying is used for the platform.
|
|
||||||
func CopyFile(target, source string) error {
|
|
||||||
src, err := os.Open(source)
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to open source %s", source)
|
|
||||||
}
|
|
||||||
defer src.Close()
|
|
||||||
tgt, err := os.Create(target)
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to open target %s", target)
|
|
||||||
}
|
|
||||||
defer tgt.Close()
|
|
||||||
|
|
||||||
return copyFileContent(tgt, src)
|
|
||||||
}
|
|
||||||
-144
@@ -1,144 +0,0 @@
|
|||||||
/*
|
|
||||||
Copyright The containerd Authors.
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package fs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"syscall"
|
|
||||||
|
|
||||||
"github.com/containerd/continuity/sysx"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"golang.org/x/sys/unix"
|
|
||||||
)
|
|
||||||
|
|
||||||
func copyFileInfo(fi os.FileInfo, name string) error {
|
|
||||||
st := fi.Sys().(*syscall.Stat_t)
|
|
||||||
if err := os.Lchown(name, int(st.Uid), int(st.Gid)); err != nil {
|
|
||||||
if os.IsPermission(err) {
|
|
||||||
// Normally if uid/gid are the same this would be a no-op, but some
|
|
||||||
// filesystems may still return EPERM... for instance NFS does this.
|
|
||||||
// In such a case, this is not an error.
|
|
||||||
if dstStat, err2 := os.Lstat(name); err2 == nil {
|
|
||||||
st2 := dstStat.Sys().(*syscall.Stat_t)
|
|
||||||
if st.Uid == st2.Uid && st.Gid == st2.Gid {
|
|
||||||
err = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to chown %s", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fi.Mode() & os.ModeSymlink) != os.ModeSymlink {
|
|
||||||
if err := os.Chmod(name, fi.Mode()); err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to chmod %s", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
timespec := []unix.Timespec{unix.Timespec(StatAtime(st)), unix.Timespec(StatMtime(st))}
|
|
||||||
if err := unix.UtimesNanoAt(unix.AT_FDCWD, name, timespec, unix.AT_SYMLINK_NOFOLLOW); err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to utime %s", name)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const maxSSizeT = int64(^uint(0) >> 1)
|
|
||||||
|
|
||||||
func copyFileContent(dst, src *os.File) error {
|
|
||||||
st, err := src.Stat()
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrap(err, "unable to stat source")
|
|
||||||
}
|
|
||||||
|
|
||||||
size := st.Size()
|
|
||||||
first := true
|
|
||||||
srcFd := int(src.Fd())
|
|
||||||
dstFd := int(dst.Fd())
|
|
||||||
|
|
||||||
for size > 0 {
|
|
||||||
// Ensure that we are never trying to copy more than SSIZE_MAX at a
|
|
||||||
// time and at the same time avoids overflows when the file is larger
|
|
||||||
// than 4GB on 32-bit systems.
|
|
||||||
var copySize int
|
|
||||||
if size > maxSSizeT {
|
|
||||||
copySize = int(maxSSizeT)
|
|
||||||
} else {
|
|
||||||
copySize = int(size)
|
|
||||||
}
|
|
||||||
n, err := unix.CopyFileRange(srcFd, nil, dstFd, nil, copySize, 0)
|
|
||||||
if err != nil {
|
|
||||||
if (err != unix.ENOSYS && err != unix.EXDEV) || !first {
|
|
||||||
return errors.Wrap(err, "copy file range failed")
|
|
||||||
}
|
|
||||||
|
|
||||||
buf := bufferPool.Get().(*[]byte)
|
|
||||||
_, err = io.CopyBuffer(dst, src, *buf)
|
|
||||||
bufferPool.Put(buf)
|
|
||||||
return errors.Wrap(err, "userspace copy failed")
|
|
||||||
}
|
|
||||||
|
|
||||||
first = false
|
|
||||||
size -= int64(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func copyXAttrs(dst, src string, xeh XAttrErrorHandler) error {
|
|
||||||
xattrKeys, err := sysx.LListxattr(src)
|
|
||||||
if err != nil {
|
|
||||||
e := errors.Wrapf(err, "failed to list xattrs on %s", src)
|
|
||||||
if xeh != nil {
|
|
||||||
e = xeh(dst, src, "", e)
|
|
||||||
}
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
for _, xattr := range xattrKeys {
|
|
||||||
data, err := sysx.LGetxattr(src, xattr)
|
|
||||||
if err != nil {
|
|
||||||
e := errors.Wrapf(err, "failed to get xattr %q on %s", xattr, src)
|
|
||||||
if xeh != nil {
|
|
||||||
if e = xeh(dst, src, xattr, e); e == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
if err := sysx.LSetxattr(dst, xattr, data, 0); err != nil {
|
|
||||||
e := errors.Wrapf(err, "failed to set xattr %q on %s", xattr, dst)
|
|
||||||
if xeh != nil {
|
|
||||||
if e = xeh(dst, src, xattr, e); e == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func copyDevice(dst string, fi os.FileInfo) error {
|
|
||||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
|
||||||
if !ok {
|
|
||||||
return errors.New("unsupported stat type")
|
|
||||||
}
|
|
||||||
return unix.Mknod(dst, uint32(fi.Mode()), int(st.Rdev))
|
|
||||||
}
|
|
||||||
-112
@@ -1,112 +0,0 @@
|
|||||||
// +build solaris darwin freebsd
|
|
||||||
|
|
||||||
/*
|
|
||||||
Copyright The containerd Authors.
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package fs
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"syscall"
|
|
||||||
|
|
||||||
"github.com/containerd/continuity/sysx"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"golang.org/x/sys/unix"
|
|
||||||
)
|
|
||||||
|
|
||||||
func copyFileInfo(fi os.FileInfo, name string) error {
|
|
||||||
st := fi.Sys().(*syscall.Stat_t)
|
|
||||||
if err := os.Lchown(name, int(st.Uid), int(st.Gid)); err != nil {
|
|
||||||
if os.IsPermission(err) {
|
|
||||||
// Normally if uid/gid are the same this would be a no-op, but some
|
|
||||||
// filesystems may still return EPERM... for instance NFS does this.
|
|
||||||
// In such a case, this is not an error.
|
|
||||||
if dstStat, err2 := os.Lstat(name); err2 == nil {
|
|
||||||
st2 := dstStat.Sys().(*syscall.Stat_t)
|
|
||||||
if st.Uid == st2.Uid && st.Gid == st2.Gid {
|
|
||||||
err = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to chown %s", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fi.Mode() & os.ModeSymlink) != os.ModeSymlink {
|
|
||||||
if err := os.Chmod(name, fi.Mode()); err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to chmod %s", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
timespec := []syscall.Timespec{StatAtime(st), StatMtime(st)}
|
|
||||||
if err := syscall.UtimesNano(name, timespec); err != nil {
|
|
||||||
return errors.Wrapf(err, "failed to utime %s", name)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func copyFileContent(dst, src *os.File) error {
|
|
||||||
buf := bufferPool.Get().(*[]byte)
|
|
||||||
_, err := io.CopyBuffer(dst, src, *buf)
|
|
||||||
bufferPool.Put(buf)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func copyXAttrs(dst, src string, xeh XAttrErrorHandler) error {
|
|
||||||
xattrKeys, err := sysx.LListxattr(src)
|
|
||||||
if err != nil {
|
|
||||||
e := errors.Wrapf(err, "failed to list xattrs on %s", src)
|
|
||||||
if xeh != nil {
|
|
||||||
e = xeh(dst, src, "", e)
|
|
||||||
}
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
for _, xattr := range xattrKeys {
|
|
||||||
data, err := sysx.LGetxattr(src, xattr)
|
|
||||||
if err != nil {
|
|
||||||
e := errors.Wrapf(err, "failed to get xattr %q on %s", xattr, src)
|
|
||||||
if xeh != nil {
|
|
||||||
if e = xeh(dst, src, xattr, e); e == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
if err := sysx.LSetxattr(dst, xattr, data, 0); err != nil {
|
|
||||||
e := errors.Wrapf(err, "failed to set xattr %q on %s", xattr, dst)
|
|
||||||
if xeh != nil {
|
|
||||||
if e = xeh(dst, src, xattr, e); e == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func copyDevice(dst string, fi os.FileInfo) error {
|
|
||||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
|
||||||
if !ok {
|
|
||||||
return errors.New("unsupported stat type")
|
|
||||||
}
|
|
||||||
return unix.Mknod(dst, uint32(fi.Mode()), int(st.Rdev))
|
|
||||||
}
|
|
||||||
Loaded 50 of 1561 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user