From a3c4ef36ad971d5c24e99acf0b19405db4f49701 Mon Sep 17 00:00:00 2001 From: "mingang.he" Date: Sat, 26 Jun 2021 14:47:39 +0000 Subject: [PATCH] Refactor for single-command --- Makefile | 18 +- graftcp-local/clientMain.go | 38 -- graftcp-local/contrib/lib/libgraftcp.a | 1 - graftcp-local/graftcp | 1 - graftcp-local/singleMain.go | 55 --- .../github.com/hashicorp/go-syslog/LICENSE | 20 - .../github.com/hashicorp/go-syslog/README.md | 11 - .../github.com/hashicorp/go-syslog/builtin.go | 214 ---------- .../github.com/hashicorp/go-syslog/syslog.go | 27 -- .../github.com/hashicorp/go-syslog/unix.go | 123 ------ .../hashicorp/go-syslog/unsupported.go | 17 - .../github.com/jedisct1/dlog/Gopkg.lock | 25 -- .../github.com/jedisct1/dlog/Gopkg.toml | 7 - .../vendor/github.com/jedisct1/dlog/LICENSE | 25 -- .../vendor/github.com/jedisct1/dlog/README.md | 13 - .../vendor/github.com/jedisct1/dlog/dlog.go | 256 ------------ .../jedisct1/dlog/sysdeps_others.go | 33 -- .../jedisct1/dlog/sysdeps_windows.go | 28 -- .../vendor/github.com/kardianos/osext/LICENSE | 27 -- .../github.com/kardianos/osext/README.md | 16 - .../github.com/kardianos/osext/osext.go | 33 -- .../github.com/kardianos/osext/osext_plan9.go | 20 - .../kardianos/osext/osext_procfs.go | 36 -- .../kardianos/osext/osext_sysctl.go | 126 ------ .../kardianos/osext/osext_windows.go | 34 -- .../github.com/kardianos/service/LICENSE | 20 - .../github.com/kardianos/service/README.md | 14 - .../github.com/kardianos/service/appveyor.yml | 21 - .../github.com/kardianos/service/console.go | 48 --- .../kardianos/service/linux-test-su.sh | 15 - .../github.com/kardianos/service/pre_go1.8.go | 16 - .../github.com/kardianos/service/service.go | 362 ---------------- .../kardianos/service/service_darwin.go | 240 ----------- .../kardianos/service/service_go1.8.go | 15 - .../kardianos/service/service_linux.go | 75 ---- .../service/service_systemd_linux.go | 175 -------- .../kardianos/service/service_sysv_linux.go | 252 ------------ .../kardianos/service/service_unix.go | 88 ---- .../service/service_upstart_linux.go | 226 ---------- .../kardianos/service/service_windows.go | 389 ------------------ graftcp-local/vendor/golang.org/x/net/LICENSE | 27 -- graftcp-local/vendor/golang.org/x/net/PATENTS | 22 - .../vendor/golang.org/x/net/proxy/direct.go | 18 - .../vendor/golang.org/x/net/proxy/per_host.go | 140 ------- .../vendor/golang.org/x/net/proxy/proxy.go | 94 ----- .../vendor/golang.org/x/net/proxy/socks5.go | 210 ---------- {graftcp-local => local}/Makefile | 33 +- .../cmd/graftcp-local}/config.go | 3 +- .../cmd/graftcp-local}/main.go | 23 +- local/cmd/mgraftcp/main.go | 104 +++++ .../contrib/systemd/graftcp-local.service | 0 .../example-graftcp-local.conf | 0 {graftcp-local => local}/exe_path_go19.go | 2 +- {graftcp-local => local}/exe_path_not_go19.go | 2 +- local/go.mod | 9 + local/go.sum | 16 + {graftcp-local => local}/http_proxy.go | 2 +- {graftcp-local => local}/local.go | 38 +- {graftcp-local => local}/proc_mutex_map.go | 2 +- {graftcp-local => local}/proc_sync_map.go | 2 +- {graftcp-local => local}/util.go | 2 +- 61 files changed, 202 insertions(+), 3707 deletions(-) delete mode 100644 graftcp-local/clientMain.go delete mode 120000 graftcp-local/contrib/lib/libgraftcp.a delete mode 120000 graftcp-local/graftcp delete mode 100644 graftcp-local/singleMain.go delete mode 100644 graftcp-local/vendor/github.com/hashicorp/go-syslog/LICENSE delete mode 100644 graftcp-local/vendor/github.com/hashicorp/go-syslog/README.md delete mode 100644 graftcp-local/vendor/github.com/hashicorp/go-syslog/builtin.go delete mode 100644 graftcp-local/vendor/github.com/hashicorp/go-syslog/syslog.go delete mode 100644 graftcp-local/vendor/github.com/hashicorp/go-syslog/unix.go delete mode 100644 graftcp-local/vendor/github.com/hashicorp/go-syslog/unsupported.go delete mode 100644 graftcp-local/vendor/github.com/jedisct1/dlog/Gopkg.lock delete mode 100644 graftcp-local/vendor/github.com/jedisct1/dlog/Gopkg.toml delete mode 100644 graftcp-local/vendor/github.com/jedisct1/dlog/LICENSE delete mode 100644 graftcp-local/vendor/github.com/jedisct1/dlog/README.md delete mode 100644 graftcp-local/vendor/github.com/jedisct1/dlog/dlog.go delete mode 100644 graftcp-local/vendor/github.com/jedisct1/dlog/sysdeps_others.go delete mode 100644 graftcp-local/vendor/github.com/jedisct1/dlog/sysdeps_windows.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/osext/LICENSE delete mode 100644 graftcp-local/vendor/github.com/kardianos/osext/README.md delete mode 100644 graftcp-local/vendor/github.com/kardianos/osext/osext.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/osext/osext_plan9.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/osext/osext_procfs.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/osext/osext_sysctl.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/osext/osext_windows.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/LICENSE delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/README.md delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/appveyor.yml delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/console.go delete mode 100755 graftcp-local/vendor/github.com/kardianos/service/linux-test-su.sh delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/pre_go1.8.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/service.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/service_darwin.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/service_go1.8.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/service_linux.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/service_systemd_linux.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/service_sysv_linux.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/service_unix.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/service_upstart_linux.go delete mode 100644 graftcp-local/vendor/github.com/kardianos/service/service_windows.go delete mode 100644 graftcp-local/vendor/golang.org/x/net/LICENSE delete mode 100644 graftcp-local/vendor/golang.org/x/net/PATENTS delete mode 100644 graftcp-local/vendor/golang.org/x/net/proxy/direct.go delete mode 100644 graftcp-local/vendor/golang.org/x/net/proxy/per_host.go delete mode 100644 graftcp-local/vendor/golang.org/x/net/proxy/proxy.go delete mode 100644 graftcp-local/vendor/golang.org/x/net/proxy/socks5.go rename {graftcp-local => local}/Makefile (61%) rename {graftcp-local => local/cmd/graftcp-local}/config.go (98%) rename {graftcp-local => local/cmd/graftcp-local}/main.go (87%) create mode 100644 local/cmd/mgraftcp/main.go rename {graftcp-local => local}/contrib/systemd/graftcp-local.service (100%) rename {graftcp-local => local}/example-graftcp-local.conf (100%) rename {graftcp-local => local}/exe_path_go19.go (93%) rename {graftcp-local => local}/exe_path_not_go19.go (92%) create mode 100644 local/go.mod create mode 100644 local/go.sum rename {graftcp-local => local}/http_proxy.go (99%) rename {graftcp-local => local}/local.go (87%) rename {graftcp-local => local}/proc_mutex_map.go (98%) rename {graftcp-local => local}/proc_sync_map.go (98%) rename {graftcp-local => local}/util.go (99%) diff --git a/Makefile b/Makefile index d2dbb83..26755b8 100644 --- a/Makefile +++ b/Makefile @@ -42,7 +42,7 @@ CFLAGS += -DVERSION=\"$(VERSION)\" SRC := $(wildcard *.c) -GRAFTCP_LOCAL_BIN = graftcp-local/graftcp-local +GRAFTCP_LOCAL_BIN = local/cmd/graftcp-local/graftcp-local local/cmd/mgraftcp/mgraftcp TARGET = graftcp $(GRAFTCP_LOCAL_BIN) all:: $(TARGET) @@ -58,15 +58,15 @@ libgraftcp.a: graftcp.o util.o string-set.o $(CC) $(CFLAGS) -c -o $@ $< $(GRAFTCP_LOCAL_BIN):: - $(MAKE) -C graftcp-local VERSION=$(VERSION) + $(MAKE) -C local VERSION=$(VERSION) install:: graftcp $(GRAFTCP_LOCAL_BIN) $(INSTALL) $< $(DESTDIR)$(BINDIR)/$< - $(MAKE) -C graftcp-local $@ + $(MAKE) -C local $@ uninstall:: -rm -f $(DESTDIR)$(BINDIR)/graftcp - $(MAKE) -C graftcp-local $@ + $(MAKE) -C local $@ install_graftcp:: graftcp $(INSTALL) $< $(DESTDIR)$(BINDIR)/$< @@ -75,16 +75,16 @@ uninstall_graftcp:: -rm -f $(DESTDIR)$(BINDIR)/graftcp install_systemd:: - $(MAKE) -C graftcp-local install_systemd + $(MAKE) -C local install_systemd uninstall_systemd:: - $(MAKE) -C graftcp-local uninstall_systemd + $(MAKE) -C local uninstall_systemd install_graftcp_local:: - $(MAKE) -C graftcp-local install + $(MAKE) -C local install uninstall_graftcp_local:: - $(MAKE) -C graftcp-local uninstall + $(MAKE) -C local uninstall sinclude $(SRC:.c=.d) @@ -96,4 +96,4 @@ sinclude $(SRC:.c=.d) clean:: -rm -f *.o graftcp *.d - $(MAKE) -C graftcp-local $@ + $(MAKE) -C local $@ diff --git a/graftcp-local/clientMain.go b/graftcp-local/clientMain.go deleted file mode 100644 index 9774709..0000000 --- a/graftcp-local/clientMain.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -// #cgo LDFLAGS: -L./contrib/lib -lgraftcp -// -// #include -// static void* alloc_string_slice(int len){ -// return malloc(sizeof(char*)*len); -// } -// -// int client_main(int argc, char *argv[]); -import "C" - -import ( - "unsafe" - - log "github.com/jedisct1/dlog" -) - -const ( - maxArgsLen = 0xfff -) - -func client_main(args []string) int { - argc := C.int(len(args)) - - log.Debugf("Got %v args: %v\n", argc, args) - - argv := (*[maxArgsLen]*C.char)(C.alloc_string_slice(argc)) - defer C.free(unsafe.Pointer(argv)) - - for i, arg := range args { - argv[i] = C.CString(arg) - defer C.free(unsafe.Pointer(argv[i])) - } - - returnValue := C.client_main(argc, (**C.char)(unsafe.Pointer(argv))) - return int(returnValue) -} diff --git a/graftcp-local/contrib/lib/libgraftcp.a b/graftcp-local/contrib/lib/libgraftcp.a deleted file mode 120000 index 272139e..0000000 --- a/graftcp-local/contrib/lib/libgraftcp.a +++ /dev/null @@ -1 +0,0 @@ -../../../libgraftcp.a \ No newline at end of file diff --git a/graftcp-local/graftcp b/graftcp-local/graftcp deleted file mode 120000 index d423896..0000000 --- a/graftcp-local/graftcp +++ /dev/null @@ -1 +0,0 @@ -graftcp-local \ No newline at end of file diff --git a/graftcp-local/singleMain.go b/graftcp-local/singleMain.go deleted file mode 100644 index c2e03ae..0000000 --- a/graftcp-local/singleMain.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "os" - "path/filepath" - "strings" - "time" - - log "github.com/jedisct1/dlog" -) - -func constructArgs(args []string) ([]string, []string) { - server := make([]string, 0, len(args)) - client := make([]string, 0, len(args)) - - isCommand := false - for _, arg := range args { - if isCommand { - client = append(client, arg) - } else { - if strings.HasPrefix(arg, "--server") { - server = append(server, strings.TrimPrefix(arg, "--server")) - } else if strings.HasPrefix(arg, "--client") { - client = append(client, strings.TrimPrefix(arg, "--client")) - } else { - isCommand = true - client = append(client, arg) - } - } - } - - return server, client -} - -func main() { - cmdName := filepath.Base(os.Args[0]) - - if cmdName == "graftcp-local" { - local_main(os.Args) - } else { - // todo: we need special handle on args like '--help' which trigger os.Exit - // todo: randomly set and detect port number if no one specified - serverArgs, clientArgs := constructArgs(os.Args[1:]) - serverArgs = append(os.Args[:1], serverArgs...) - clientArgs = append(os.Args[:1], clientArgs...) - log.Infof("server args: %v", serverArgs) // todo: we need to suppress or redirect logging - log.Infof("client args: %v", clientArgs) - - go local_main(serverArgs) - // todo: we may use a channle to notify the graftcp-local is ready to accept request - time.Sleep(1 * time.Second) - - os.Exit(client_main(clientArgs)) - } -} diff --git a/graftcp-local/vendor/github.com/hashicorp/go-syslog/LICENSE b/graftcp-local/vendor/github.com/hashicorp/go-syslog/LICENSE deleted file mode 100644 index a5df10e..0000000 --- a/graftcp-local/vendor/github.com/hashicorp/go-syslog/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Armon Dadgar - -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. diff --git a/graftcp-local/vendor/github.com/hashicorp/go-syslog/README.md b/graftcp-local/vendor/github.com/hashicorp/go-syslog/README.md deleted file mode 100644 index bbfae8f..0000000 --- a/graftcp-local/vendor/github.com/hashicorp/go-syslog/README.md +++ /dev/null @@ -1,11 +0,0 @@ -go-syslog -========= - -This repository provides a very simple `gsyslog` package. The point of this -package is to allow safe importing of syslog without introducing cross-compilation -issues. The stdlib `log/syslog` cannot be imported on Windows systems, and without -conditional compilation this adds complications. - -Instead, `gsyslog` provides a very simple wrapper around `log/syslog` but returns -a runtime error if attempting to initialize on a non Linux or OSX system. - diff --git a/graftcp-local/vendor/github.com/hashicorp/go-syslog/builtin.go b/graftcp-local/vendor/github.com/hashicorp/go-syslog/builtin.go deleted file mode 100644 index 72bdd61..0000000 --- a/graftcp-local/vendor/github.com/hashicorp/go-syslog/builtin.go +++ /dev/null @@ -1,214 +0,0 @@ -// This file is taken from the log/syslog in the standard lib. -// However, there is a bug with overwhelming syslog that causes writes -// to block indefinitely. This is fixed by adding a write deadline. -// -// +build !windows,!nacl,!plan9 - -package gsyslog - -import ( - "errors" - "fmt" - "log/syslog" - "net" - "os" - "strings" - "sync" - "time" -) - -const severityMask = 0x07 -const facilityMask = 0xf8 -const localDeadline = 20 * time.Millisecond -const remoteDeadline = 50 * time.Millisecond - -// A builtinWriter is a connection to a syslog server. -type builtinWriter struct { - priority syslog.Priority - tag string - hostname string - network string - raddr string - - mu sync.Mutex // guards conn - conn serverConn -} - -// This interface and the separate syslog_unix.go file exist for -// Solaris support as implemented by gccgo. On Solaris you can not -// simply open a TCP connection to the syslog daemon. The gccgo -// sources have a syslog_solaris.go file that implements unixSyslog to -// return a type that satisfies this interface and simply calls the C -// library syslog function. -type serverConn interface { - writeString(p syslog.Priority, hostname, tag, s, nl string) error - close() error -} - -type netConn struct { - local bool - conn net.Conn -} - -// New establishes a new connection to the system log daemon. Each -// write to the returned writer sends a log message with the given -// priority and prefix. -func newBuiltin(priority syslog.Priority, tag string) (w *builtinWriter, err error) { - return dialBuiltin("", "", priority, tag) -} - -// Dial establishes a connection to a log daemon by connecting to -// address raddr on the specified network. Each write to the returned -// writer sends a log message with the given facility, severity and -// tag. -// If network is empty, Dial will connect to the local syslog server. -func dialBuiltin(network, raddr string, priority syslog.Priority, tag string) (*builtinWriter, error) { - if priority < 0 || priority > syslog.LOG_LOCAL7|syslog.LOG_DEBUG { - return nil, errors.New("log/syslog: invalid priority") - } - - if tag == "" { - tag = os.Args[0] - } - hostname, _ := os.Hostname() - - w := &builtinWriter{ - priority: priority, - tag: tag, - hostname: hostname, - network: network, - raddr: raddr, - } - - w.mu.Lock() - defer w.mu.Unlock() - - err := w.connect() - if err != nil { - return nil, err - } - return w, err -} - -// connect makes a connection to the syslog server. -// It must be called with w.mu held. -func (w *builtinWriter) connect() (err error) { - if w.conn != nil { - // ignore err from close, it makes sense to continue anyway - w.conn.close() - w.conn = nil - } - - if w.network == "" { - w.conn, err = unixSyslog() - if w.hostname == "" { - w.hostname = "localhost" - } - } else { - var c net.Conn - c, err = net.DialTimeout(w.network, w.raddr, remoteDeadline) - if err == nil { - w.conn = &netConn{conn: c} - if w.hostname == "" { - w.hostname = c.LocalAddr().String() - } - } - } - return -} - -// Write sends a log message to the syslog daemon. -func (w *builtinWriter) Write(b []byte) (int, error) { - return w.writeAndRetry(w.priority, string(b)) -} - -// Close closes a connection to the syslog daemon. -func (w *builtinWriter) Close() error { - w.mu.Lock() - defer w.mu.Unlock() - - if w.conn != nil { - err := w.conn.close() - w.conn = nil - return err - } - return nil -} - -func (w *builtinWriter) writeAndRetry(p syslog.Priority, s string) (int, error) { - pr := (w.priority & facilityMask) | (p & severityMask) - - w.mu.Lock() - defer w.mu.Unlock() - - if w.conn != nil { - if n, err := w.write(pr, s); err == nil { - return n, err - } - } - if err := w.connect(); err != nil { - return 0, err - } - return w.write(pr, s) -} - -// write generates and writes a syslog formatted string. The -// format is as follows: TIMESTAMP HOSTNAME TAG[PID]: MSG -func (w *builtinWriter) write(p syslog.Priority, msg string) (int, error) { - // ensure it ends in a \n - nl := "" - if !strings.HasSuffix(msg, "\n") { - nl = "\n" - } - - err := w.conn.writeString(p, w.hostname, w.tag, msg, nl) - if err != nil { - return 0, err - } - // Note: return the length of the input, not the number of - // bytes printed by Fprintf, because this must behave like - // an io.Writer. - return len(msg), nil -} - -func (n *netConn) writeString(p syslog.Priority, hostname, tag, msg, nl string) error { - if n.local { - // Compared to the network form below, the changes are: - // 1. Use time.Stamp instead of time.RFC3339. - // 2. Drop the hostname field from the Fprintf. - timestamp := time.Now().Format(time.Stamp) - n.conn.SetWriteDeadline(time.Now().Add(localDeadline)) - _, err := fmt.Fprintf(n.conn, "<%d>%s %s[%d]: %s%s", - p, timestamp, - tag, os.Getpid(), msg, nl) - return err - } - timestamp := time.Now().Format(time.RFC3339) - n.conn.SetWriteDeadline(time.Now().Add(remoteDeadline)) - _, err := fmt.Fprintf(n.conn, "<%d>%s %s %s[%d]: %s%s", - p, timestamp, hostname, - tag, os.Getpid(), msg, nl) - return err -} - -func (n *netConn) close() error { - return n.conn.Close() -} - -// unixSyslog opens a connection to the syslog daemon running on the -// local machine using a Unix domain socket. -func unixSyslog() (conn serverConn, err error) { - logTypes := []string{"unixgram", "unix"} - logPaths := []string{"/dev/log", "/var/run/syslog", "/var/run/log"} - for _, network := range logTypes { - for _, path := range logPaths { - conn, err := net.DialTimeout(network, path, localDeadline) - if err != nil { - continue - } else { - return &netConn{conn: conn, local: true}, nil - } - } - } - return nil, errors.New("Unix syslog delivery error") -} diff --git a/graftcp-local/vendor/github.com/hashicorp/go-syslog/syslog.go b/graftcp-local/vendor/github.com/hashicorp/go-syslog/syslog.go deleted file mode 100644 index 3f5a6f3..0000000 --- a/graftcp-local/vendor/github.com/hashicorp/go-syslog/syslog.go +++ /dev/null @@ -1,27 +0,0 @@ -package gsyslog - -// Priority maps to the syslog priority levels -type Priority int - -const ( - LOG_EMERG Priority = iota - LOG_ALERT - LOG_CRIT - LOG_ERR - LOG_WARNING - LOG_NOTICE - LOG_INFO - LOG_DEBUG -) - -// Syslogger interface is used to write log messages to syslog -type Syslogger interface { - // WriteLevel is used to write a message at a given level - WriteLevel(Priority, []byte) error - - // Write is used to write a message at the default level - Write([]byte) (int, error) - - // Close is used to close the connection to the logger - Close() error -} diff --git a/graftcp-local/vendor/github.com/hashicorp/go-syslog/unix.go b/graftcp-local/vendor/github.com/hashicorp/go-syslog/unix.go deleted file mode 100644 index 70b7180..0000000 --- a/graftcp-local/vendor/github.com/hashicorp/go-syslog/unix.go +++ /dev/null @@ -1,123 +0,0 @@ -// +build linux darwin dragonfly freebsd netbsd openbsd solaris - -package gsyslog - -import ( - "fmt" - "log/syslog" - "strings" -) - -// builtinLogger wraps the Golang implementation of a -// syslog.Writer to provide the Syslogger interface -type builtinLogger struct { - *builtinWriter -} - -// NewLogger is used to construct a new Syslogger -func NewLogger(p Priority, facility, tag string) (Syslogger, error) { - fPriority, err := facilityPriority(facility) - if err != nil { - return nil, err - } - priority := syslog.Priority(p) | fPriority - l, err := newBuiltin(priority, tag) - if err != nil { - return nil, err - } - return &builtinLogger{l}, nil -} - -// DialLogger is used to construct a new Syslogger that establishes connection to remote syslog server -func DialLogger(network, raddr string, p Priority, facility, tag string) (Syslogger, error) { - fPriority, err := facilityPriority(facility) - if err != nil { - return nil, err - } - - priority := syslog.Priority(p) | fPriority - - l, err := dialBuiltin(network, raddr, priority, tag) - if err != nil { - return nil, err - } - - return &builtinLogger{l}, nil -} - -// WriteLevel writes out a message at the given priority -func (b *builtinLogger) WriteLevel(p Priority, buf []byte) error { - var err error - m := string(buf) - switch p { - case LOG_EMERG: - _, err = b.writeAndRetry(syslog.LOG_EMERG, m) - case LOG_ALERT: - _, err = b.writeAndRetry(syslog.LOG_ALERT, m) - case LOG_CRIT: - _, err = b.writeAndRetry(syslog.LOG_CRIT, m) - case LOG_ERR: - _, err = b.writeAndRetry(syslog.LOG_ERR, m) - case LOG_WARNING: - _, err = b.writeAndRetry(syslog.LOG_WARNING, m) - case LOG_NOTICE: - _, err = b.writeAndRetry(syslog.LOG_NOTICE, m) - case LOG_INFO: - _, err = b.writeAndRetry(syslog.LOG_INFO, m) - case LOG_DEBUG: - _, err = b.writeAndRetry(syslog.LOG_DEBUG, m) - default: - err = fmt.Errorf("Unknown priority: %v", p) - } - return err -} - -// facilityPriority converts a facility string into -// an appropriate priority level or returns an error -func facilityPriority(facility string) (syslog.Priority, error) { - facility = strings.ToUpper(facility) - switch facility { - case "KERN": - return syslog.LOG_KERN, nil - case "USER": - return syslog.LOG_USER, nil - case "MAIL": - return syslog.LOG_MAIL, nil - case "DAEMON": - return syslog.LOG_DAEMON, nil - case "AUTH": - return syslog.LOG_AUTH, nil - case "SYSLOG": - return syslog.LOG_SYSLOG, nil - case "LPR": - return syslog.LOG_LPR, nil - case "NEWS": - return syslog.LOG_NEWS, nil - case "UUCP": - return syslog.LOG_UUCP, nil - case "CRON": - return syslog.LOG_CRON, nil - case "AUTHPRIV": - return syslog.LOG_AUTHPRIV, nil - case "FTP": - return syslog.LOG_FTP, nil - case "LOCAL0": - return syslog.LOG_LOCAL0, nil - case "LOCAL1": - return syslog.LOG_LOCAL1, nil - case "LOCAL2": - return syslog.LOG_LOCAL2, nil - case "LOCAL3": - return syslog.LOG_LOCAL3, nil - case "LOCAL4": - return syslog.LOG_LOCAL4, nil - case "LOCAL5": - return syslog.LOG_LOCAL5, nil - case "LOCAL6": - return syslog.LOG_LOCAL6, nil - case "LOCAL7": - return syslog.LOG_LOCAL7, nil - default: - return 0, fmt.Errorf("invalid syslog facility: %s", facility) - } -} diff --git a/graftcp-local/vendor/github.com/hashicorp/go-syslog/unsupported.go b/graftcp-local/vendor/github.com/hashicorp/go-syslog/unsupported.go deleted file mode 100644 index b8ca3a5..0000000 --- a/graftcp-local/vendor/github.com/hashicorp/go-syslog/unsupported.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build windows plan9 nacl - -package gsyslog - -import ( - "fmt" -) - -// NewLogger is used to construct a new Syslogger -func NewLogger(p Priority, facility, tag string) (Syslogger, error) { - return nil, fmt.Errorf("Platform does not support syslog") -} - -// DialLogger is used to construct a new Syslogger that establishes connection to remote syslog server -func DialLogger(network, raddr string, p Priority, facility, tag string) (Syslogger, error) { - return nil, fmt.Errorf("Platform does not support syslog") -} diff --git a/graftcp-local/vendor/github.com/jedisct1/dlog/Gopkg.lock b/graftcp-local/vendor/github.com/jedisct1/dlog/Gopkg.lock deleted file mode 100644 index d476e84..0000000 --- a/graftcp-local/vendor/github.com/jedisct1/dlog/Gopkg.lock +++ /dev/null @@ -1,25 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-syslog" - packages = ["."] - revision = "326bf4a7f709d263f964a6a96558676b103f3534" - -[[projects]] - branch = "master" - name = "golang.org/x/sys" - packages = [ - "windows", - "windows/registry", - "windows/svc/eventlog" - ] - revision = "7dfd1290c7917b7ba22824b9d24954ab3002fe24" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "328c0e201a8f9b84770fc7b0efb002f50e64da384499776e57cc1edb38b26a51" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/graftcp-local/vendor/github.com/jedisct1/dlog/Gopkg.toml b/graftcp-local/vendor/github.com/jedisct1/dlog/Gopkg.toml deleted file mode 100644 index 3b1e495..0000000 --- a/graftcp-local/vendor/github.com/jedisct1/dlog/Gopkg.toml +++ /dev/null @@ -1,7 +0,0 @@ -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-syslog" - -[[constraint]] - branch = "master" - name = "golang.org/x/sys" diff --git a/graftcp-local/vendor/github.com/jedisct1/dlog/LICENSE b/graftcp-local/vendor/github.com/jedisct1/dlog/LICENSE deleted file mode 100644 index 46a815a..0000000 --- a/graftcp-local/vendor/github.com/jedisct1/dlog/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -BSD 2-Clause License - -Copyright (c) 2018, Frank Denis -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. - -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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. diff --git a/graftcp-local/vendor/github.com/jedisct1/dlog/README.md b/graftcp-local/vendor/github.com/jedisct1/dlog/README.md deleted file mode 100644 index 46574fa..0000000 --- a/graftcp-local/vendor/github.com/jedisct1/dlog/README.md +++ /dev/null @@ -1,13 +0,0 @@ -[![](https://godoc.org/github.com/jedisct1/dlog?status.svg)](https://godoc.org/github.com/jedisct1/dlog) - -# dlog - -Go's standard logger is fairly limited. As result, kazilion alternatives loggers have been written. - -All of these are wonderful. They can make your logs look colorful and pretty, buffer things in complicated ways, format data for ElasticSearch, and more. - -Cool, but all I wanted is something super dumb, that just exposes `log.Info()`, `log.Error()` and a couple other standard levels. - -I don't need a super flexible kitchen sink. Just something super basic and trivial to use. I just want it to handle different log levels, and be able to write simple logs to `stderr`, to a local file, to `syslog` and to the Windows event log. - -So, here's one more logging library for Go. The dumbest of them all. Enjoy. diff --git a/graftcp-local/vendor/github.com/jedisct1/dlog/dlog.go b/graftcp-local/vendor/github.com/jedisct1/dlog/dlog.go deleted file mode 100644 index 84dcd4a..0000000 --- a/graftcp-local/vendor/github.com/jedisct1/dlog/dlog.go +++ /dev/null @@ -1,256 +0,0 @@ -package dlog - -import ( - "flag" - "fmt" - "os" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" -) - -type Severity int32 - -type globals struct { - sync.Mutex - logLevel Severity - useSyslog *bool - appName string - syslogFacility string - systemLogger *systemLogger - fileName *string - outFd *os.File - lastMessage string - lastOccurrence time.Time - occurrences uint64 -} - -var ( - _globals = globals{ - logLevel: SeverityLast, - appName: "-", - lastMessage: "", - lastOccurrence: time.Now(), - occurrences: 0, - } -) - -const ( - SeverityDebug Severity = iota - SeverityInfo - SeverityNotice - SeverityWarning - SeverityError - SeverityCritical - SeverityFatal - SeverityLast -) - -const ( - floodDelay = 5 * time.Second - floodMinRepeats = 3 -) - -var SeverityName = []string{ - SeverityDebug: "DEBUG", - SeverityInfo: "INFO", - SeverityNotice: "NOTICE", - SeverityWarning: "WARNING", - SeverityError: "ERROR", - SeverityCritical: "CRITICAL", - SeverityFatal: "FATAL", -} - -func Debugf(format string, args ...interface{}) { - logf(SeverityDebug, format, args...) -} - -func Infof(format string, args ...interface{}) { - logf(SeverityInfo, format, args...) -} - -func Noticef(format string, args ...interface{}) { - logf(SeverityNotice, format, args...) -} - -func Warnf(format string, args ...interface{}) { - logf(SeverityWarning, format, args...) -} - -func Errorf(format string, args ...interface{}) { - logf(SeverityError, format, args...) -} - -func Criticalf(format string, args ...interface{}) { - logf(SeverityCritical, format, args...) -} - -func Fatalf(format string, args ...interface{}) { - logf(SeverityFatal, format, args...) -} - -func Debug(message interface{}) { - log(SeverityDebug, message) -} - -func Info(message interface{}) { - log(SeverityInfo, message) -} - -func Notice(message interface{}) { - log(SeverityNotice, message) -} - -func Warn(message interface{}) { - log(SeverityWarning, message) -} - -func Error(message interface{}) { - log(SeverityError, message) -} - -func Critical(message interface{}) { - log(SeverityCritical, message) -} - -func Fatal(message interface{}) { - log(SeverityFatal, message) -} - -func (s *Severity) get() Severity { - return Severity(atomic.LoadInt32((*int32)(s))) -} - -func (s *Severity) set(val Severity) { - atomic.StoreInt32((*int32)(s), int32(val)) -} - -func (s *Severity) String() string { - return strconv.FormatInt(int64(*s), 10) -} - -func (s *Severity) Get() interface{} { - return s.get() -} - -func (s *Severity) Set(strVal string) error { - val, _ := strconv.Atoi(strVal) - s.set(Severity(val)) - return nil -} - -func Init(appName string, logLevel Severity, syslogFacility string) error { - _globals.logLevel.set(logLevel) - - if len(syslogFacility) == 0 { - syslogFacility = "DAEMON" - } - _globals.appName = appName - _globals.syslogFacility = syslogFacility - _globals.useSyslog = flag.Bool("syslog", false, "Send logs to the local system logger (Eventlog on Windows, syslog on Unix)") - _globals.fileName = flag.String("logfile", "", "Write logs to file") - flag.Var(&_globals.logLevel, "loglevel", fmt.Sprintf("Log level (%d-%d)", SeverityDebug, SeverityFatal)) - return nil -} - -func LogLevel() Severity { - _globals.Lock() - logLevel := _globals.logLevel.get() - _globals.Unlock() - return logLevel -} - -func SetLogLevel(logLevel Severity) { - _globals.Lock() - _globals.logLevel.set(logLevel) - _globals.Unlock() -} - -func UseSyslog(value bool) { - _globals.Lock() - _globals.useSyslog = &value - _globals.Unlock() -} - -func UseLogFile(fileName string) { - _globals.Lock() - _globals.fileName = &fileName - _globals.Unlock() -} - -func GetFileDescriptor() (*os.File) { - _globals.Lock() - createFileDescriptor() - _globals.Unlock() - return _globals.outFd -} - -func SetFileDescriptor(fd *os.File) { - _globals.Lock() - _globals.outFd = fd - _globals.Unlock() -} - -func createFileDescriptor() { - if _globals.fileName != nil && len(*_globals.fileName) > 0 && _globals.outFd == nil { - outFd, err := os.OpenFile(*_globals.fileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) - if err == nil { - _globals.outFd = outFd - } - } -} - -func logf(severity Severity, format string, args ...interface{}) { - if severity < _globals.logLevel.get() { - return - } - now := time.Now().Local() - year, month, day := now.Date() - hour, minute, second := now.Clock() - message := fmt.Sprintf(format, args...) - message = strings.TrimSpace(strings.TrimSuffix(message, "\n")) - if len(message) <= 0 { - return - } - _globals.Lock() - defer _globals.Unlock() - if _globals.lastMessage == message { - if time.Since(_globals.lastOccurrence) < floodDelay { - _globals.occurrences++ - if _globals.occurrences > floodMinRepeats { - return - } - } - } else { - _globals.occurrences = 0 - _globals.lastMessage = message - } - _globals.lastOccurrence = now - if *_globals.useSyslog && _globals.systemLogger == nil { - systemLogger, err := newSystemLogger(_globals.appName, _globals.syslogFacility) - if err == nil { - _globals.systemLogger = systemLogger - } - } - createFileDescriptor() - if _globals.systemLogger != nil { - (*_globals.systemLogger).writeString(severity, message) - } else { - line := fmt.Sprintf("[%d-%02d-%02d %02d:%02d:%02d] [%s] %s\n", year, int(month), day, hour, minute, second, SeverityName[severity], message) - if _globals.outFd != nil { - _globals.outFd.WriteString(line) - _globals.outFd.Sync() - } else { - os.Stderr.WriteString(line) - } - } - if severity >= SeverityFatal { - os.Exit(255) - } -} - -func log(severity Severity, args interface{}) { - logf(severity, "%v", args) -} diff --git a/graftcp-local/vendor/github.com/jedisct1/dlog/sysdeps_others.go b/graftcp-local/vendor/github.com/jedisct1/dlog/sysdeps_others.go deleted file mode 100644 index 58ca0f3..0000000 --- a/graftcp-local/vendor/github.com/jedisct1/dlog/sysdeps_others.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build !windows - -package dlog - -import ( - "github.com/hashicorp/go-syslog" -) - -var severityToSyslogPriority = []gsyslog.Priority{ - SeverityDebug: gsyslog.LOG_DEBUG, - SeverityInfo: gsyslog.LOG_INFO, - SeverityNotice: gsyslog.LOG_NOTICE, - SeverityWarning: gsyslog.LOG_WARNING, - SeverityError: gsyslog.LOG_ERR, - SeverityCritical: gsyslog.LOG_CRIT, - SeverityFatal: gsyslog.LOG_ALERT, -} - -type systemLogger struct { - inner *gsyslog.Syslogger -} - -func newSystemLogger(appName string, facility string) (*systemLogger, error) { - eventLogger, err := gsyslog.NewLogger(gsyslog.LOG_INFO, facility, appName) - if err != nil { - return nil, err - } - return &systemLogger{inner: &eventLogger}, nil -} - -func (systemLogger *systemLogger) writeString(severity Severity, message string) { - (*systemLogger.inner).WriteLevel(severityToSyslogPriority[severity], []byte(message)) -} diff --git a/graftcp-local/vendor/github.com/jedisct1/dlog/sysdeps_windows.go b/graftcp-local/vendor/github.com/jedisct1/dlog/sysdeps_windows.go deleted file mode 100644 index 2aa4fbb..0000000 --- a/graftcp-local/vendor/github.com/jedisct1/dlog/sysdeps_windows.go +++ /dev/null @@ -1,28 +0,0 @@ -package dlog - -import "golang.org/x/sys/windows/svc/eventlog" - -type systemLogger struct { - inner *eventlog.Log -} - -func newSystemLogger(appName string, facility string) (*systemLogger, error) { - eventLogger, err := eventlog.Open(appName) - if err != nil { - return nil, err - } - return &systemLogger{inner: eventLogger}, nil -} - -func (systemLogger *systemLogger) writeString(severity Severity, message string) { - switch severity { - case SeverityError: - case SeverityCritical: - case SeverityFatal: - systemLogger.inner.Error(uint32(severity), message) - case SeverityWarning: - systemLogger.inner.Warning(uint32(severity), message) - default: - systemLogger.inner.Info(uint32(severity), message) - } -} diff --git a/graftcp-local/vendor/github.com/kardianos/osext/LICENSE b/graftcp-local/vendor/github.com/kardianos/osext/LICENSE deleted file mode 100644 index 7448756..0000000 --- a/graftcp-local/vendor/github.com/kardianos/osext/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go Authors. 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 Google Inc. 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 THE COPYRIGHT -OWNER OR CONTRIBUTORS 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. diff --git a/graftcp-local/vendor/github.com/kardianos/osext/README.md b/graftcp-local/vendor/github.com/kardianos/osext/README.md deleted file mode 100644 index 61350ba..0000000 --- a/graftcp-local/vendor/github.com/kardianos/osext/README.md +++ /dev/null @@ -1,16 +0,0 @@ -### Extensions to the "os" package. - -## Find the current Executable and ExecutableFolder. - -There is sometimes utility in finding the current executable file -that is running. This can be used for upgrading the current executable -or finding resources located relative to the executable file. Both -working directory and the os.Args[0] value are arbitrary and cannot -be relied on; os.Args[0] can be "faked". - -Multi-platform and supports: - * Linux - * OS X - * Windows - * Plan 9 - * BSDs. diff --git a/graftcp-local/vendor/github.com/kardianos/osext/osext.go b/graftcp-local/vendor/github.com/kardianos/osext/osext.go deleted file mode 100644 index 17f380f..0000000 --- a/graftcp-local/vendor/github.com/kardianos/osext/osext.go +++ /dev/null @@ -1,33 +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. - -// Extensions to the standard "os" package. -package osext // import "github.com/kardianos/osext" - -import "path/filepath" - -var cx, ce = executableClean() - -func executableClean() (string, error) { - p, err := executable() - return filepath.Clean(p), err -} - -// Executable returns an absolute path that can be used to -// re-invoke the current program. -// It may not be valid after the current program exits. -func Executable() (string, error) { - return cx, ce -} - -// Returns same path as Executable, returns just the folder -// path. Excludes the executable name and any trailing slash. -func ExecutableFolder() (string, error) { - p, err := Executable() - if err != nil { - return "", err - } - - return filepath.Dir(p), nil -} diff --git a/graftcp-local/vendor/github.com/kardianos/osext/osext_plan9.go b/graftcp-local/vendor/github.com/kardianos/osext/osext_plan9.go deleted file mode 100644 index 655750c..0000000 --- a/graftcp-local/vendor/github.com/kardianos/osext/osext_plan9.go +++ /dev/null @@ -1,20 +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 osext - -import ( - "os" - "strconv" - "syscall" -) - -func executable() (string, error) { - f, err := os.Open("/proc/" + strconv.Itoa(os.Getpid()) + "/text") - if err != nil { - return "", err - } - defer f.Close() - return syscall.Fd2path(int(f.Fd())) -} diff --git a/graftcp-local/vendor/github.com/kardianos/osext/osext_procfs.go b/graftcp-local/vendor/github.com/kardianos/osext/osext_procfs.go deleted file mode 100644 index d59847e..0000000 --- a/graftcp-local/vendor/github.com/kardianos/osext/osext_procfs.go +++ /dev/null @@ -1,36 +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 linux netbsd solaris dragonfly - -package osext - -import ( - "errors" - "fmt" - "os" - "runtime" - "strings" -) - -func executable() (string, error) { - switch runtime.GOOS { - case "linux": - const deletedTag = " (deleted)" - execpath, err := os.Readlink("/proc/self/exe") - if err != nil { - return execpath, err - } - execpath = strings.TrimSuffix(execpath, deletedTag) - execpath = strings.TrimPrefix(execpath, deletedTag) - return execpath, nil - case "netbsd": - return os.Readlink("/proc/curproc/exe") - case "dragonfly": - return os.Readlink("/proc/curproc/file") - case "solaris": - return os.Readlink(fmt.Sprintf("/proc/%d/path/a.out", os.Getpid())) - } - return "", errors.New("ExecPath not implemented for " + runtime.GOOS) -} diff --git a/graftcp-local/vendor/github.com/kardianos/osext/osext_sysctl.go b/graftcp-local/vendor/github.com/kardianos/osext/osext_sysctl.go deleted file mode 100644 index 66da0bc..0000000 --- a/graftcp-local/vendor/github.com/kardianos/osext/osext_sysctl.go +++ /dev/null @@ -1,126 +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 darwin freebsd openbsd - -package osext - -import ( - "os" - "os/exec" - "path/filepath" - "runtime" - "syscall" - "unsafe" -) - -var initCwd, initCwdErr = os.Getwd() - -func executable() (string, error) { - var mib [4]int32 - switch runtime.GOOS { - case "freebsd": - mib = [4]int32{1 /* CTL_KERN */, 14 /* KERN_PROC */, 12 /* KERN_PROC_PATHNAME */, -1} - case "darwin": - mib = [4]int32{1 /* CTL_KERN */, 38 /* KERN_PROCARGS */, int32(os.Getpid()), -1} - case "openbsd": - mib = [4]int32{1 /* CTL_KERN */, 55 /* KERN_PROC_ARGS */, int32(os.Getpid()), 1 /* KERN_PROC_ARGV */} - } - - n := uintptr(0) - // Get length. - _, _, errNum := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, 0, uintptr(unsafe.Pointer(&n)), 0, 0) - if errNum != 0 { - return "", errNum - } - if n == 0 { // This shouldn't happen. - return "", nil - } - buf := make([]byte, n) - _, _, errNum = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n)), 0, 0) - if errNum != 0 { - return "", errNum - } - if n == 0 { // This shouldn't happen. - return "", nil - } - - var execPath string - switch runtime.GOOS { - case "openbsd": - // buf now contains **argv, with pointers to each of the C-style - // NULL terminated arguments. - var args []string - argv := uintptr(unsafe.Pointer(&buf[0])) - Loop: - for { - argp := *(**[1 << 20]byte)(unsafe.Pointer(argv)) - if argp == nil { - break - } - for i := 0; uintptr(i) < n; i++ { - // we don't want the full arguments list - if string(argp[i]) == " " { - break Loop - } - if argp[i] != 0 { - continue - } - args = append(args, string(argp[:i])) - n -= uintptr(i) - break - } - if n < unsafe.Sizeof(argv) { - break - } - argv += unsafe.Sizeof(argv) - n -= unsafe.Sizeof(argv) - } - execPath = args[0] - // There is no canonical way to get an executable path on - // OpenBSD, so check PATH in case we are called directly - if execPath[0] != '/' && execPath[0] != '.' { - execIsInPath, err := exec.LookPath(execPath) - if err == nil { - execPath = execIsInPath - } - } - default: - for i, v := range buf { - if v == 0 { - buf = buf[:i] - break - } - } - execPath = string(buf) - } - - var err error - // execPath will not be empty due to above checks. - // Try to get the absolute path if the execPath is not rooted. - if execPath[0] != '/' { - execPath, err = getAbs(execPath) - if err != nil { - return execPath, err - } - } - // For darwin KERN_PROCARGS may return the path to a symlink rather than the - // actual executable. - if runtime.GOOS == "darwin" { - if execPath, err = filepath.EvalSymlinks(execPath); err != nil { - return execPath, err - } - } - return execPath, nil -} - -func getAbs(execPath string) (string, error) { - if initCwdErr != nil { - return execPath, initCwdErr - } - // The execPath may begin with a "../" or a "./" so clean it first. - // Join the two paths, trailing and starting slashes undetermined, so use - // the generic Join function. - return filepath.Join(initCwd, filepath.Clean(execPath)), nil -} diff --git a/graftcp-local/vendor/github.com/kardianos/osext/osext_windows.go b/graftcp-local/vendor/github.com/kardianos/osext/osext_windows.go deleted file mode 100644 index 72d282c..0000000 --- a/graftcp-local/vendor/github.com/kardianos/osext/osext_windows.go +++ /dev/null @@ -1,34 +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 osext - -import ( - "syscall" - "unicode/utf16" - "unsafe" -) - -var ( - kernel = syscall.MustLoadDLL("kernel32.dll") - getModuleFileNameProc = kernel.MustFindProc("GetModuleFileNameW") -) - -// GetModuleFileName() with hModule = NULL -func executable() (exePath string, err error) { - return getModuleFileName() -} - -func getModuleFileName() (string, error) { - var n uint32 - b := make([]uint16, syscall.MAX_PATH) - size := uint32(len(b)) - - r0, _, e1 := getModuleFileNameProc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(size)) - n = uint32(r0) - if n == 0 { - return "", e1 - } - return string(utf16.Decode(b[0:n])), nil -} diff --git a/graftcp-local/vendor/github.com/kardianos/service/LICENSE b/graftcp-local/vendor/github.com/kardianos/service/LICENSE deleted file mode 100644 index fce91b4..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2015 Daniel Theophanes - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source - distribution. diff --git a/graftcp-local/vendor/github.com/kardianos/service/README.md b/graftcp-local/vendor/github.com/kardianos/service/README.md deleted file mode 100644 index 2dab8d6..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# service [![GoDoc](https://godoc.org/github.com/kardianos/service?status.svg)](https://godoc.org/github.com/kardianos/service) - -service will install / un-install, start / stop, and run a program as a service (daemon). -Currently supports Windows XP+, Linux/(systemd | Upstart | SysV), and OSX/Launchd. - -Windows controls services by setting up callbacks that is non-trivial. This -is very different then other systems. This package provides the same API -despite the substantial differences. -It also can be used to detect how a program is called, from an interactive -terminal or from a service manager. - -## BUGS - * Dependencies field is not implemented for Linux systems and Launchd. - * OS X when running as a UserService Interactive will not be accurate. diff --git a/graftcp-local/vendor/github.com/kardianos/service/appveyor.yml b/graftcp-local/vendor/github.com/kardianos/service/appveyor.yml deleted file mode 100644 index 92238c3..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/appveyor.yml +++ /dev/null @@ -1,21 +0,0 @@ -version: "{build}" - -platform: - - x86 - - x64 - -clone_folder: c:\gopath\src\github.com\kardianos\service - -environment: - GOPATH: c:\gopath - -install: - - go version - - go env - - go get -v -t ./... - -build_script: - - go install -v ./... - -test_script: - - go test -v -tags su ./... diff --git a/graftcp-local/vendor/github.com/kardianos/service/console.go b/graftcp-local/vendor/github.com/kardianos/service/console.go deleted file mode 100644 index ff03375..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/console.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2015 Daniel Theophanes. -// Use of this source code is governed by a zlib-style -// license that can be found in the LICENSE file. - -package service - -import ( - "log" - "os" -) - -// ConsoleLogger logs to the std err. -var ConsoleLogger = consoleLogger{} - -type consoleLogger struct { - info, warn, err *log.Logger -} - -func init() { - ConsoleLogger.info = log.New(os.Stderr, "I: ", log.Ltime) - ConsoleLogger.warn = log.New(os.Stderr, "W: ", log.Ltime) - ConsoleLogger.err = log.New(os.Stderr, "E: ", log.Ltime) -} - -func (c consoleLogger) Error(v ...interface{}) error { - c.err.Print(v...) - return nil -} -func (c consoleLogger) Warning(v ...interface{}) error { - c.warn.Print(v...) - return nil -} -func (c consoleLogger) Info(v ...interface{}) error { - c.info.Print(v...) - return nil -} -func (c consoleLogger) Errorf(format string, a ...interface{}) error { - c.err.Printf(format, a...) - return nil -} -func (c consoleLogger) Warningf(format string, a ...interface{}) error { - c.warn.Printf(format, a...) - return nil -} -func (c consoleLogger) Infof(format string, a ...interface{}) error { - c.info.Printf(format, a...) - return nil -} diff --git a/graftcp-local/vendor/github.com/kardianos/service/linux-test-su.sh b/graftcp-local/vendor/github.com/kardianos/service/linux-test-su.sh deleted file mode 100755 index 3beb240..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/linux-test-su.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash -# This script is used to run the tests under linux as root -# -# Usage: -# linux-test-su.sh goPath goBinPath -# -# goPath is the standard GOPATH -# goBinPath is the location of go -# -# Typical usage: -# sudo ./linux-test-su.sh $GOPATH `which go` - -export GOPATH=$1 -export GOROOT=`dirname $(dirname $2)` -$GOROOT/bin/go test -v -tags su ./... diff --git a/graftcp-local/vendor/github.com/kardianos/service/pre_go1.8.go b/graftcp-local/vendor/github.com/kardianos/service/pre_go1.8.go deleted file mode 100644 index 56d7fbb..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/pre_go1.8.go +++ /dev/null @@ -1,16 +0,0 @@ -//+build !go1.8 - -package service - -import ( - "path/filepath" - - "github.com/kardianos/osext" -) - -func (c *Config) execPath() (string, error) { - if len(c.Executable) != 0 { - return filepath.Abs(c.Executable) - } - return osext.Executable() -} diff --git a/graftcp-local/vendor/github.com/kardianos/service/service.go b/graftcp-local/vendor/github.com/kardianos/service/service.go deleted file mode 100644 index af90204..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/service.go +++ /dev/null @@ -1,362 +0,0 @@ -// Copyright 2015 Daniel Theophanes. -// Use of this source code is governed by a zlib-style -// license that can be found in the LICENSE file. - -// Package service provides a simple way to create a system service. -// Currently supports Windows, Linux/(systemd | Upstart | SysV), and OSX/Launchd. -// -// Windows controls services by setting up callbacks that is non-trivial. This -// is very different then other systems. This package provides the same API -// despite the substantial differences. -// It also can be used to detect how a program is called, from an interactive -// terminal or from a service manager. -// -// Examples in the example/ folder. -// -// package main -// -// import ( -// "log" -// -// "github.com/kardianos/service" -// ) -// -// var logger service.Logger -// -// type program struct{} -// -// func (p *program) Start(s service.Service) error { -// // Start should not block. Do the actual work async. -// go p.run() -// return nil -// } -// func (p *program) run() { -// // Do work here -// } -// func (p *program) Stop(s service.Service) error { -// // Stop should not block. Return with a few seconds. -// return nil -// } -// -// func main() { -// svcConfig := &service.Config{ -// Name: "GoServiceTest", -// DisplayName: "Go Service Test", -// Description: "This is a test Go service.", -// } -// -// prg := &program{} -// s, err := service.New(prg, svcConfig) -// if err != nil { -// log.Fatal(err) -// } -// logger, err = s.Logger(nil) -// if err != nil { -// log.Fatal(err) -// } -// err = s.Run() -// if err != nil { -// logger.Error(err) -// } -// } -package service // import "github.com/kardianos/service" - -import ( - "errors" - "fmt" -) - -const ( - optionKeepAlive = "KeepAlive" - optionKeepAliveDefault = true - optionRunAtLoad = "RunAtLoad" - optionRunAtLoadDefault = false - optionUserService = "UserService" - optionUserServiceDefault = false - optionSessionCreate = "SessionCreate" - optionSessionCreateDefault = false - - optionRunWait = "RunWait" - optionReloadSignal = "ReloadSignal" - optionPIDFile = "PIDFile" -) - -// Config provides the setup for a Service. The Name field is required. -type Config struct { - Name string // Required name of the service. No spaces suggested. - DisplayName string // Display name, spaces allowed. - Description string // Long description of service. - UserName string // Run as username. - Arguments []string // Run with arguments. - - // Optional field to specify the executable for service. - // If empty the current executable is used. - Executable string - - // Array of service dependencies. - // Not yet implemented on Linux or OS X. - Dependencies []string - - // The following fields are not supported on Windows. - WorkingDirectory string // Initial working directory. - ChRoot string - - // System specific options. - // * OS X - // - KeepAlive bool (true) - // - RunAtLoad bool (false) - // - UserService bool (false) - Install as a current user service. - // - SessionCreate bool (false) - Create a full user session. - // * POSIX - // - RunWait func() (wait for SIGNAL) - Do not install signal but wait for this function to return. - // - ReloadSignal string () [USR1, ...] - Signal to send on reaload. - // - PIDFile string () [/run/prog.pid] - Location of the PID file. - Option KeyValue -} - -var ( - system System - systemRegistry []System -) - -var ( - // ErrNameFieldRequired is returned when Conifg.Name is empty. - ErrNameFieldRequired = errors.New("Config.Name field is required.") - // ErrNoServiceSystemDetected is returned when no system was detected. - ErrNoServiceSystemDetected = errors.New("No service system detected.") -) - -// New creates a new service based on a service interface and configuration. -func New(i Interface, c *Config) (Service, error) { - if len(c.Name) == 0 { - return nil, ErrNameFieldRequired - } - if system == nil { - return nil, ErrNoServiceSystemDetected - } - return system.New(i, c) -} - -// KeyValue provides a list of platform specific options. See platform docs for -// more details. -type KeyValue map[string]interface{} - -// bool returns the value of the given name, assuming the value is a boolean. -// If the value isn't found or is not of the type, the defaultValue is returned. -func (kv KeyValue) bool(name string, defaultValue bool) bool { - if v, found := kv[name]; found { - if castValue, is := v.(bool); is { - return castValue - } - } - return defaultValue -} - -// int returns the value of the given name, assuming the value is an int. -// If the value isn't found or is not of the type, the defaultValue is returned. -func (kv KeyValue) int(name string, defaultValue int) int { - if v, found := kv[name]; found { - if castValue, is := v.(int); is { - return castValue - } - } - return defaultValue -} - -// string returns the value of the given name, assuming the value is a string. -// If the value isn't found or is not of the type, the defaultValue is returned. -func (kv KeyValue) string(name string, defaultValue string) string { - if v, found := kv[name]; found { - if castValue, is := v.(string); is { - return castValue - } - } - return defaultValue -} - -// float64 returns the value of the given name, assuming the value is a float64. -// If the value isn't found or is not of the type, the defaultValue is returned. -func (kv KeyValue) float64(name string, defaultValue float64) float64 { - if v, found := kv[name]; found { - if castValue, is := v.(float64); is { - return castValue - } - } - return defaultValue -} - -// funcSingle returns the value of the given name, assuming the value is a float64. -// If the value isn't found or is not of the type, the defaultValue is returned. -func (kv KeyValue) funcSingle(name string, defaultValue func()) func() { - if v, found := kv[name]; found { - if castValue, is := v.(func()); is { - return castValue - } - } - return defaultValue -} - -// Platform returns a description of the system service. -func Platform() string { - if system == nil { - return "" - } - return system.String() -} - -// Interactive returns false if running under the OS service manager -// and true otherwise. -func Interactive() bool { - if system == nil { - return true - } - return system.Interactive() -} - -func newSystem() System { - for _, choice := range systemRegistry { - if choice.Detect() == false { - continue - } - return choice - } - return nil -} - -// ChooseSystem chooses a system from the given system services. -// SystemServices are considered in the order they are suggested. -// Calling this may change what Interactive and Platform return. -func ChooseSystem(a ...System) { - systemRegistry = a - system = newSystem() -} - -// ChosenSystem returns the system that service will use. -func ChosenSystem() System { - return system -} - -// AvailableSystems returns the list of system services considered -// when choosing the system service. -func AvailableSystems() []System { - return systemRegistry -} - -// System represents the service manager that is available. -type System interface { - // String returns a description of the system. - String() string - - // Detect returns true if the system is available to use. - Detect() bool - - // Interactive returns false if running under the system service manager - // and true otherwise. - Interactive() bool - - // New creates a new service for this system. - New(i Interface, c *Config) (Service, error) -} - -// Interface represents the service interface for a program. Start runs before -// the hosting process is granted control and Stop runs when control is returned. -// -// 1. OS service manager executes user program. -// 2. User program sees it is executed from a service manager (IsInteractive is false). -// 3. User program calls Service.Run() which blocks. -// 4. Interface.Start() is called and quickly returns. -// 5. User program runs. -// 6. OS service manager signals the user program to stop. -// 7. Interface.Stop() is called and quickly returns. -// - For a successful exit, os.Exit should not be called in Interface.Stop(). -// 8. Service.Run returns. -// 9. User program should quickly exit. -type Interface interface { - // Start provides a place to initiate the service. The service doesn't not - // signal a completed start until after this function returns, so the - // Start function must not take more then a few seconds at most. - Start(s Service) error - - // Stop provides a place to clean up program execution before it is terminated. - // It should not take more then a few seconds to execute. - // Stop should not call os.Exit directly in the function. - Stop(s Service) error -} - -// TODO: Add Configure to Service interface. - -// Service represents a service that can be run or controlled. -type Service interface { - // Run should be called shortly after the program entry point. - // After Interface.Stop has finished running, Run will stop blocking. - // After Run stops blocking, the program must exit shortly after. - Run() error - - // Start signals to the OS service manager the given service should start. - Start() error - - // Stop signals to the OS service manager the given service should stop. - Stop() error - - // Restart signals to the OS service manager the given service should stop then start. - Restart() error - - // Install setups up the given service in the OS service manager. This may require - // greater rights. Will return an error if it is already installed. - Install() error - - // Uninstall removes the given service from the OS service manager. This may require - // greater rights. Will return an error if the service is not present. - Uninstall() error - - // Opens and returns a system logger. If the user program is running - // interactively rather then as a service, the returned logger will write to - // os.Stderr. If errs is non-nil errors will be sent on errs as well as - // returned from Logger's functions. - Logger(errs chan<- error) (Logger, error) - - // SystemLogger opens and returns a system logger. If errs is non-nil errors - // will be sent on errs as well as returned from Logger's functions. - SystemLogger(errs chan<- error) (Logger, error) - - // String displays the name of the service. The display name if present, - // otherwise the name. - String() string -} - -// ControlAction list valid string texts to use in Control. -var ControlAction = [5]string{"start", "stop", "restart", "install", "uninstall"} - -// Control issues control functions to the service from a given action string. -func Control(s Service, action string) error { - var err error - switch action { - case ControlAction[0]: - err = s.Start() - case ControlAction[1]: - err = s.Stop() - case ControlAction[2]: - err = s.Restart() - case ControlAction[3]: - err = s.Install() - case ControlAction[4]: - err = s.Uninstall() - default: - err = fmt.Errorf("Unknown action %s", action) - } - if err != nil { - return fmt.Errorf("Failed to %s %v: %v", action, s, err) - } - return nil -} - -// Logger writes to the system log. -type Logger interface { - Error(v ...interface{}) error - Warning(v ...interface{}) error - Info(v ...interface{}) error - - Errorf(format string, a ...interface{}) error - Warningf(format string, a ...interface{}) error - Infof(format string, a ...interface{}) error -} diff --git a/graftcp-local/vendor/github.com/kardianos/service/service_darwin.go b/graftcp-local/vendor/github.com/kardianos/service/service_darwin.go deleted file mode 100644 index 0a28962..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/service_darwin.go +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright 2015 Daniel Theophanes. -// Use of this source code is governed by a zlib-style -// license that can be found in the LICENSE file. - -package service - -import ( - "errors" - "fmt" - "os" - "os/signal" - "os/user" - "path/filepath" - "syscall" - "text/template" - "time" -) - -const maxPathSize = 32 * 1024 - -const version = "darwin-launchd" - -type darwinSystem struct{} - -func (darwinSystem) String() string { - return version -} -func (darwinSystem) Detect() bool { - return true -} -func (darwinSystem) Interactive() bool { - return interactive -} -func (darwinSystem) New(i Interface, c *Config) (Service, error) { - s := &darwinLaunchdService{ - i: i, - Config: c, - - userService: c.Option.bool(optionUserService, optionUserServiceDefault), - } - - return s, nil -} - -func init() { - ChooseSystem(darwinSystem{}) -} - -var interactive = false - -func init() { - var err error - interactive, err = isInteractive() - if err != nil { - panic(err) - } -} - -func isInteractive() (bool, error) { - // TODO: The PPID of Launchd is 1. The PPid of a service process should match launchd's PID. - return os.Getppid() != 1, nil -} - -type darwinLaunchdService struct { - i Interface - *Config - - userService bool -} - -func (s *darwinLaunchdService) String() string { - if len(s.DisplayName) > 0 { - return s.DisplayName - } - return s.Name -} - -func (s *darwinLaunchdService) getHomeDir() (string, error) { - u, err := user.Current() - if err == nil { - return u.HomeDir, nil - } - - // alternate methods - homeDir := os.Getenv("HOME") // *nix - if homeDir == "" { - return "", errors.New("User home directory not found.") - } - return homeDir, nil -} - -func (s *darwinLaunchdService) getServiceFilePath() (string, error) { - if s.userService { - homeDir, err := s.getHomeDir() - if err != nil { - return "", err - } - return homeDir + "/Library/LaunchAgents/" + s.Name + ".plist", nil - } - return "/Library/LaunchDaemons/" + s.Name + ".plist", nil -} - -func (s *darwinLaunchdService) Install() error { - confPath, err := s.getServiceFilePath() - if err != nil { - return err - } - _, err = os.Stat(confPath) - if err == nil { - return fmt.Errorf("Init already exists: %s", confPath) - } - - if s.userService { - // Ensure that ~/Library/LaunchAgents exists. - err = os.MkdirAll(filepath.Dir(confPath), 0700) - if err != nil { - return err - } - } - - f, err := os.Create(confPath) - if err != nil { - return err - } - defer f.Close() - - path, err := s.execPath() - if err != nil { - return err - } - - var to = &struct { - *Config - Path string - - KeepAlive, RunAtLoad bool - SessionCreate bool - }{ - Config: s.Config, - Path: path, - KeepAlive: s.Option.bool(optionKeepAlive, optionKeepAliveDefault), - RunAtLoad: s.Option.bool(optionRunAtLoad, optionRunAtLoadDefault), - SessionCreate: s.Option.bool(optionSessionCreate, optionSessionCreateDefault), - } - - functions := template.FuncMap{ - "bool": func(v bool) string { - if v { - return "true" - } - return "false" - }, - } - t := template.Must(template.New("launchdConfig").Funcs(functions).Parse(launchdConfig)) - return t.Execute(f, to) -} - -func (s *darwinLaunchdService) Uninstall() error { - s.Stop() - - confPath, err := s.getServiceFilePath() - if err != nil { - return err - } - return os.Remove(confPath) -} - -func (s *darwinLaunchdService) Start() error { - confPath, err := s.getServiceFilePath() - if err != nil { - return err - } - return run("launchctl", "load", confPath) -} -func (s *darwinLaunchdService) Stop() error { - confPath, err := s.getServiceFilePath() - if err != nil { - return err - } - return run("launchctl", "unload", confPath) -} -func (s *darwinLaunchdService) Restart() error { - err := s.Stop() - if err != nil { - return err - } - time.Sleep(50 * time.Millisecond) - return s.Start() -} - -func (s *darwinLaunchdService) Run() error { - var err error - - err = s.i.Start(s) - if err != nil { - return err - } - - s.Option.funcSingle(optionRunWait, func() { - var sigChan = make(chan os.Signal, 3) - signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt) - <-sigChan - })() - - return s.i.Stop(s) -} - -func (s *darwinLaunchdService) Logger(errs chan<- error) (Logger, error) { - if interactive { - return ConsoleLogger, nil - } - return s.SystemLogger(errs) -} -func (s *darwinLaunchdService) SystemLogger(errs chan<- error) (Logger, error) { - return newSysLogger(s.Name, errs) -} - -var launchdConfig = ` - - - -Label{{html .Name}} -ProgramArguments - - {{html .Path}} -{{range .Config.Arguments}} - {{html .}} -{{end}} - -{{if .UserName}}UserName{{html .UserName}}{{end}} -{{if .ChRoot}}RootDirectory{{html .ChRoot}}{{end}} -{{if .WorkingDirectory}}WorkingDirectory{{html .WorkingDirectory}}{{end}} -SessionCreate<{{bool .SessionCreate}}/> -KeepAlive<{{bool .KeepAlive}}/> -RunAtLoad<{{bool .RunAtLoad}}/> -Disabled - - -` diff --git a/graftcp-local/vendor/github.com/kardianos/service/service_go1.8.go b/graftcp-local/vendor/github.com/kardianos/service/service_go1.8.go deleted file mode 100644 index 64bb0a9..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/service_go1.8.go +++ /dev/null @@ -1,15 +0,0 @@ -//+build go1.8 - -package service - -import ( - "os" - "path/filepath" -) - -func (c *Config) execPath() (string, error) { - if len(c.Executable) != 0 { - return filepath.Abs(c.Executable) - } - return os.Executable() -} diff --git a/graftcp-local/vendor/github.com/kardianos/service/service_linux.go b/graftcp-local/vendor/github.com/kardianos/service/service_linux.go deleted file mode 100644 index 64158d8..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/service_linux.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2015 Daniel Theophanes. -// Use of this source code is governed by a zlib-style -// license that can be found in the LICENSE file. - -package service - -import ( - "os" - "strings" -) - -type linuxSystemService struct { - name string - detect func() bool - interactive func() bool - new func(i Interface, c *Config) (Service, error) -} - -func (sc linuxSystemService) String() string { - return sc.name -} -func (sc linuxSystemService) Detect() bool { - return sc.detect() -} -func (sc linuxSystemService) Interactive() bool { - return sc.interactive() -} -func (sc linuxSystemService) New(i Interface, c *Config) (Service, error) { - return sc.new(i, c) -} - -func init() { - ChooseSystem(linuxSystemService{ - name: "linux-systemd", - detect: isSystemd, - interactive: func() bool { - is, _ := isInteractive() - return is - }, - new: newSystemdService, - }, - linuxSystemService{ - name: "linux-upstart", - detect: isUpstart, - interactive: func() bool { - is, _ := isInteractive() - return is - }, - new: newUpstartService, - }, - linuxSystemService{ - name: "unix-systemv", - detect: func() bool { return true }, - interactive: func() bool { - is, _ := isInteractive() - return is - }, - new: newSystemVService, - }, - ) -} - -func isInteractive() (bool, error) { - // TODO: This is not true for user services. - return os.Getppid() != 1, nil -} - -var tf = map[string]interface{}{ - "cmd": func(s string) string { - return `"` + strings.Replace(s, `"`, `\"`, -1) + `"` - }, - "cmdEscape": func(s string) string { - return strings.Replace(s, " ", `\x20`, -1) - }, -} diff --git a/graftcp-local/vendor/github.com/kardianos/service/service_systemd_linux.go b/graftcp-local/vendor/github.com/kardianos/service/service_systemd_linux.go deleted file mode 100644 index 259fd9e..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/service_systemd_linux.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright 2015 Daniel Theophanes. -// Use of this source code is governed by a zlib-style -// license that can be found in the LICENSE file. - -package service - -import ( - "errors" - "fmt" - "os" - "os/signal" - "syscall" - "text/template" -) - -func isSystemd() bool { - if _, err := os.Stat("/run/systemd/system"); err == nil { - return true - } - return false -} - -type systemd struct { - i Interface - *Config -} - -func newSystemdService(i Interface, c *Config) (Service, error) { - s := &systemd{ - i: i, - Config: c, - } - - return s, nil -} - -func (s *systemd) String() string { - if len(s.DisplayName) > 0 { - return s.DisplayName - } - return s.Name -} - -// Systemd services should be supported, but are not currently. -var errNoUserServiceSystemd = errors.New("User services are not supported on systemd.") - -func (s *systemd) configPath() (cp string, err error) { - if s.Option.bool(optionUserService, optionUserServiceDefault) { - err = errNoUserServiceSystemd - return - } - cp = "/etc/systemd/system/" + s.Config.Name + ".service" - return -} -func (s *systemd) template() *template.Template { - return template.Must(template.New("").Funcs(tf).Parse(systemdScript)) -} - -func (s *systemd) Install() error { - confPath, err := s.configPath() - if err != nil { - return err - } - _, err = os.Stat(confPath) - if err == nil { - return fmt.Errorf("Init already exists: %s", confPath) - } - - f, err := os.Create(confPath) - if err != nil { - return err - } - defer f.Close() - - path, err := s.execPath() - if err != nil { - return err - } - - var to = &struct { - *Config - Path string - ReloadSignal string - PIDFile string - }{ - s.Config, - path, - s.Option.string(optionReloadSignal, ""), - s.Option.string(optionPIDFile, ""), - } - - err = s.template().Execute(f, to) - if err != nil { - return err - } - - err = run("systemctl", "enable", s.Name+".service") - if err != nil { - return err - } - return run("systemctl", "daemon-reload") -} - -func (s *systemd) Uninstall() error { - err := run("systemctl", "disable", s.Name+".service") - if err != nil { - return err - } - cp, err := s.configPath() - if err != nil { - return err - } - if err := os.Remove(cp); err != nil { - return err - } - return nil -} - -func (s *systemd) Logger(errs chan<- error) (Logger, error) { - if system.Interactive() { - return ConsoleLogger, nil - } - return s.SystemLogger(errs) -} -func (s *systemd) SystemLogger(errs chan<- error) (Logger, error) { - return newSysLogger(s.Name, errs) -} - -func (s *systemd) Run() (err error) { - err = s.i.Start(s) - if err != nil { - return err - } - - s.Option.funcSingle(optionRunWait, func() { - var sigChan = make(chan os.Signal, 3) - signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt) - <-sigChan - })() - - return s.i.Stop(s) -} - -func (s *systemd) Start() error { - return run("systemctl", "start", s.Name+".service") -} - -func (s *systemd) Stop() error { - return run("systemctl", "stop", s.Name+".service") -} - -func (s *systemd) Restart() error { - return run("systemctl", "restart", s.Name+".service") -} - -const systemdScript = `[Unit] -Description={{.Description}} -ConditionFileIsExecutable={{.Path|cmdEscape}} - -[Service] -StartLimitInterval=5 -StartLimitBurst=10 -ExecStart=/bin/bash -c {{.Path|cmdEscape}}{{range .Arguments}} {{.|cmd}}{{end}} -{{if .ChRoot}}RootDirectory={{.ChRoot|cmd}}{{end}} -{{if .WorkingDirectory}}WorkingDirectory={{.WorkingDirectory|cmdEscape}}{{end}} -{{if .UserName}}User={{.UserName}}{{end}} -{{if .ReloadSignal}}ExecReload=/bin/kill -{{.ReloadSignal}} "$MAINPID"{{end}} -{{if .PIDFile}}PIDFile={{.PIDFile|cmd}}{{end}} -Restart=always -RestartSec=120 -EnvironmentFile=-/etc/sysconfig/{{.Name}} - -[Install] -WantedBy=multi-user.target -` diff --git a/graftcp-local/vendor/github.com/kardianos/service/service_sysv_linux.go b/graftcp-local/vendor/github.com/kardianos/service/service_sysv_linux.go deleted file mode 100644 index d2a965b..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/service_sysv_linux.go +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright 2015 Daniel Theophanes. -// Use of this source code is governed by a zlib-style -// license that can be found in the LICENSE file. - -package service - -import ( - "errors" - "fmt" - "os" - "os/signal" - "syscall" - "text/template" - "time" -) - -type sysv struct { - i Interface - *Config -} - -func newSystemVService(i Interface, c *Config) (Service, error) { - s := &sysv{ - i: i, - Config: c, - } - - return s, nil -} - -func (s *sysv) String() string { - if len(s.DisplayName) > 0 { - return s.DisplayName - } - return s.Name -} - -var errNoUserServiceSystemV = errors.New("User services are not supported on SystemV.") - -func (s *sysv) configPath() (cp string, err error) { - if s.Option.bool(optionUserService, optionUserServiceDefault) { - err = errNoUserServiceSystemV - return - } - cp = "/etc/init.d/" + s.Config.Name - return -} -func (s *sysv) template() *template.Template { - return template.Must(template.New("").Funcs(tf).Parse(sysvScript)) -} - -func (s *sysv) Install() error { - confPath, err := s.configPath() - if err != nil { - return err - } - _, err = os.Stat(confPath) - if err == nil { - return fmt.Errorf("Init already exists: %s", confPath) - } - - f, err := os.Create(confPath) - if err != nil { - return err - } - defer f.Close() - - path, err := s.execPath() - if err != nil { - return err - } - - var to = &struct { - *Config - Path string - }{ - s.Config, - path, - } - - err = s.template().Execute(f, to) - if err != nil { - return err - } - - if err = os.Chmod(confPath, 0755); err != nil { - return err - } - for _, i := range [...]string{"2", "3", "4", "5"} { - if err = os.Symlink(confPath, "/etc/rc"+i+".d/S50"+s.Name); err != nil { - continue - } - } - for _, i := range [...]string{"0", "1", "6"} { - if err = os.Symlink(confPath, "/etc/rc"+i+".d/K02"+s.Name); err != nil { - continue - } - } - - return nil -} - -func (s *sysv) Uninstall() error { - cp, err := s.configPath() - if err != nil { - return err - } - if err := os.Remove(cp); err != nil { - return err - } - return nil -} - -func (s *sysv) Logger(errs chan<- error) (Logger, error) { - if system.Interactive() { - return ConsoleLogger, nil - } - return s.SystemLogger(errs) -} -func (s *sysv) SystemLogger(errs chan<- error) (Logger, error) { - return newSysLogger(s.Name, errs) -} - -func (s *sysv) Run() (err error) { - err = s.i.Start(s) - if err != nil { - return err - } - - s.Option.funcSingle(optionRunWait, func() { - var sigChan = make(chan os.Signal, 3) - signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt) - <-sigChan - })() - - return s.i.Stop(s) -} - -func (s *sysv) Start() error { - return run("service", s.Name, "start") -} - -func (s *sysv) Stop() error { - return run("service", s.Name, "stop") -} - -func (s *sysv) Restart() error { - err := s.Stop() - if err != nil { - return err - } - time.Sleep(50 * time.Millisecond) - return s.Start() -} - -const sysvScript = `#!/bin/sh -# For RedHat and cousins: -# chkconfig: - 99 01 -# description: {{.Description}} -# processname: {{.Path}} - -### BEGIN INIT INFO -# Provides: {{.Path}} -# Required-Start: -# Required-Stop: -# Default-Start: 2 3 4 5 -# Default-Stop: 0 1 6 -# Short-Description: {{.DisplayName}} -# Description: {{.Description}} -### END INIT INFO - -cmd="{{.Path}}{{range .Arguments}} {{.|cmd}}{{end}}" - -name=$(basename $(readlink -f $0)) -pid_file="/var/run/$name.pid" -stdout_log="/var/log/$name.log" -stderr_log="/var/log/$name.err" - -[ -e /etc/sysconfig/$name ] && . /etc/sysconfig/$name - -get_pid() { - cat "$pid_file" -} - -is_running() { - [ -f "$pid_file" ] && ps $(get_pid) > /dev/null 2>&1 -} - -case "$1" in - start) - if is_running; then - echo "Already started" - else - echo "Starting $name" - {{if .WorkingDirectory}}cd '{{.WorkingDirectory}}'{{end}} - $cmd >> "$stdout_log" 2>> "$stderr_log" & - echo $! > "$pid_file" - if ! is_running; then - echo "Unable to start, see $stdout_log and $stderr_log" - exit 1 - fi - fi - ;; - stop) - if is_running; then - echo -n "Stopping $name.." - kill $(get_pid) - for i in $(seq 1 10) - do - if ! is_running; then - break - fi - echo -n "." - sleep 1 - done - echo - if is_running; then - echo "Not stopped; may still be shutting down or shutdown may have failed" - exit 1 - else - echo "Stopped" - if [ -f "$pid_file" ]; then - rm "$pid_file" - fi - fi - else - echo "Not running" - fi - ;; - restart) - $0 stop - if is_running; then - echo "Unable to stop, will not attempt to start" - exit 1 - fi - $0 start - ;; - status) - if is_running; then - echo "Running" - else - echo "Stopped" - exit 1 - fi - ;; - *) - echo "Usage: $0 {start|stop|restart|status}" - exit 1 - ;; -esac -exit 0 -` diff --git a/graftcp-local/vendor/github.com/kardianos/service/service_unix.go b/graftcp-local/vendor/github.com/kardianos/service/service_unix.go deleted file mode 100644 index bf4e2bd..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/service_unix.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2015 Daniel Theophanes. -// Use of this source code is governed by a zlib-style -// license that can be found in the LICENSE file. - -// +build linux darwin - -package service - -import ( - "fmt" - "io/ioutil" - "log/syslog" - "os/exec" -) - -func newSysLogger(name string, errs chan<- error) (Logger, error) { - w, err := syslog.New(syslog.LOG_INFO, name) - if err != nil { - return nil, err - } - return sysLogger{w, errs}, nil -} - -type sysLogger struct { - *syslog.Writer - errs chan<- error -} - -func (s sysLogger) send(err error) error { - if err != nil && s.errs != nil { - s.errs <- err - } - return err -} - -func (s sysLogger) Error(v ...interface{}) error { - return s.send(s.Writer.Err(fmt.Sprint(v...))) -} -func (s sysLogger) Warning(v ...interface{}) error { - return s.send(s.Writer.Warning(fmt.Sprint(v...))) -} -func (s sysLogger) Info(v ...interface{}) error { - return s.send(s.Writer.Info(fmt.Sprint(v...))) -} -func (s sysLogger) Errorf(format string, a ...interface{}) error { - return s.send(s.Writer.Err(fmt.Sprintf(format, a...))) -} -func (s sysLogger) Warningf(format string, a ...interface{}) error { - return s.send(s.Writer.Warning(fmt.Sprintf(format, a...))) -} -func (s sysLogger) Infof(format string, a ...interface{}) error { - return s.send(s.Writer.Info(fmt.Sprintf(format, a...))) -} - -func run(command string, arguments ...string) error { - cmd := exec.Command(command, arguments...) - - // Connect pipe to read Stderr - stderr, err := cmd.StderrPipe() - - if err != nil { - // Failed to connect pipe - return fmt.Errorf("%q failed to connect stderr pipe: %v", command, err) - } - - // Do not use cmd.Run() - if err := cmd.Start(); err != nil { - // Problem while copying stdin, stdout, or stderr - return fmt.Errorf("%q failed: %v", command, err) - } - - // Zero exit status - // Darwin: launchctl can fail with a zero exit status, - // so check for emtpy stderr - if command == "launchctl" { - slurp, _ := ioutil.ReadAll(stderr) - if len(slurp) > 0 { - return fmt.Errorf("%q failed with stderr: %s", command, slurp) - } - } - - if err := cmd.Wait(); err != nil { - // Command didn't exit with a zero exit status. - return fmt.Errorf("%q failed: %v", command, err) - } - - return nil -} diff --git a/graftcp-local/vendor/github.com/kardianos/service/service_upstart_linux.go b/graftcp-local/vendor/github.com/kardianos/service/service_upstart_linux.go deleted file mode 100644 index 4ec01ab..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/service_upstart_linux.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2015 Daniel Theophanes. -// Use of this source code is governed by a zlib-style -// license that can be found in the LICENSE file. - -package service - -import ( - "errors" - "fmt" - "os" - "os/exec" - "os/signal" - "regexp" - "strconv" - "strings" - "text/template" - "time" -) - -func isUpstart() bool { - if _, err := os.Stat("/sbin/upstart-udev-bridge"); err == nil { - return true - } - if _, err := os.Stat("/sbin/init"); err == nil { - if out, err := exec.Command("/sbin/init", "--version").Output(); err == nil { - if strings.Contains(string(out), "init (upstart") { - return true - } - } - } - return false -} - -type upstart struct { - i Interface - *Config -} - -func newUpstartService(i Interface, c *Config) (Service, error) { - s := &upstart{ - i: i, - Config: c, - } - - return s, nil -} - -func (s *upstart) String() string { - if len(s.DisplayName) > 0 { - return s.DisplayName - } - return s.Name -} - -// Upstart has some support for user services in graphical sessions. -// Due to the mix of actual support for user services over versions, just don't bother. -// Upstart will be replaced by systemd in most cases anyway. -var errNoUserServiceUpstart = errors.New("User services are not supported on Upstart.") - -func (s *upstart) configPath() (cp string, err error) { - if s.Option.bool(optionUserService, optionUserServiceDefault) { - err = errNoUserServiceUpstart - return - } - cp = "/etc/init/" + s.Config.Name + ".conf" - return -} - -func (s *upstart) hasKillStanza() bool { - defaultValue := true - - out, err := exec.Command("/sbin/init", "--version").Output() - if err != nil { - return defaultValue - } - - re := regexp.MustCompile(`init \(upstart (\d+.\d+.\d+)\)`) - matches := re.FindStringSubmatch(string(out)) - if len(matches) != 2 { - return defaultValue - } - - version := make([]int, 3) - for idx, vStr := range strings.Split(matches[1], ".") { - version[idx], err = strconv.Atoi(vStr) - if err != nil { - return defaultValue - } - } - - maxVersion := []int{0, 6, 5} - if versionAtMost(version, maxVersion) { - return false - } - - return defaultValue -} - -func versionAtMost(version, max []int) bool { - for idx, m := range max { - v := version[idx] - if v > m { - return false - } - } - return true -} - -func (s *upstart) template() *template.Template { - return template.Must(template.New("").Funcs(tf).Parse(upstartScript)) -} - -func (s *upstart) Install() error { - confPath, err := s.configPath() - if err != nil { - return err - } - _, err = os.Stat(confPath) - if err == nil { - return fmt.Errorf("Init already exists: %s", confPath) - } - - f, err := os.Create(confPath) - if err != nil { - return err - } - defer f.Close() - - path, err := s.execPath() - if err != nil { - return err - } - - var to = &struct { - *Config - Path string - HasKillStanza bool - }{ - s.Config, - path, - s.hasKillStanza(), - } - - return s.template().Execute(f, to) -} - -func (s *upstart) Uninstall() error { - cp, err := s.configPath() - if err != nil { - return err - } - if err := os.Remove(cp); err != nil { - return err - } - return nil -} - -func (s *upstart) Logger(errs chan<- error) (Logger, error) { - if system.Interactive() { - return ConsoleLogger, nil - } - return s.SystemLogger(errs) -} -func (s *upstart) SystemLogger(errs chan<- error) (Logger, error) { - return newSysLogger(s.Name, errs) -} - -func (s *upstart) Run() (err error) { - err = s.i.Start(s) - if err != nil { - return err - } - - s.Option.funcSingle(optionRunWait, func() { - var sigChan = make(chan os.Signal, 3) - signal.Notify(sigChan, os.Interrupt, os.Kill) - <-sigChan - })() - - return s.i.Stop(s) -} - -func (s *upstart) Start() error { - return run("initctl", "start", s.Name) -} - -func (s *upstart) Stop() error { - return run("initctl", "stop", s.Name) -} - -func (s *upstart) Restart() error { - err := s.Stop() - if err != nil { - return err - } - time.Sleep(50 * time.Millisecond) - return s.Start() -} - -// The upstart script should stop with an INT or the Go runtime will terminate -// the program before the Stop handler can run. -const upstartScript = `# {{.Description}} - -{{if .DisplayName}}description "{{.DisplayName}}"{{end}} - -{{if .HasKillStanza}}kill signal INT{{end}} -{{if .ChRoot}}chroot {{.ChRoot}}{{end}} -{{if .WorkingDirectory}}chdir {{.WorkingDirectory}}{{end}} -start on filesystem or runlevel [2345] -stop on runlevel [!2345] - -{{if .UserName}}setuid {{.UserName}}{{end}} - -respawn -respawn limit 10 5 -umask 022 - -console none - -pre-start script - test -x {{.Path}} || { stop; exit 0; } -end script - -# Start -exec {{.Path}}{{range .Arguments}} {{.|cmd}}{{end}} -` diff --git a/graftcp-local/vendor/github.com/kardianos/service/service_windows.go b/graftcp-local/vendor/github.com/kardianos/service/service_windows.go deleted file mode 100644 index f081dd0..0000000 --- a/graftcp-local/vendor/github.com/kardianos/service/service_windows.go +++ /dev/null @@ -1,389 +0,0 @@ -// Copyright 2015 Daniel Theophanes. -// Use of this source code is governed by a zlib-style -// license that can be found in the LICENSE file. - -package service - -import ( - "fmt" - "os" - "os/signal" - "strconv" - "sync" - "time" - - "golang.org/x/sys/windows/registry" - "golang.org/x/sys/windows/svc" - "golang.org/x/sys/windows/svc/eventlog" - "golang.org/x/sys/windows/svc/mgr" -) - -const version = "windows-service" - -type windowsService struct { - i Interface - *Config - - errSync sync.Mutex - stopStartErr error -} - -// WindowsLogger allows using windows specific logging methods. -type WindowsLogger struct { - ev *eventlog.Log - errs chan<- error -} - -type windowsSystem struct{} - -func (windowsSystem) String() string { - return version -} -func (windowsSystem) Detect() bool { - return true -} -func (windowsSystem) Interactive() bool { - return interactive -} -func (windowsSystem) New(i Interface, c *Config) (Service, error) { - ws := &windowsService{ - i: i, - Config: c, - } - return ws, nil -} - -func init() { - ChooseSystem(windowsSystem{}) -} - -func (l WindowsLogger) send(err error) error { - if err == nil { - return nil - } - if l.errs != nil { - l.errs <- err - } - return err -} - -// Error logs an error message. -func (l WindowsLogger) Error(v ...interface{}) error { - return l.send(l.ev.Error(3, fmt.Sprint(v...))) -} - -// Warning logs an warning message. -func (l WindowsLogger) Warning(v ...interface{}) error { - return l.send(l.ev.Warning(2, fmt.Sprint(v...))) -} - -// Info logs an info message. -func (l WindowsLogger) Info(v ...interface{}) error { - return l.send(l.ev.Info(1, fmt.Sprint(v...))) -} - -// Errorf logs an error message. -func (l WindowsLogger) Errorf(format string, a ...interface{}) error { - return l.send(l.ev.Error(3, fmt.Sprintf(format, a...))) -} - -// Warningf logs an warning message. -func (l WindowsLogger) Warningf(format string, a ...interface{}) error { - return l.send(l.ev.Warning(2, fmt.Sprintf(format, a...))) -} - -// Infof logs an info message. -func (l WindowsLogger) Infof(format string, a ...interface{}) error { - return l.send(l.ev.Info(1, fmt.Sprintf(format, a...))) -} - -// NError logs an error message and an event ID. -func (l WindowsLogger) NError(eventID uint32, v ...interface{}) error { - return l.send(l.ev.Error(eventID, fmt.Sprint(v...))) -} - -// NWarning logs an warning message and an event ID. -func (l WindowsLogger) NWarning(eventID uint32, v ...interface{}) error { - return l.send(l.ev.Warning(eventID, fmt.Sprint(v...))) -} - -// NInfo logs an info message and an event ID. -func (l WindowsLogger) NInfo(eventID uint32, v ...interface{}) error { - return l.send(l.ev.Info(eventID, fmt.Sprint(v...))) -} - -// NErrorf logs an error message and an event ID. -func (l WindowsLogger) NErrorf(eventID uint32, format string, a ...interface{}) error { - return l.send(l.ev.Error(eventID, fmt.Sprintf(format, a...))) -} - -// NWarningf logs an warning message and an event ID. -func (l WindowsLogger) NWarningf(eventID uint32, format string, a ...interface{}) error { - return l.send(l.ev.Warning(eventID, fmt.Sprintf(format, a...))) -} - -// NInfof logs an info message and an event ID. -func (l WindowsLogger) NInfof(eventID uint32, format string, a ...interface{}) error { - return l.send(l.ev.Info(eventID, fmt.Sprintf(format, a...))) -} - -var interactive = false - -func init() { - var err error - interactive, err = svc.IsAnInteractiveSession() - if err != nil { - panic(err) - } -} - -func (ws *windowsService) String() string { - if len(ws.DisplayName) > 0 { - return ws.DisplayName - } - return ws.Name -} - -func (ws *windowsService) setError(err error) { - ws.errSync.Lock() - defer ws.errSync.Unlock() - ws.stopStartErr = err -} -func (ws *windowsService) getError() error { - ws.errSync.Lock() - defer ws.errSync.Unlock() - return ws.stopStartErr -} - -func (ws *windowsService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (bool, uint32) { - const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown - changes <- svc.Status{State: svc.StartPending} - - if err := ws.i.Start(ws); err != nil { - ws.setError(err) - return true, 1 - } - - changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} -loop: - for { - c := <-r - switch c.Cmd { - case svc.Interrogate: - changes <- c.CurrentStatus - case svc.Stop, svc.Shutdown: - changes <- svc.Status{State: svc.StopPending} - if err := ws.i.Stop(ws); err != nil { - ws.setError(err) - return true, 2 - } - break loop - default: - continue loop - } - } - - return false, 0 -} - -func (ws *windowsService) Install() error { - exepath, err := ws.execPath() - if err != nil { - return err - } - - m, err := mgr.Connect() - if err != nil { - return err - } - defer m.Disconnect() - s, err := m.OpenService(ws.Name) - if err == nil { - s.Close() - return fmt.Errorf("service %s already exists", ws.Name) - } - s, err = m.CreateService(ws.Name, exepath, mgr.Config{ - DisplayName: ws.DisplayName, - Description: ws.Description, - StartType: mgr.StartAutomatic, - ServiceStartName: ws.UserName, - Password: ws.Option.string("Password", ""), - Dependencies: ws.Dependencies, - }, ws.Arguments...) - if err != nil { - return err - } - defer s.Close() - err = eventlog.InstallAsEventCreate(ws.Name, eventlog.Error|eventlog.Warning|eventlog.Info) - if err != nil { - s.Delete() - return fmt.Errorf("InstallAsEventCreate() failed: %s", err) - } - return nil -} - -func (ws *windowsService) Uninstall() error { - m, err := mgr.Connect() - if err != nil { - return err - } - defer m.Disconnect() - s, err := m.OpenService(ws.Name) - if err != nil { - return fmt.Errorf("service %s is not installed", ws.Name) - } - defer s.Close() - err = s.Delete() - if err != nil { - return err - } - err = eventlog.Remove(ws.Name) - if err != nil { - return fmt.Errorf("RemoveEventLogSource() failed: %s", err) - } - return nil -} - -func (ws *windowsService) Run() error { - ws.setError(nil) - if !interactive { - // Return error messages from start and stop routines - // that get executed in the Execute method. - // Guarded with a mutex as it may run a different thread - // (callback from windows). - runErr := svc.Run(ws.Name, ws) - startStopErr := ws.getError() - if startStopErr != nil { - return startStopErr - } - if runErr != nil { - return runErr - } - return nil - } - err := ws.i.Start(ws) - if err != nil { - return err - } - - sigChan := make(chan os.Signal) - - signal.Notify(sigChan, os.Interrupt, os.Kill) - - <-sigChan - - return ws.i.Stop(ws) -} - -func (ws *windowsService) Start() error { - m, err := mgr.Connect() - if err != nil { - return err - } - defer m.Disconnect() - - s, err := m.OpenService(ws.Name) - if err != nil { - return err - } - defer s.Close() - return s.Start() -} - -func (ws *windowsService) Stop() error { - m, err := mgr.Connect() - if err != nil { - return err - } - defer m.Disconnect() - - s, err := m.OpenService(ws.Name) - if err != nil { - return err - } - defer s.Close() - - return ws.stopWait(s) -} - -func (ws *windowsService) Restart() error { - m, err := mgr.Connect() - if err != nil { - return err - } - defer m.Disconnect() - - s, err := m.OpenService(ws.Name) - if err != nil { - return err - } - defer s.Close() - - err = ws.stopWait(s) - if err != nil { - return err - } - - return s.Start() -} - -func (ws *windowsService) stopWait(s *mgr.Service) error { - // First stop the service. Then wait for the service to - // actually stop before starting it. - status, err := s.Control(svc.Stop) - if err != nil { - return err - } - - timeDuration := time.Millisecond * 50 - - timeout := time.After(getStopTimeout() + (timeDuration * 2)) - tick := time.NewTicker(timeDuration) - defer tick.Stop() - - for status.State != svc.Stopped { - select { - case <-tick.C: - status, err = s.Query() - if err != nil { - return err - } - case <-timeout: - break - } - } - return nil -} - -// getStopTimeout fetches the time before windows will kill the service. -func getStopTimeout() time.Duration { - // For default and paths see https://support.microsoft.com/en-us/kb/146092 - defaultTimeout := time.Millisecond * 20000 - key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control`, registry.READ) - if err != nil { - return defaultTimeout - } - sv, _, err := key.GetStringValue("WaitToKillServiceTimeout") - if err != nil { - return defaultTimeout - } - v, err := strconv.Atoi(sv) - if err != nil { - return defaultTimeout - } - return time.Millisecond * time.Duration(v) -} - -func (ws *windowsService) Logger(errs chan<- error) (Logger, error) { - if interactive { - return ConsoleLogger, nil - } - return ws.SystemLogger(errs) -} -func (ws *windowsService) SystemLogger(errs chan<- error) (Logger, error) { - el, err := eventlog.Open(ws.Name) - if err != nil { - return nil, err - } - return WindowsLogger{el, errs}, nil -} diff --git a/graftcp-local/vendor/golang.org/x/net/LICENSE b/graftcp-local/vendor/golang.org/x/net/LICENSE deleted file mode 100644 index 6a66aea..0000000 --- a/graftcp-local/vendor/golang.org/x/net/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. 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 Google Inc. 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 THE COPYRIGHT -OWNER OR CONTRIBUTORS 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. diff --git a/graftcp-local/vendor/golang.org/x/net/PATENTS b/graftcp-local/vendor/golang.org/x/net/PATENTS deleted file mode 100644 index 7330990..0000000 --- a/graftcp-local/vendor/golang.org/x/net/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/graftcp-local/vendor/golang.org/x/net/proxy/direct.go b/graftcp-local/vendor/golang.org/x/net/proxy/direct.go deleted file mode 100644 index 4c5ad88..0000000 --- a/graftcp-local/vendor/golang.org/x/net/proxy/direct.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2011 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 proxy - -import ( - "net" -) - -type direct struct{} - -// Direct is a direct proxy: one that makes network connections directly. -var Direct = direct{} - -func (direct) Dial(network, addr string) (net.Conn, error) { - return net.Dial(network, addr) -} diff --git a/graftcp-local/vendor/golang.org/x/net/proxy/per_host.go b/graftcp-local/vendor/golang.org/x/net/proxy/per_host.go deleted file mode 100644 index f540b19..0000000 --- a/graftcp-local/vendor/golang.org/x/net/proxy/per_host.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2011 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 proxy - -import ( - "net" - "strings" -) - -// A PerHost directs connections to a default Dialer unless the hostname -// requested matches one of a number of exceptions. -type PerHost struct { - def, bypass Dialer - - bypassNetworks []*net.IPNet - bypassIPs []net.IP - bypassZones []string - bypassHosts []string -} - -// NewPerHost returns a PerHost Dialer that directs connections to either -// defaultDialer or bypass, depending on whether the connection matches one of -// the configured rules. -func NewPerHost(defaultDialer, bypass Dialer) *PerHost { - return &PerHost{ - def: defaultDialer, - bypass: bypass, - } -} - -// Dial connects to the address addr on the given network through either -// defaultDialer or bypass. -func (p *PerHost) Dial(network, addr string) (c net.Conn, err error) { - host, _, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - - return p.dialerForRequest(host).Dial(network, addr) -} - -func (p *PerHost) dialerForRequest(host string) Dialer { - if ip := net.ParseIP(host); ip != nil { - for _, net := range p.bypassNetworks { - if net.Contains(ip) { - return p.bypass - } - } - for _, bypassIP := range p.bypassIPs { - if bypassIP.Equal(ip) { - return p.bypass - } - } - return p.def - } - - for _, zone := range p.bypassZones { - if strings.HasSuffix(host, zone) { - return p.bypass - } - if host == zone[1:] { - // For a zone "example.com", we match "example.com" - // too. - return p.bypass - } - } - for _, bypassHost := range p.bypassHosts { - if bypassHost == host { - return p.bypass - } - } - return p.def -} - -// AddFromString parses a string that contains comma-separated values -// specifying hosts that should use the bypass proxy. Each value is either an -// IP address, a CIDR range, a zone (*.example.com) or a hostname -// (localhost). A best effort is made to parse the string and errors are -// ignored. -func (p *PerHost) AddFromString(s string) { - hosts := strings.Split(s, ",") - for _, host := range hosts { - host = strings.TrimSpace(host) - if len(host) == 0 { - continue - } - if strings.Contains(host, "/") { - // We assume that it's a CIDR address like 127.0.0.0/8 - if _, net, err := net.ParseCIDR(host); err == nil { - p.AddNetwork(net) - } - continue - } - if ip := net.ParseIP(host); ip != nil { - p.AddIP(ip) - continue - } - if strings.HasPrefix(host, "*.") { - p.AddZone(host[1:]) - continue - } - p.AddHost(host) - } -} - -// AddIP specifies an IP address that will use the bypass proxy. Note that -// this will only take effect if a literal IP address is dialed. A connection -// to a named host will never match an IP. -func (p *PerHost) AddIP(ip net.IP) { - p.bypassIPs = append(p.bypassIPs, ip) -} - -// AddNetwork specifies an IP range that will use the bypass proxy. Note that -// this will only take effect if a literal IP address is dialed. A connection -// to a named host will never match. -func (p *PerHost) AddNetwork(net *net.IPNet) { - p.bypassNetworks = append(p.bypassNetworks, net) -} - -// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of -// "example.com" matches "example.com" and all of its subdomains. -func (p *PerHost) AddZone(zone string) { - if strings.HasSuffix(zone, ".") { - zone = zone[:len(zone)-1] - } - if !strings.HasPrefix(zone, ".") { - zone = "." + zone - } - p.bypassZones = append(p.bypassZones, zone) -} - -// AddHost specifies a hostname that will use the bypass proxy. -func (p *PerHost) AddHost(host string) { - if strings.HasSuffix(host, ".") { - host = host[:len(host)-1] - } - p.bypassHosts = append(p.bypassHosts, host) -} diff --git a/graftcp-local/vendor/golang.org/x/net/proxy/proxy.go b/graftcp-local/vendor/golang.org/x/net/proxy/proxy.go deleted file mode 100644 index 8ccb0c5..0000000 --- a/graftcp-local/vendor/golang.org/x/net/proxy/proxy.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2011 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 proxy provides support for a variety of protocols to proxy network -// data. -package proxy - -import ( - "errors" - "net" - "net/url" - "os" -) - -// A Dialer is a means to establish a connection. -type Dialer interface { - // Dial connects to the given address via the proxy. - Dial(network, addr string) (c net.Conn, err error) -} - -// Auth contains authentication parameters that specific Dialers may require. -type Auth struct { - User, Password string -} - -// FromEnvironment returns the dialer specified by the proxy related variables in -// the environment. -func FromEnvironment() Dialer { - allProxy := os.Getenv("all_proxy") - if len(allProxy) == 0 { - return Direct - } - - proxyURL, err := url.Parse(allProxy) - if err != nil { - return Direct - } - proxy, err := FromURL(proxyURL, Direct) - if err != nil { - return Direct - } - - noProxy := os.Getenv("no_proxy") - if len(noProxy) == 0 { - return proxy - } - - perHost := NewPerHost(proxy, Direct) - perHost.AddFromString(noProxy) - return perHost -} - -// proxySchemes is a map from URL schemes to a function that creates a Dialer -// from a URL with such a scheme. -var proxySchemes map[string]func(*url.URL, Dialer) (Dialer, error) - -// RegisterDialerType takes a URL scheme and a function to generate Dialers from -// a URL with that scheme and a forwarding Dialer. Registered schemes are used -// by FromURL. -func RegisterDialerType(scheme string, f func(*url.URL, Dialer) (Dialer, error)) { - if proxySchemes == nil { - proxySchemes = make(map[string]func(*url.URL, Dialer) (Dialer, error)) - } - proxySchemes[scheme] = f -} - -// FromURL returns a Dialer given a URL specification and an underlying -// Dialer for it to make network requests. -func FromURL(u *url.URL, forward Dialer) (Dialer, error) { - var auth *Auth - if u.User != nil { - auth = new(Auth) - auth.User = u.User.Username() - if p, ok := u.User.Password(); ok { - auth.Password = p - } - } - - switch u.Scheme { - case "socks5": - return SOCKS5("tcp", u.Host, auth, forward) - } - - // If the scheme doesn't match any of the built-in schemes, see if it - // was registered by another package. - if proxySchemes != nil { - if f, ok := proxySchemes[u.Scheme]; ok { - return f(u, forward) - } - } - - return nil, errors.New("proxy: unknown scheme: " + u.Scheme) -} diff --git a/graftcp-local/vendor/golang.org/x/net/proxy/socks5.go b/graftcp-local/vendor/golang.org/x/net/proxy/socks5.go deleted file mode 100644 index 9b96282..0000000 --- a/graftcp-local/vendor/golang.org/x/net/proxy/socks5.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2011 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 proxy - -import ( - "errors" - "io" - "net" - "strconv" -) - -// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address -// with an optional username and password. See RFC 1928. -func SOCKS5(network, addr string, auth *Auth, forward Dialer) (Dialer, error) { - s := &socks5{ - network: network, - addr: addr, - forward: forward, - } - if auth != nil { - s.user = auth.User - s.password = auth.Password - } - - return s, nil -} - -type socks5 struct { - user, password string - network, addr string - forward Dialer -} - -const socks5Version = 5 - -const ( - socks5AuthNone = 0 - socks5AuthPassword = 2 -) - -const socks5Connect = 1 - -const ( - socks5IP4 = 1 - socks5Domain = 3 - socks5IP6 = 4 -) - -var socks5Errors = []string{ - "", - "general failure", - "connection forbidden", - "network unreachable", - "host unreachable", - "connection refused", - "TTL expired", - "command not supported", - "address type not supported", -} - -// Dial connects to the address addr on the network net via the SOCKS5 proxy. -func (s *socks5) Dial(network, addr string) (net.Conn, error) { - switch network { - case "tcp", "tcp6", "tcp4": - default: - return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network) - } - - conn, err := s.forward.Dial(s.network, s.addr) - if err != nil { - return nil, err - } - closeConn := &conn - defer func() { - if closeConn != nil { - (*closeConn).Close() - } - }() - - host, portStr, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - - port, err := strconv.Atoi(portStr) - if err != nil { - return nil, errors.New("proxy: failed to parse port number: " + portStr) - } - if port < 1 || port > 0xffff { - return nil, errors.New("proxy: port number out of range: " + portStr) - } - - // the size here is just an estimate - buf := make([]byte, 0, 6+len(host)) - - buf = append(buf, socks5Version) - if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 { - buf = append(buf, 2 /* num auth methods */, socks5AuthNone, socks5AuthPassword) - } else { - buf = append(buf, 1 /* num auth methods */, socks5AuthNone) - } - - if _, err := conn.Write(buf); err != nil { - return nil, errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return nil, errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - if buf[0] != 5 { - return nil, errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0]))) - } - if buf[1] == 0xff { - return nil, errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication") - } - - if buf[1] == socks5AuthPassword { - buf = buf[:0] - buf = append(buf, 1 /* password protocol version */) - buf = append(buf, uint8(len(s.user))) - buf = append(buf, s.user...) - buf = append(buf, uint8(len(s.password))) - buf = append(buf, s.password...) - - if _, err := conn.Write(buf); err != nil { - return nil, errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return nil, errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if buf[1] != 0 { - return nil, errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password") - } - } - - buf = buf[:0] - buf = append(buf, socks5Version, socks5Connect, 0 /* reserved */) - - if ip := net.ParseIP(host); ip != nil { - if ip4 := ip.To4(); ip4 != nil { - buf = append(buf, socks5IP4) - ip = ip4 - } else { - buf = append(buf, socks5IP6) - } - buf = append(buf, ip...) - } else { - if len(host) > 255 { - return nil, errors.New("proxy: destination hostname too long: " + host) - } - buf = append(buf, socks5Domain) - buf = append(buf, byte(len(host))) - buf = append(buf, host...) - } - buf = append(buf, byte(port>>8), byte(port)) - - if _, err := conn.Write(buf); err != nil { - return nil, errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:4]); err != nil { - return nil, errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - failure := "unknown error" - if int(buf[1]) < len(socks5Errors) { - failure = socks5Errors[buf[1]] - } - - if len(failure) > 0 { - return nil, errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure) - } - - bytesToDiscard := 0 - switch buf[3] { - case socks5IP4: - bytesToDiscard = net.IPv4len - case socks5IP6: - bytesToDiscard = net.IPv6len - case socks5Domain: - _, err := io.ReadFull(conn, buf[:1]) - if err != nil { - return nil, errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - bytesToDiscard = int(buf[0]) - default: - return nil, errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr) - } - - if cap(buf) < bytesToDiscard { - buf = make([]byte, bytesToDiscard) - } else { - buf = buf[:bytesToDiscard] - } - if _, err := io.ReadFull(conn, buf); err != nil { - return nil, errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - // Also need to discard the port number - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return nil, errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - closeConn = nil - return conn, nil -} diff --git a/graftcp-local/Makefile b/local/Makefile similarity index 61% rename from graftcp-local/Makefile rename to local/Makefile index ea72ed5..effc435 100644 --- a/graftcp-local/Makefile +++ b/local/Makefile @@ -1,8 +1,5 @@ -export GOPATH := $(CURDIR)/.gopath -export PATH := $(PATH):$(CURDIR)/.gopath/bin - ifneq ($(shell echo $(VERSION) | head -c 1), v) - VERSION=v0.3 + VERSION=v0.4 endif PREFIX = /usr/local @@ -10,21 +7,17 @@ BINDIR = $(PREFIX)/bin INSTALL = install -D -GO_IMPORT_PATH := github.com/hmgle/graftcp/graftcp-local - -all:: graftcp-local +TARGET = cmd/graftcp-local/graftcp-local cmd/mgraftcp/mgraftcp -graftcp-local: .gopath/.created $(wildcard *.go) - GO111MODULE=auto go build -ldflags "-s -w -X main.version=${VERSION}" $(GO_IMPORT_PATH) +all:: $(TARGET) -.gopath/.created: - rm -rf .gopath - mkdir -p $(dir .gopath/src/$(GO_IMPORT_PATH)) - ln -s $(CURDIR) .gopath/src/$(GO_IMPORT_PATH) - touch $@ +cmd/graftcp-local/graftcp-local: $(wildcard *.go) $(wildcard cmd/graftcp-local/*.go) + cd cmd/graftcp-local && go build -ldflags "-s -w -X main.version=${VERSION}" +cmd/mgraftcp/mgraftcp: $(wildcard *.go) $(wildcard cmd/mgraftcp/*.go) + cd cmd/mgraftcp && go build -ldflags "-s -w -X main.version=${VERSION}" -install:: graftcp-local +install:: cmd/graftcp-local/graftcp-local $(INSTALL) $< $(DESTDIR)$(BINDIR)/$< SYSTEMD_UNIT_DIR:=$(shell pkg-config --variable=systemdsystemunitdir systemd 2>/dev/null) @@ -49,11 +42,11 @@ uninstall_systemd:: uninstall:: -rm -f $(DESTDIR)$(BINDIR)/$< -install_service:: graftcp-local - ./graftcp-local -service install && ./graftcp-local -service start +install_service:: cmd/graftcp-local/graftcp-local + cmd/graftcp-local/graftcp-local -service install && cmd/graftcp-local/graftcp-local -service start -uninstall_service:: graftcp-local - ./graftcp-local -service stop && ./graftcp-local -service uninstall +uninstall_service:: cmd/graftcp-local/graftcp-local + cmd/graftcp-local/graftcp-local -service stop && cmd/graftcp-local/graftcp-local -service uninstall clean:: - -rm -rf graftcp-local .gopath + -rm -rf $(TARGET) diff --git a/graftcp-local/config.go b/local/cmd/graftcp-local/config.go similarity index 98% rename from graftcp-local/config.go rename to local/cmd/graftcp-local/config.go index a30751b..cfea88f 100644 --- a/graftcp-local/config.go +++ b/local/cmd/graftcp-local/config.go @@ -9,6 +9,7 @@ import ( "strconv" "strings" + "github.com/hmgle/graftcp/local" "github.com/jedisct1/dlog" ) @@ -71,7 +72,7 @@ func parseLine(line string) (key, val string) { func ParseConfigFile(path string, app *App) error { if path == "" { // try default config file "graftcp-local.conf" - exePath := GetExePath() + exePath := local.GetExePath() defaultConf := filepath.Dir(exePath) + "/graftcp-local.conf" if _, err := os.Stat(defaultConf); err == nil { dlog.Infof("find config: %s", defaultConf) diff --git a/graftcp-local/main.go b/local/cmd/graftcp-local/main.go similarity index 87% rename from graftcp-local/main.go rename to local/cmd/graftcp-local/main.go index 54920b5..d27c0e3 100644 --- a/graftcp-local/main.go +++ b/local/cmd/graftcp-local/main.go @@ -1,23 +1,22 @@ package main import ( - _flag "flag" + "flag" "fmt" "os" - "path/filepath" "syscall" - "context" - + "github.com/hmgle/graftcp/local" "github.com/jedisct1/dlog" "github.com/kardianos/service" ) var ( selectProxyMode string - version = "v0.3" + version = "v0.4" ) +// App for graftcp-local. type App struct { ListenAddr string Socks5Addr string @@ -27,6 +26,7 @@ type App struct { PipePath string } +// Start service. func (app *App) Start(s service.Service) error { if s != nil { go func() { @@ -41,7 +41,7 @@ func (app *App) Start(s service.Service) error { func (app *App) run() { var err error - l := NewLocal(app.ListenAddr, app.Socks5Addr, app.Socks5Username, app.Socks5Password, app.HTTPProxyAddr) + l := local.NewLocal(app.ListenAddr, app.Socks5Addr, app.Socks5Username, app.Socks5Password, app.HTTPProxyAddr) dlog.Infof("select_proxy_mode: %s", selectProxyMode) l.SetSelectMode(selectProxyMode) @@ -56,15 +56,13 @@ func (app *App) run() { l.Start() } +// Stop service. func (app *App) Stop(s service.Service) error { dlog.Noticef("graftcp-local stop") return nil } -func local_main(args []string, ctx ...context.Context) { - cmdName := filepath.Base(args[0]) - flag := _flag.NewFlagSet(cmdName, _flag.ExitOnError) - +func main() { var configFile string dlog.Init("graftcp-local", dlog.SeverityInfo, "") @@ -96,10 +94,7 @@ func local_main(args []string, ctx ...context.Context) { flag.StringVar(&configFile, "config", "", "Path to the configuration file") flag.StringVar(&app.PipePath, "pipepath", "/tmp/graftcplocal.fifo", "Pipe path for graftcp to send address info") v := flag.Bool("version", false, "Print the graftcp-local version information") - if err := flag.Parse(args[1:]); err != nil { - fmt.Printf("Wrong command line arguments for %s: %s\n", cmdName, err.Error()) - os.Exit(1) - } + flag.Parse() if *v { fmt.Printf("graftcp-local version %s\n", version) os.Exit(0) diff --git a/local/cmd/mgraftcp/main.go b/local/cmd/mgraftcp/main.go new file mode 100644 index 0000000..47f3d97 --- /dev/null +++ b/local/cmd/mgraftcp/main.go @@ -0,0 +1,104 @@ +package main + +// #cgo LDFLAGS: -L../../.. -lgraftcp +// +// #include +// +// static void *alloc_string_slice(int len) { +// return malloc(sizeof(char*)*len); +// } +// +// int client_main(int argc, char **argv); +import "C" +import ( + "log" + "os" + "strconv" + "strings" + "syscall" + "unsafe" + + "github.com/hmgle/graftcp/local" +) + +const ( + maxArgsLen = 0xfff +) + +func clientMain(args []string) int { + argc := C.int(len(args)) + + log.Printf("Got %v args: %v\n", argc, args) + + argv := (*[maxArgsLen]*C.char)(C.alloc_string_slice(argc)) + defer C.free(unsafe.Pointer(argv)) + + for i, arg := range args { + argv[i] = C.CString(arg) + defer C.free(unsafe.Pointer(argv[i])) + } + + returnValue := C.client_main(argc, (**C.char)(unsafe.Pointer(argv))) + return int(returnValue) +} + +func constructArgs(args []string) ([]string, []string) { + server := make([]string, 0, len(args)) + client := make([]string, 0, len(args)) + + isCommand := false + for _, arg := range args { + if isCommand { + client = append(client, arg) + } else { + if strings.HasPrefix(arg, "--server") { + server = append(server, strings.TrimPrefix(arg, "--server")) + } else if strings.HasPrefix(arg, "--client") { + client = append(client, strings.TrimPrefix(arg, "--client")) + } else { + isCommand = true + client = append(client, arg) + } + } + } + + return server, client +} + +func main() { + + // todo: we need special handle on args like '--help' which trigger os.Exit + // todo: randomly set and detect port number if no one specified + serverArgs, clientArgs := constructArgs(os.Args[1:]) + + clientArgs = append(os.Args[:1], clientArgs...) + + // TODO: config args + l := local.NewLocal(":0", "127.0.0.1:1080", "", "", "") + + pipePath := "/tmp/mgraftcp.fifo" + syscall.Mkfifo(pipePath, uint32(os.ModePerm)) + os.Chmod(pipePath, 0666) + var err error + l.FifoFd, err = os.OpenFile(pipePath, os.O_RDWR, 0) + if err != nil { + log.Fatalf("os.OpenFile(%s) err: %s", pipePath, err.Error()) + } + + go l.UpdateProcessAddrInfo() + ln, err := l.StartListen() + if err != nil { + log.Fatalf("l.StartListen err: %s", err.Error()) + } + go l.StartService(ln) + defer ln.Close() + + _, faddr := l.GetFAddr() + + var fixArgs []string + fixArgs = append(fixArgs, clientArgs[0]) + fixArgs = append(fixArgs, "-p", strconv.Itoa(faddr.Port), "-f", pipePath) + fixArgs = append(fixArgs, clientArgs[1:]...) + log.Printf("serverArgs: %+v, fixArgs: %+v\n", serverArgs, fixArgs) + os.Exit(clientMain(fixArgs)) +} diff --git a/graftcp-local/contrib/systemd/graftcp-local.service b/local/contrib/systemd/graftcp-local.service similarity index 100% rename from graftcp-local/contrib/systemd/graftcp-local.service rename to local/contrib/systemd/graftcp-local.service diff --git a/graftcp-local/example-graftcp-local.conf b/local/example-graftcp-local.conf similarity index 100% rename from graftcp-local/example-graftcp-local.conf rename to local/example-graftcp-local.conf diff --git a/graftcp-local/exe_path_go19.go b/local/exe_path_go19.go similarity index 93% rename from graftcp-local/exe_path_go19.go rename to local/exe_path_go19.go index 882f332..4ca253a 100644 --- a/graftcp-local/exe_path_go19.go +++ b/local/exe_path_go19.go @@ -1,6 +1,6 @@ // +build go1.9 -package main +package local import "os" diff --git a/graftcp-local/exe_path_not_go19.go b/local/exe_path_not_go19.go similarity index 92% rename from graftcp-local/exe_path_not_go19.go rename to local/exe_path_not_go19.go index 3a1ead0..2942ec3 100644 --- a/graftcp-local/exe_path_not_go19.go +++ b/local/exe_path_not_go19.go @@ -1,6 +1,6 @@ // +build !go1.9 -package main +package local // GetExePath returns the path name for the executable that started // the current process. diff --git a/local/go.mod b/local/go.mod new file mode 100644 index 0000000..8256a35 --- /dev/null +++ b/local/go.mod @@ -0,0 +1,9 @@ +module github.com/hmgle/graftcp/local + +go 1.16 + +require ( + github.com/jedisct1/dlog v0.0.0-20210101122416-354ffe815216 + github.com/kardianos/service v1.2.0 + golang.org/x/net v0.0.0-20210614182718-04defd469f4e +) diff --git a/local/go.sum b/local/go.sum new file mode 100644 index 0000000..a495e32 --- /dev/null +++ b/local/go.sum @@ -0,0 +1,16 @@ +github.com/hashicorp/go-syslog v1.0.0 h1:KaodqZuhUoZereWVIYmpUgZysurB1kBLX2j0MwMrUAE= +github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= +github.com/jedisct1/dlog v0.0.0-20210101122416-354ffe815216 h1:31uZUKhZFZGKTg8GsKXBNIcK9TxjXEk2hg+rSKgGDI4= +github.com/jedisct1/dlog v0.0.0-20210101122416-354ffe815216/go.mod h1:CIy7i6SX94LqHB4I4V8JTHovTxZJoQfH1DH31XYNfcs= +github.com/kardianos/service v1.2.0 h1:bGuZ/epo3vrt8IPC7mnKQolqFeYJb7Cs8Rk4PSOBB/g= +github.com/kardianos/service v1.2.0/go.mod h1:CIMRFEJVL+0DS1a3Nx06NaMn4Dz63Ng6O7dl0qH0zVM= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e h1:XpT3nA5TvE525Ne3hInMh6+GETgn27Zfm9dxsThnX2Q= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201231184435-2d18734c6014/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da h1:b3NXsE2LusjYGGjL5bxEVZZORm/YEFFrWFjR8eFrw/c= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/graftcp-local/http_proxy.go b/local/http_proxy.go similarity index 99% rename from graftcp-local/http_proxy.go rename to local/http_proxy.go index 4cea823..8597f39 100644 --- a/graftcp-local/http_proxy.go +++ b/local/http_proxy.go @@ -1,4 +1,4 @@ -package main +package local import ( "bufio" diff --git a/graftcp-local/local.go b/local/local.go similarity index 87% rename from graftcp-local/local.go rename to local/local.go index 30216be..29b92ce 100644 --- a/graftcp-local/local.go +++ b/local/local.go @@ -1,4 +1,4 @@ -package main +package local import ( "bufio" @@ -30,6 +30,7 @@ const ( DirectMode ) +// Local ... type Local struct { faddr *net.TCPAddr // Frontend address: graftcp-local address @@ -44,6 +45,12 @@ type Local struct { selectMode modeT } +// GetFAddr return faddrString and faddr of l. +func (l *Local) GetFAddr() (faddrString string, faddr *net.TCPAddr) { + return l.faddrString, l.faddr +} + +// NewLocal ... func NewLocal(listenAddr, socks5Addr, socks5Username, socks5PassWord, httpProxyAddr string) *Local { listenTCPAddr, err := net.ResolveTCPAddr("tcp", listenAddr) if err != nil { @@ -138,14 +145,26 @@ func (l *Local) proxySelector() proxy.Dialer { } } -func (l *Local) Start() { - ln, err := net.ListenTCP("tcp", l.faddr) +// StartListen start listening. +func (l *Local) StartListen() (ln *net.TCPListener, err error) { + ln, err = net.ListenTCP("tcp", l.faddr) if err != nil { dlog.Fatalf("net.ListenTCP(%s) err: %s", l.faddr.String(), err.Error()) + return } - defer ln.Close() dlog.Infof("graftcp-local start listening %s...", l.faddr.String()) + if l.faddr.Port == 0 { + l.faddrString = ln.Addr().String() + l.faddr, err = net.ResolveTCPAddr("tcp", l.faddrString) + if err != nil { + dlog.Errorf("net.ResolveTCPAddr err: %s", err.Error()) + } + } + return +} +// StartService start service. +func (l *Local) StartService(ln *net.TCPListener) { for { conn, err := ln.AcceptTCP() if err != nil { @@ -156,6 +175,15 @@ func (l *Local) Start() { } } +// Start listening and service. +func (l *Local) Start() { + ln, _ := l.StartListen() + defer ln.Close() + dlog.Infof("graftcp-local start listening %s...", l.faddr.String()) + + l.StartService(ln) +} + func getPidByAddr(localAddr, remoteAddr string, isTCP6 bool) (pid string, destAddr string) { inode, err := getInodeByAddrs(localAddr, remoteAddr, isTCP6) if err != nil { @@ -182,6 +210,7 @@ func getPidByAddr(localAddr, remoteAddr string, isTCP6 bool) (pid string, destAd return } +// HandleConn handle conn. func (l *Local) HandleConn(conn net.Conn) error { raddr := conn.RemoteAddr() var isTCP6 bool @@ -230,6 +259,7 @@ func pipe(dst, src net.Conn, c chan int64) { c <- n } +// UpdateProcessAddrInfo update process address info. func (l *Local) UpdateProcessAddrInfo() { r := bufio.NewReader(l.FifoFd) for { diff --git a/graftcp-local/proc_mutex_map.go b/local/proc_mutex_map.go similarity index 98% rename from graftcp-local/proc_mutex_map.go rename to local/proc_mutex_map.go index 7fa4551..0d70f30 100644 --- a/graftcp-local/proc_mutex_map.go +++ b/local/proc_mutex_map.go @@ -1,6 +1,6 @@ // +build !go1.9 -package main +package local import "sync" diff --git a/graftcp-local/proc_sync_map.go b/local/proc_sync_map.go similarity index 98% rename from graftcp-local/proc_sync_map.go rename to local/proc_sync_map.go index 1e61dee..6517126 100644 --- a/graftcp-local/proc_sync_map.go +++ b/local/proc_sync_map.go @@ -1,6 +1,6 @@ // +build go1.9 -package main +package local import "sync" diff --git a/graftcp-local/util.go b/local/util.go similarity index 99% rename from graftcp-local/util.go rename to local/util.go index 54a07e1..2d67d02 100644 --- a/graftcp-local/util.go +++ b/local/util.go @@ -1,4 +1,4 @@ -package main +package local import ( "encoding/binary"