From 95425b79ae947706402a52a5a0f17e3cd5f62bc5 Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Tue, 17 Dec 2019 20:30:21 +0300 Subject: [PATCH 01/33] Implement visor restart from hypervisor --- cmd/skywire-visor/commands/root.go | 11 ++- pkg/hypervisor/hypervisor.go | 13 +++ pkg/restart/restart.go | 139 +++++++++++++++++++++++++++++ pkg/router/routerclient/client.go | 2 +- pkg/visor/rpc.go | 16 ++++ pkg/visor/rpc_client.go | 17 +++- pkg/visor/visor.go | 22 ++--- 7 files changed, 201 insertions(+), 19 deletions(-) create mode 100644 pkg/restart/restart.go diff --git a/cmd/skywire-visor/commands/root.go b/cmd/skywire-visor/commands/root.go index 1b49da606..b0213cce7 100644 --- a/cmd/skywire-visor/commands/root.go +++ b/cmd/skywire-visor/commands/root.go @@ -23,6 +23,7 @@ import ( "github.com/spf13/cobra" "github.com/SkycoinProject/skywire-mainnet/internal/utclient" + "github.com/SkycoinProject/skywire-mainnet/pkg/restart" "github.com/SkycoinProject/skywire-mainnet/pkg/util/pathutil" "github.com/SkycoinProject/skywire-mainnet/pkg/visor" ) @@ -46,6 +47,7 @@ type runCfg struct { masterLogger *logging.MasterLogger conf visor.Config node *visor.Node + restartCtx *restart.Context } var cfg *runCfg @@ -73,6 +75,13 @@ func init() { rootCmd.Flags().BoolVarP(&cfg.cfgFromStdin, "stdin", "i", false, "read config from STDIN") rootCmd.Flags().StringVarP(&cfg.profileMode, "profile", "p", "none", "enable profiling with pprof. Mode: none or one of: [cpu, mem, mutex, block, trace, http]") rootCmd.Flags().StringVarP(&cfg.port, "port", "", "6060", "port for http-mode of pprof") + + restartCtx, err := restart.CaptureContext() + if err != nil { + log.Printf("Failed to capture context: %v", err) + } else { + cfg.restartCtx = restartCtx + } } // Execute executes root CLI command. @@ -148,7 +157,7 @@ func (cfg *runCfg) readConfig() *runCfg { } func (cfg *runCfg) runNode() *runCfg { - node, err := visor.NewNode(&cfg.conf, cfg.masterLogger) + node, err := visor.NewNode(&cfg.conf, cfg.masterLogger, cfg.restartCtx) if err != nil { cfg.logger.Fatal("Failed to initialize node: ", err) } diff --git a/pkg/hypervisor/hypervisor.go b/pkg/hypervisor/hypervisor.go index 5df044407..c4170d32b 100644 --- a/pkg/hypervisor/hypervisor.go +++ b/pkg/hypervisor/hypervisor.go @@ -151,6 +151,7 @@ func (m *Node) ServeHTTP(w http.ResponseWriter, req *http.Request) { r.Put("/nodes/{pk}/routes/{rid}", m.putRoute()) r.Delete("/nodes/{pk}/routes/{rid}", m.deleteRoute()) r.Get("/nodes/{pk}/loops", m.getLoops()) + r.Get("/nodes/{pk}/restart", m.restart()) }) }) r.ServeHTTP(w, req) @@ -569,6 +570,18 @@ func (m *Node) getLoops() http.HandlerFunc { }) } +// NOTE: Reply comes with a delay, because of check if new executable is started successfully. +func (m *Node) restart() http.HandlerFunc { + return m.withCtx(m.nodeCtx, func(w http.ResponseWriter, r *http.Request, ctx *httpCtx) { + if err := ctx.RPC.Restart(); err != nil { + httputil.WriteJSON(w, r, http.StatusInternalServerError, err) + return + } + + httputil.WriteJSON(w, r, http.StatusOK, true) + }) +} + /* <<< Helper functions >>> */ diff --git a/pkg/restart/restart.go b/pkg/restart/restart.go new file mode 100644 index 000000000..e7087d7f5 --- /dev/null +++ b/pkg/restart/restart.go @@ -0,0 +1,139 @@ +package restart + +import ( + "errors" + "log" + "os" + "os/exec" + "path/filepath" + "time" + + "github.com/SkycoinProject/skycoin/src/util/logging" +) + +var ( + // ErrMalformedArgs is returned when executable args are malformed. + ErrMalformedArgs = errors.New("malformed args") +) + +const defaultCheckDelay = 5 * time.Second + +// Context describes data required for restarting visor. +type Context struct { + log *logging.Logger + checkDelay time.Duration + workingDirectory string + args []string +} + +// CaptureContext captures data required for restarting visor. +// Data used by CaptureContext must not be modified before, +// therefore calling CaptureContext immediately after starting executable is recommended. +func CaptureContext() (*Context, error) { + wd, err := os.Getwd() + if err != nil { + return nil, err + } + + args := os.Args + + context := &Context{ + checkDelay: defaultCheckDelay, + workingDirectory: wd, + args: args, + } + + return context, nil +} + +// RegisterLogger registers a logger instead of standard one. +func (c *Context) RegisterLogger(logger *logging.Logger) { + c.log = logger +} + +// SetCheckDelay sets a check delay instead of standard one. +func (c *Context) SetCheckDelay(delay time.Duration) { + c.checkDelay = delay +} + +// Restart restarts executable using Context. +// Should not be called from a goroutine. +func (c *Context) Restart() error { + if len(c.args) == 0 { + return ErrMalformedArgs + } + + executableRelPath := c.args[0] + executableAbsPath := filepath.Join(c.workingDirectory, executableRelPath) + + c.infoLogger()("Starting new instance of executable (path: %q)", executableAbsPath) + + errCh := c.start(executableAbsPath) + + ticker := time.NewTicker(c.checkDelay) + defer ticker.Stop() + + select { + case err := <-errCh: + c.errorLogger()("Failed to start new instance: %v", err) + return err + case <-ticker.C: + c.infoLogger()("New instance started successfully, exiting") + os.Exit(0) + + // unreachable + return nil + } +} + +func (c *Context) start(path string) chan error { + errCh := make(chan error, 1) + + go func(path string) { + normalizedPath, err := exec.LookPath(path) + if err != nil { + errCh <- err + return + } + + if len(c.args) == 0 { + errCh <- ErrMalformedArgs + return + } + + args := c.args[1:] + cmd := exec.Command(normalizedPath, args...) + + if err := cmd.Start(); err != nil { + errCh <- err + return + } + + if err := cmd.Wait(); err != nil { + errCh <- err + return + } + }(path) + + return errCh +} + +func (c *Context) infoLogger() func(string, ...interface{}) { + if c.log != nil { + return c.log.Infof + } + + logger := log.New(os.Stdout, "[INFO] ", log.LstdFlags) + + return logger.Printf +} + +func (c *Context) errorLogger() func(string, ...interface{}) { + if c.log != nil { + return c.log.Errorf + } + + logger := log.New(os.Stdout, "[ERROR] ", log.LstdFlags) + + return logger.Printf +} diff --git a/pkg/router/routerclient/client.go b/pkg/router/routerclient/client.go index ced537a60..dc4c6b66c 100644 --- a/pkg/router/routerclient/client.go +++ b/pkg/router/routerclient/client.go @@ -15,7 +15,7 @@ const rpcName = "RPCGateway" // Client is an RPC client for router. type Client struct { - tr *dmsg.Transport + tr *dmsg.Stream rpc *rpc.Client } diff --git a/pkg/visor/rpc.go b/pkg/visor/rpc.go index 10c5f55bf..97e7b6691 100644 --- a/pkg/visor/rpc.go +++ b/pkg/visor/rpc.go @@ -29,6 +29,9 @@ var ( // ErrNotFound is returned when a requested resource is not found. ErrNotFound = errors.New("not found") + + // ErrMalformedRestartContext is returned when restart context is malformed. + ErrMalformedRestartContext = errors.New("restart context is malformed") ) // RPC defines RPC methods for Node. @@ -390,3 +393,16 @@ func (r *RPC) Loops(_ *struct{}, out *[]LoopInfo) error { *out = loops return nil } + +/* + <<< VISOR MANAGEMENT >>> +*/ + +// Restart restarts visor. +func (r *RPC) Restart(_ *struct{}, _ *struct{}) error { + if r.node.restartCtx == nil { + return ErrMalformedRestartContext + } + + return r.node.restartCtx.Restart() +} diff --git a/pkg/visor/rpc_client.go b/pkg/visor/rpc_client.go index e470bd190..ea5e15c59 100644 --- a/pkg/visor/rpc_client.go +++ b/pkg/visor/rpc_client.go @@ -9,13 +9,12 @@ import ( "sync" "time" - "github.com/SkycoinProject/skywire-mainnet/pkg/app2" - "github.com/SkycoinProject/skywire-mainnet/pkg/router" - "github.com/SkycoinProject/dmsg/cipher" "github.com/SkycoinProject/skycoin/src/util/logging" "github.com/google/uuid" + "github.com/SkycoinProject/skywire-mainnet/pkg/app2" + "github.com/SkycoinProject/skywire-mainnet/pkg/router" "github.com/SkycoinProject/skywire-mainnet/pkg/routing" "github.com/SkycoinProject/skywire-mainnet/pkg/transport" ) @@ -49,6 +48,8 @@ type RPCClient interface { RemoveRoutingRule(key routing.RouteID) error Loops() ([]LoopInfo, error) + + Restart() error } // RPCClient provides methods to call an RPC Server. @@ -221,6 +222,11 @@ func (rc *rpcClient) Loops() ([]LoopInfo, error) { return loops, err } +// Restart calls Restart. +func (rc *rpcClient) Restart() error { + return rc.Call("Restart", &struct{}{}, &struct{}{}) +} + // MockRPCClient mocks RPCClient. type mockRPCClient struct { startedAt time.Time @@ -528,3 +534,8 @@ func (mc *mockRPCClient) Loops() ([]LoopInfo, error) { return loops, nil } + +// Restart implements RPCClient. +func (mc *mockRPCClient) Restart() error { + return nil +} diff --git a/pkg/visor/visor.go b/pkg/visor/visor.go index 703ec9565..e88e288da 100644 --- a/pkg/visor/visor.go +++ b/pkg/visor/visor.go @@ -6,7 +6,6 @@ import ( "context" "errors" "fmt" - "io" "net" "net/rpc" "os" @@ -20,7 +19,6 @@ import ( "time" "github.com/SkycoinProject/dmsg" - "github.com/SkycoinProject/dmsg/cipher" "github.com/SkycoinProject/dmsg/noise" "github.com/SkycoinProject/skycoin/src/util/logging" @@ -28,6 +26,7 @@ import ( "github.com/SkycoinProject/skywire-mainnet/pkg/app2/appnet" "github.com/SkycoinProject/skywire-mainnet/pkg/app2/appserver" "github.com/SkycoinProject/skywire-mainnet/pkg/dmsgpty" + "github.com/SkycoinProject/skywire-mainnet/pkg/restart" "github.com/SkycoinProject/skywire-mainnet/pkg/routefinder/rfclient" "github.com/SkycoinProject/skywire-mainnet/pkg/router" "github.com/SkycoinProject/skywire-mainnet/pkg/routing" @@ -67,18 +66,11 @@ type AppState struct { Status AppStatus `json:"status"` } -// PacketRouter performs routing of the skywire packets. -type PacketRouter interface { - io.Closer - Serve(ctx context.Context) error - SetupIsTrusted(sPK cipher.PubKey) bool -} - // Node provides messaging runtime for Apps by setting up all // necessary connections and performing messaging gateway functions. type Node struct { conf *Config - router PacketRouter + router router.Router n *snet.Network tm *transport.Manager rt routing.Table @@ -91,7 +83,8 @@ type Node struct { localPath string appsConf []AppConfig - startedAt time.Time + startedAt time.Time + restartCtx *restart.Context pidMu sync.Mutex @@ -102,12 +95,13 @@ type Node struct { } // NewNode constructs new Node. -func NewNode(config *Config, masterLogger *logging.MasterLogger) (*Node, error) { +func NewNode(config *Config, masterLogger *logging.MasterLogger, restartCtx *restart.Context) (*Node, error) { ctx := context.Background() node := &Node{ conf: config, procManager: appserver.NewProcManager(logging.MustGetLogger("proc_manager")), + restartCtx: restartCtx, } node.Logger = masterLogger @@ -430,8 +424,8 @@ func (node *Node) SpawnApp(config *AppConfig, startCh chan<- struct{}) (err erro appCfg := appcommon.Config{ Name: config.App, Version: config.Version, - SockFile: node.config.AppServerSockFile, - VisorPK: node.config.Node.StaticPubKey.Hex(), + SockFile: node.conf.AppServerSockFile, + VisorPK: node.conf.Node.StaticPubKey.Hex(), BinaryDir: node.appsPath, WorkDir: filepath.Join(node.localPath, config.App, fmt.Sprintf("v%s", config.Version)), } From f6a2c0e45f5ddaedadc5dbbf1f059d29bb31fb14 Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Tue, 17 Dec 2019 21:56:39 +0300 Subject: [PATCH 02/33] Implement tests for visor restart from hypervisor --- pkg/restart/restart.go | 22 ++++++++--- pkg/restart/restart_test.go | 79 +++++++++++++++++++++++++++++++++++++ pkg/visor/config.go | 2 + pkg/visor/visor.go | 10 ++++- 4 files changed, 106 insertions(+), 7 deletions(-) create mode 100644 pkg/restart/restart_test.go diff --git a/pkg/restart/restart.go b/pkg/restart/restart.go index e7087d7f5..b8013515c 100644 --- a/pkg/restart/restart.go +++ b/pkg/restart/restart.go @@ -16,7 +16,7 @@ var ( ErrMalformedArgs = errors.New("malformed args") ) -const defaultCheckDelay = 5 * time.Second +const DefaultCheckDelay = 5 * time.Second // Context describes data required for restarting visor. type Context struct { @@ -24,6 +24,7 @@ type Context struct { checkDelay time.Duration workingDirectory string args []string + needsExit bool // disable in (c *Context) Restart() tests } // CaptureContext captures data required for restarting visor. @@ -38,9 +39,10 @@ func CaptureContext() (*Context, error) { args := os.Args context := &Context{ - checkDelay: defaultCheckDelay, + checkDelay: DefaultCheckDelay, workingDirectory: wd, args: args, + needsExit: true, } return context, nil @@ -48,12 +50,16 @@ func CaptureContext() (*Context, error) { // RegisterLogger registers a logger instead of standard one. func (c *Context) RegisterLogger(logger *logging.Logger) { - c.log = logger + if c != nil { + c.log = logger + } } // SetCheckDelay sets a check delay instead of standard one. func (c *Context) SetCheckDelay(delay time.Duration) { - c.checkDelay = delay + if c != nil { + c.checkDelay = delay + } } // Restart restarts executable using Context. @@ -79,9 +85,11 @@ func (c *Context) Restart() error { return err case <-ticker.C: c.infoLogger()("New instance started successfully, exiting") - os.Exit(0) + if c.needsExit { + os.Exit(0) + } - // unreachable + // unreachable unless run in tests return nil } } @@ -90,6 +98,8 @@ func (c *Context) start(path string) chan error { errCh := make(chan error, 1) go func(path string) { + defer close(errCh) + normalizedPath, err := exec.LookPath(path) if err != nil { errCh <- err diff --git a/pkg/restart/restart_test.go b/pkg/restart/restart_test.go new file mode 100644 index 000000000..92d47227c --- /dev/null +++ b/pkg/restart/restart_test.go @@ -0,0 +1,79 @@ +package restart + +import ( + "os" + "testing" + "time" + + "github.com/SkycoinProject/skycoin/src/util/logging" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCaptureContext(t *testing.T) { + cc, err := CaptureContext() + require.NoError(t, err) + + wd, err := os.Getwd() + assert.NoError(t, err) + + require.Equal(t, wd, cc.workingDirectory) + require.Equal(t, DefaultCheckDelay, cc.checkDelay) + require.Equal(t, os.Args, cc.args) + require.Nil(t, cc.log) + require.True(t, cc.needsExit) +} + +func TestContext_RegisterLogger(t *testing.T) { + cc, err := CaptureContext() + require.NoError(t, err) + require.Nil(t, cc.log) + + logger := logging.MustGetLogger("test") + cc.RegisterLogger(logger) + require.Equal(t, logger, cc.log) +} + +func TestContext_Restart(t *testing.T) { + cc, err := CaptureContext() + require.NoError(t, err) + assert.NotZero(t, len(cc.args)) + + cc.workingDirectory = "" + cc.needsExit = false + + t.Run("executable started", func(t *testing.T) { + cmd := "touch" + path := "/tmp/test_restart" + args := []string{cmd, path} + cc.args = args + + assert.NoError(t, cc.Restart()) + assert.NoError(t, os.Remove(path)) + }) + + t.Run("bad args", func(t *testing.T) { + cmd := "bad_command" + args := []string{cmd} + cc.args = args + + // TODO(nkryuchkov): Check if it works on Linux and Windows, if not then change the error text. + assert.EqualError(t, cc.Restart(), `exec: "bad_command": executable file not found in $PATH`) + }) + + t.Run("empty args", func(t *testing.T) { + cc.args = nil + + assert.Equal(t, ErrMalformedArgs, cc.Restart()) + }) +} + +func TestContext_SetCheckDelay(t *testing.T) { + cc, err := CaptureContext() + require.NoError(t, err) + require.Equal(t, DefaultCheckDelay, cc.checkDelay) + + const oneSecond = 1 * time.Second + cc.SetCheckDelay(oneSecond) + require.Equal(t, oneSecond, cc.checkDelay) +} diff --git a/pkg/visor/config.go b/pkg/visor/config.go index 69e54d808..c4c1bbbb3 100644 --- a/pkg/visor/config.go +++ b/pkg/visor/config.go @@ -73,6 +73,8 @@ type Config struct { Interfaces InterfaceConfig `json:"interfaces"` AppServerSockFile string `json:"app_server_sock_file"` + + RestartCheckDelay string `json:"restart_check_delay"` } // MessagingConfig returns config for dmsg client. diff --git a/pkg/visor/visor.go b/pkg/visor/visor.go index e88e288da..8916877c2 100644 --- a/pkg/visor/visor.go +++ b/pkg/visor/visor.go @@ -101,12 +101,20 @@ func NewNode(config *Config, masterLogger *logging.MasterLogger, restartCtx *res node := &Node{ conf: config, procManager: appserver.NewProcManager(logging.MustGetLogger("proc_manager")), - restartCtx: restartCtx, } node.Logger = masterLogger node.logger = node.Logger.PackageLogger("skywire") + restartCheckDelay, err := time.ParseDuration(config.RestartCheckDelay) + if err == nil { + restartCtx.SetCheckDelay(restartCheckDelay) + } + + restartCtx.RegisterLogger(node.logger) + + node.restartCtx = restartCtx + pk := config.Node.StaticPubKey sk := config.Node.StaticSecKey From 01ae1ba33f26f7f48418601529778bbcd91847de Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Tue, 17 Dec 2019 21:59:38 +0300 Subject: [PATCH 03/33] Make minor linter improvements --- pkg/restart/restart.go | 1 + pkg/restart/restart_test.go | 1 + 2 files changed, 2 insertions(+) diff --git a/pkg/restart/restart.go b/pkg/restart/restart.go index b8013515c..18be8a302 100644 --- a/pkg/restart/restart.go +++ b/pkg/restart/restart.go @@ -85,6 +85,7 @@ func (c *Context) Restart() error { return err case <-ticker.C: c.infoLogger()("New instance started successfully, exiting") + if c.needsExit { os.Exit(0) } diff --git a/pkg/restart/restart_test.go b/pkg/restart/restart_test.go index 92d47227c..80e291c92 100644 --- a/pkg/restart/restart_test.go +++ b/pkg/restart/restart_test.go @@ -74,6 +74,7 @@ func TestContext_SetCheckDelay(t *testing.T) { require.Equal(t, DefaultCheckDelay, cc.checkDelay) const oneSecond = 1 * time.Second + cc.SetCheckDelay(oneSecond) require.Equal(t, oneSecond, cc.checkDelay) } From 3a73eea9785a5b5839eb19f4f7a44d8d0c150b05 Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Mon, 23 Dec 2019 16:11:04 +0400 Subject: [PATCH 04/33] Fix linter errors --- pkg/restart/restart.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pkg/restart/restart.go b/pkg/restart/restart.go index 18be8a302..00837ce48 100644 --- a/pkg/restart/restart.go +++ b/pkg/restart/restart.go @@ -16,6 +16,7 @@ var ( ErrMalformedArgs = errors.New("malformed args") ) +// DefaultCheckDelay is a default delay for checking if a new instance is started successfully. const DefaultCheckDelay = 5 * time.Second // Context describes data required for restarting visor. @@ -113,7 +114,7 @@ func (c *Context) start(path string) chan error { } args := c.args[1:] - cmd := exec.Command(normalizedPath, args...) + cmd := exec.Command(normalizedPath, args...) // nolint:gosec if err := cmd.Start(); err != nil { errCh <- err From b1caac53d4a8d4a927bca3042266d3a82b0b0bb8 Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Tue, 24 Dec 2019 16:06:10 +0400 Subject: [PATCH 05/33] Forbid simultaneous restarts --- pkg/restart/restart.go | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/pkg/restart/restart.go b/pkg/restart/restart.go index 00837ce48..3a452047b 100644 --- a/pkg/restart/restart.go +++ b/pkg/restart/restart.go @@ -6,14 +6,17 @@ import ( "os" "os/exec" "path/filepath" + "sync/atomic" "time" - "github.com/SkycoinProject/skycoin/src/util/logging" + "github.com/sirupsen/logrus" ) var ( // ErrMalformedArgs is returned when executable args are malformed. ErrMalformedArgs = errors.New("malformed args") + // ErrAlreadyRestarting is returned on restarting attempt when restarting is in progress. + ErrAlreadyRestarting = errors.New("already restarting") ) // DefaultCheckDelay is a default delay for checking if a new instance is started successfully. @@ -21,11 +24,12 @@ const DefaultCheckDelay = 5 * time.Second // Context describes data required for restarting visor. type Context struct { - log *logging.Logger + log logrus.FieldLogger checkDelay time.Duration workingDirectory string args []string needsExit bool // disable in (c *Context) Restart() tests + isRestarting int32 } // CaptureContext captures data required for restarting visor. @@ -50,7 +54,7 @@ func CaptureContext() (*Context, error) { } // RegisterLogger registers a logger instead of standard one. -func (c *Context) RegisterLogger(logger *logging.Logger) { +func (c *Context) RegisterLogger(logger logrus.FieldLogger) { if c != nil { c.log = logger } @@ -64,8 +68,13 @@ func (c *Context) SetCheckDelay(delay time.Duration) { } // Restart restarts executable using Context. -// Should not be called from a goroutine. func (c *Context) Restart() error { + if atomic.CompareAndSwapInt32(&c.isRestarting, 0, 1) { + return ErrAlreadyRestarting + } + + defer atomic.StoreInt32(&c.isRestarting, 0) + if len(c.args) == 0 { return ErrMalformedArgs } From e2ea0edc971dd9a464e23ad24eef0b1a01980677 Mon Sep 17 00:00:00 2001 From: Sir Darkrengarius Date: Tue, 24 Dec 2019 15:19:32 +0300 Subject: [PATCH 06/33] Remove SSH apps from default visor config generation --- cmd/skywire-cli/commands/node/gen-config.go | 20 -------------------- internal/skyenv/const.go | 9 ++------- 2 files changed, 2 insertions(+), 27 deletions(-) diff --git a/cmd/skywire-cli/commands/node/gen-config.go b/cmd/skywire-cli/commands/node/gen-config.go index 8cc27ab4a..a9f1141f6 100644 --- a/cmd/skywire-cli/commands/node/gen-config.go +++ b/cmd/skywire-cli/commands/node/gen-config.go @@ -98,9 +98,7 @@ func defaultConfig() *visor.Config { //passcode := base64.StdEncoding.Strict().EncodeToString(cipher.RandByte(8)) conf.Apps = []visor.AppConfig{ defaultSkychatConfig(), - defaultSkysshConfig(), defaultSkyproxyConfig(""), - defaultSkysshClientConfig(), defaultSkyproxyClientConfig(), } conf.TrustedNodes = []cipher.PubKey{} @@ -164,15 +162,6 @@ func defaultSkychatConfig() visor.AppConfig { } } -func defaultSkysshConfig() visor.AppConfig { - return visor.AppConfig{ - App: skyenv.SkysshName, - Version: skyenv.SkysshVersion, - AutoStart: true, - Port: routing.Port(skyenv.SkysshPort), - } -} - func defaultSkyproxyConfig(passcode string) visor.AppConfig { var args []string if passcode != "" { @@ -187,15 +176,6 @@ func defaultSkyproxyConfig(passcode string) visor.AppConfig { } } -func defaultSkysshClientConfig() visor.AppConfig { - return visor.AppConfig{ - App: skyenv.SkysshClientName, - Version: skyenv.SkysshVersion, - AutoStart: true, - Port: routing.Port(skyenv.SkysshClientPort), - } -} - func defaultSkyproxyClientConfig() visor.AppConfig { return visor.AppConfig{ App: skyenv.SkyproxyClientName, diff --git a/internal/skyenv/const.go b/internal/skyenv/const.go index 40593c086..d2d17c317 100644 --- a/internal/skyenv/const.go +++ b/internal/skyenv/const.go @@ -41,18 +41,13 @@ const ( SkychatPort = uint16(1) SkychatAddr = ":8000" - SkysshName = "SSH" - SkysshVersion = "1.0" - SkysshPort = uint16(2) + SkysshPort = uint16(2) SkyproxyName = "socksproxy" SkyproxyVersion = "1.0" SkyproxyPort = uint16(3) - SkysshClientName = "SSH-client" - SkysshClientVersion = "1.0" - SkysshClientPort = uint16(12) - SkysshClientAddr = ":2222" + SkysshClientAddr = ":2222" SkyproxyClientName = "socksproxy-client" SkyproxyClientVersion = "1.0" From a9264013b99bdf66c5b0482609d090c1ca63f474 Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Tue, 24 Dec 2019 16:45:42 +0400 Subject: [PATCH 07/33] Fix restart bug --- pkg/restart/restart.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/restart/restart.go b/pkg/restart/restart.go index 3a452047b..edeb68818 100644 --- a/pkg/restart/restart.go +++ b/pkg/restart/restart.go @@ -69,7 +69,7 @@ func (c *Context) SetCheckDelay(delay time.Duration) { // Restart restarts executable using Context. func (c *Context) Restart() error { - if atomic.CompareAndSwapInt32(&c.isRestarting, 0, 1) { + if !atomic.CompareAndSwapInt32(&c.isRestarting, 0, 1) { return ErrAlreadyRestarting } From b8e2cd0c9481abd59700565678948b466ed1e505 Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Tue, 24 Dec 2019 16:47:08 +0400 Subject: [PATCH 08/33] Add "already restarting" test case --- pkg/restart/restart_test.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/pkg/restart/restart_test.go b/pkg/restart/restart_test.go index 80e291c92..e0c118add 100644 --- a/pkg/restart/restart_test.go +++ b/pkg/restart/restart_test.go @@ -66,6 +66,25 @@ func TestContext_Restart(t *testing.T) { assert.Equal(t, ErrMalformedArgs, cc.Restart()) }) + + t.Run("already restarting", func(t *testing.T) { + cc.args = nil + + cmd := "touch" + path := "/tmp/test_restart" + args := []string{cmd, path} + cc.args = args + + ch := make(chan error, 1) + go func() { + ch <- cc.Restart() + }() + + assert.NoError(t, cc.Restart()) + assert.NoError(t, os.Remove(path)) + + assert.Equal(t, ErrAlreadyRestarting, <-ch) + }) } func TestContext_SetCheckDelay(t *testing.T) { From abcee9532b7d921d9be3aa93a00d4444d04e22a7 Mon Sep 17 00:00:00 2001 From: Sir Darkrengarius Date: Wed, 25 Dec 2019 16:28:22 +0300 Subject: [PATCH 09/33] Update vvendor --- Makefile | 4 +- vendor/github.com/SkycoinProject/dmsg/go.mod | 4 +- vendor/github.com/SkycoinProject/dmsg/go.sum | 5 +-- .../go-windows-terminal-sequences/README.md | 1 + .../sequences_dummy.go | 11 +++++ .../mattn/go-colorable/colorable_appengine.go | 6 +-- .../mattn/go-colorable/colorable_others.go | 6 +-- .../mattn/go-colorable/colorable_windows.go | 43 ++++--------------- .../mattn/go-colorable/noncolorable.go | 6 +-- vendor/modules.txt | 6 +-- 10 files changed, 38 insertions(+), 54 deletions(-) create mode 100644 vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go diff --git a/Makefile b/Makefile index 2a1764b94..4e0299571 100644 --- a/Makefile +++ b/Makefile @@ -31,9 +31,9 @@ config: ## Generate skywire.json clean: ## Clean project: remove created binaries and apps -rm -rf ./apps - -rm -f ./skywire-visor ./skywire-cli ./setup-node ./hypervisor ./SSH-cli + -rm -f ./skywire-visor ./skywire-cli ./setup-node ./hypervisor -install: ## Install `skywire-visor`, `skywire-cli`, `hypervisor`, `SSH-cli`, `dmsgpty` +install: ## Install `skywire-visor`, `skywire-cli`, `hypervisor`, `dmsgpty` ${OPTS} go install ./cmd/skywire-visor ./cmd/skywire-cli ./cmd/setup-node ./cmd/hypervisor ./cmd/therealssh-cli ./cmd/dmsgpty rerun: stop diff --git a/vendor/github.com/SkycoinProject/dmsg/go.mod b/vendor/github.com/SkycoinProject/dmsg/go.mod index a60278f79..72283c2b4 100644 --- a/vendor/github.com/SkycoinProject/dmsg/go.mod +++ b/vendor/github.com/SkycoinProject/dmsg/go.mod @@ -5,10 +5,8 @@ go 1.12 require ( github.com/SkycoinProject/skycoin v0.26.0 github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6 - github.com/mattn/go-colorable v0.1.4 // indirect - github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect github.com/sirupsen/logrus v1.4.2 - github.com/skycoin/skycoin v0.26.0 // indirect + github.com/skycoin/dmsg v0.0.0-20190805065636-70f4c32a994f github.com/stretchr/testify v1.3.0 golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 // indirect golang.org/x/net v0.0.0-20191014212845-da9a3fd4c582 diff --git a/vendor/github.com/SkycoinProject/dmsg/go.sum b/vendor/github.com/SkycoinProject/dmsg/go.sum index 5c54bb13d..037462e79 100644 --- a/vendor/github.com/SkycoinProject/dmsg/go.sum +++ b/vendor/github.com/SkycoinProject/dmsg/go.sum @@ -5,7 +5,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6 h1:u/UEqS66A5ckRmS4yNpjmVH56sVtS/RfclBAYocb4as= github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6/go.mod h1:1i71OnUq3iUe1ma7Lr6yG6/rjvM3emb6yoL7xLFzcVQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -14,8 +13,6 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= -github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4= @@ -24,6 +21,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/skycoin/dmsg v0.0.0-20190805065636-70f4c32a994f h1:WWjaxOXoj6oYelm67MNtJbg51HQALjKAyhs2WAHgpZs= +github.com/skycoin/dmsg v0.0.0-20190805065636-70f4c32a994f/go.mod h1:obZYZp8eKR7Xqz+KNhJdUE6Gvp6rEXbDO8YTlW2YXgU= github.com/skycoin/skycoin v0.26.0 h1:xDxe2r8AclMntZ550Y/vUQgwgLtwrf9Wu5UYiYcN5/o= github.com/skycoin/skycoin v0.26.0/go.mod h1:78nHjQzd8KG0jJJVL/j0xMmrihXi70ti63fh8vXScJw= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md b/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md index 949b77e30..195333e51 100644 --- a/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md @@ -26,6 +26,7 @@ The tool is sponsored by the [marvin + konsorten GmbH](http://www.konsorten.de). We thank all the authors who provided code to this library: * Felix Kollmann +* Nicolas Perraut ## License diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go new file mode 100644 index 000000000..df61a6f2f --- /dev/null +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go @@ -0,0 +1,11 @@ +// +build linux darwin + +package sequences + +import ( + "fmt" +) + +func EnableVirtualTerminalProcessing(stream uintptr, enable bool) error { + return fmt.Errorf("windows only package") +} diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go index 0b0aef837..1f28d773d 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_appengine.go +++ b/vendor/github.com/mattn/go-colorable/colorable_appengine.go @@ -9,7 +9,7 @@ import ( _ "github.com/mattn/go-isatty" ) -// NewColorable returns new instance of Writer which handles escape sequence. +// NewColorable return new instance of Writer which handle escape sequence. func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") @@ -18,12 +18,12 @@ func NewColorable(file *os.File) io.Writer { return file } -// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. +// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. func NewColorableStdout() io.Writer { return os.Stdout } -// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. +// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. func NewColorableStderr() io.Writer { return os.Stderr } diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go index 3fb771dcc..887f203dc 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_others.go +++ b/vendor/github.com/mattn/go-colorable/colorable_others.go @@ -10,7 +10,7 @@ import ( _ "github.com/mattn/go-isatty" ) -// NewColorable returns new instance of Writer which handles escape sequence. +// NewColorable return new instance of Writer which handle escape sequence. func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") @@ -19,12 +19,12 @@ func NewColorable(file *os.File) io.Writer { return file } -// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. +// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. func NewColorableStdout() io.Writer { return os.Stdout } -// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. +// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. func NewColorableStderr() io.Writer { return os.Stderr } diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go index 1bd628f25..404e10ca0 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -81,7 +81,7 @@ var ( procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") ) -// Writer provides colorable Writer to the console +// Writer provide colorable Writer to the console type Writer struct { out io.Writer handle syscall.Handle @@ -91,7 +91,7 @@ type Writer struct { rest bytes.Buffer } -// NewColorable returns new instance of Writer which handles escape sequence from File. +// NewColorable return new instance of Writer which handle escape sequence from File. func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") @@ -106,12 +106,12 @@ func NewColorable(file *os.File) io.Writer { return file } -// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. +// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. func NewColorableStdout() io.Writer { return NewColorable(os.Stdout) } -// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. +// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. func NewColorableStderr() io.Writer { return NewColorable(os.Stderr) } @@ -414,15 +414,7 @@ func doTitleSequence(er *bytes.Reader) error { return nil } -// returns Atoi(s) unless s == "" in which case it returns def -func atoiWithDefault(s string, def int) (int, error) { - if s == "" { - return def, nil - } - return strconv.Atoi(s) -} - -// Write writes data on console +// Write write data on console func (w *Writer) Write(data []byte) (n int, err error) { var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) @@ -508,7 +500,7 @@ loop: switch m { case 'A': - n, err = atoiWithDefault(buf.String(), 1) + n, err = strconv.Atoi(buf.String()) if err != nil { continue } @@ -516,7 +508,7 @@ loop: csbi.cursorPosition.y -= short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'B': - n, err = atoiWithDefault(buf.String(), 1) + n, err = strconv.Atoi(buf.String()) if err != nil { continue } @@ -524,7 +516,7 @@ loop: csbi.cursorPosition.y += short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'C': - n, err = atoiWithDefault(buf.String(), 1) + n, err = strconv.Atoi(buf.String()) if err != nil { continue } @@ -532,7 +524,7 @@ loop: csbi.cursorPosition.x += short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'D': - n, err = atoiWithDefault(buf.String(), 1) + n, err = strconv.Atoi(buf.String()) if err != nil { continue } @@ -565,9 +557,6 @@ loop: if err != nil { continue } - if n < 1 { - n = 1 - } procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = short(n - 1) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) @@ -646,20 +635,6 @@ loop: } procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'X': - n := 0 - if buf.Len() > 0 { - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - var cursor coord - var written dword - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'm': procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) attr := csbi.attributes diff --git a/vendor/github.com/mattn/go-colorable/noncolorable.go b/vendor/github.com/mattn/go-colorable/noncolorable.go index 95f2c6be2..9721e16f4 100644 --- a/vendor/github.com/mattn/go-colorable/noncolorable.go +++ b/vendor/github.com/mattn/go-colorable/noncolorable.go @@ -5,17 +5,17 @@ import ( "io" ) -// NonColorable holds writer but removes escape sequence. +// NonColorable hold writer but remove escape sequence. type NonColorable struct { out io.Writer } -// NewNonColorable returns new instance of Writer which removes escape sequence from Writer. +// NewNonColorable return new instance of Writer which remove escape sequence from Writer. func NewNonColorable(w io.Writer) io.Writer { return &NonColorable{out: w} } -// Write writes data on console +// Write write data on console func (w *NonColorable) Write(data []byte) (n int, err error) { er := bytes.NewReader(data) var bw [1]byte diff --git a/vendor/modules.txt b/vendor/modules.txt index ce09179bc..cf0988743 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,4 +1,4 @@ -# github.com/SkycoinProject/dmsg v0.0.0-20191106075825-cabc26522b11 => ../dmsg +# github.com/SkycoinProject/dmsg v0.0.0-20191106075825-cabc26522b11 github.com/SkycoinProject/dmsg github.com/SkycoinProject/dmsg/cipher github.com/SkycoinProject/dmsg/disc @@ -40,9 +40,9 @@ github.com/gorilla/handlers github.com/gorilla/securecookie # github.com/inconshreveable/mousetrap v1.0.0 github.com/inconshreveable/mousetrap -# github.com/konsorten/go-windows-terminal-sequences v1.0.1 +# github.com/konsorten/go-windows-terminal-sequences v1.0.2 github.com/konsorten/go-windows-terminal-sequences -# github.com/mattn/go-colorable v0.1.4 +# github.com/mattn/go-colorable v0.1.2 github.com/mattn/go-colorable # github.com/mattn/go-isatty v0.0.8 github.com/mattn/go-isatty From 53796362176f73c27d055ba7850e26bfe4b358be Mon Sep 17 00:00:00 2001 From: Sir Darkrengarius Date: Thu, 26 Dec 2019 10:16:51 +0300 Subject: [PATCH 10/33] Remove all SSH references from Makefile --- Makefile | 22 ++++------------------ 1 file changed, 4 insertions(+), 18 deletions(-) diff --git a/Makefile b/Makefile index 4e0299571..f82df6aef 100644 --- a/Makefile +++ b/Makefile @@ -34,7 +34,7 @@ clean: ## Clean project: remove created binaries and apps -rm -f ./skywire-visor ./skywire-cli ./setup-node ./hypervisor install: ## Install `skywire-visor`, `skywire-cli`, `hypervisor`, `dmsgpty` - ${OPTS} go install ./cmd/skywire-visor ./cmd/skywire-cli ./cmd/setup-node ./cmd/hypervisor ./cmd/therealssh-cli ./cmd/dmsgpty + ${OPTS} go install ./cmd/skywire-visor ./cmd/skywire-cli ./cmd/setup-node ./cmd/hypervisor ./cmd/dmsgpty rerun: stop ${OPTS} go build -race -o ./skywire-visor ./cmd/skywire-visor @@ -56,9 +56,6 @@ vendorcheck: ## Run vendorcheck GO111MODULE=off vendorcheck ./cmd/setup-node/... GO111MODULE=off vendorcheck ./cmd/skywire-cli/... GO111MODULE=off vendorcheck ./cmd/skywire-visor/... - # vendorcheck fails on ./cmd/therealssh-cli - # the problem is indirect dependency to github.com/sirupsen/logrus - #GO111MODULE=off vendorcheck ./cmd/therealssh-cli/... test: ## Run tests -go clean -testcache &>/dev/null @@ -91,31 +88,25 @@ host-apps: ## Build app ${OPTS} go build ${BUILD_OPTS} -o ./apps/helloworld.v1.0 ./cmd/apps/helloworld ${OPTS} go build ${BUILD_OPTS} -o ./apps/socksproxy.v1.0 ./cmd/apps/therealproxy ${OPTS} go build ${BUILD_OPTS} -o ./apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-client - ${OPTS} go build ${BUILD_OPTS} -o ./apps/SSH.v1.0 ./cmd/apps/therealssh - ${OPTS} go build ${BUILD_OPTS} -o ./apps/SSH-client.v1.0 ./cmd/apps/therealssh-client # Bin -bin: ## Build `skywire-visor`, `skywire-cli`, `hypervisor`, `SSH-cli` +bin: ## Build `skywire-visor`, `skywire-cli`, `hypervisor` ${OPTS} go build ${BUILD_OPTS} -o ./skywire-visor ./cmd/skywire-visor ${OPTS} go build ${BUILD_OPTS} -o ./skywire-cli ./cmd/skywire-cli ${OPTS} go build ${BUILD_OPTS} -o ./setup-node ./cmd/setup-node ${OPTS} go build ${BUILD_OPTS} -o ./dmsg-server ./cmd/dmsg-server ${OPTS} go build ${BUILD_OPTS} -o ./hypervisor ./cmd/hypervisor - ${OPTS} go build ${BUILD_OPTS} -o ./SSH-cli ./cmd/therealssh-cli ${OPTS} go build ${BUILD_OPTS} -o ./dmsgpty ./cmd/dmsgpty -release: ## Build `skywire-visor`, `skywire-cli`, `hypervisor`, `SSH-cli` and apps without -race flag +release: ## Build `skywire-visor`, `skywire-cli`, `hypervisor` and apps without -race flag ${OPTS} go build -o ./skywire-visor ./cmd/skywire-visor ${OPTS} go build -o ./skywire-cli ./cmd/skywire-cli ${OPTS} go build -o ./setup-node ./cmd/setup-node ${OPTS} go build -o ./hypervisor ./cmd/hypervisor - ${OPTS} go build -o ./SSH-cli ./cmd/therealssh-cli ${OPTS} go build -o ./apps/skychat.v1.0 ./cmd/apps/skychat ${OPTS} go build -o ./apps/helloworld.v1.0 ./cmd/apps/helloworld ${OPTS} go build -o ./apps/socksproxy.v1.0 ./cmd/apps/therealproxy ${OPTS} go build -o ./apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-client - ${OPTS} go build -o ./apps/SSH.v1.0 ./cmd/apps/therealssh - ${OPTS} go build -o ./apps/SSH-client.v1.0 ./cmd/apps/therealssh-client # Dockerized skywire-visor docker-image: ## Build docker image `skywire-runner` @@ -133,10 +124,8 @@ docker-apps: ## Build apps binaries for dockerized skywire-visor. `go build` wit -${DOCKER_OPTS} go build -race -o ./node/apps/helloworld.v1.0 ./cmd/apps/helloworld -${DOCKER_OPTS} go build -race -o ./node/apps/socksproxy.v1.0 ./cmd/apps/therealproxy -${DOCKER_OPTS} go build -race -o ./node/apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-client - -${DOCKER_OPTS} go build -race -o ./node/apps/SSH.v1.0 ./cmd/apps/therealssh - -${DOCKER_OPTS} go build -race -o ./node/apps/SSH-client.v1.0 ./cmd/apps/therealssh-client -docker-bin: ## Build `skywire-visor`, `skywire-cli`, `hypervisor`, `therealssh-cli`. `go build` with ${DOCKER_OPTS} +docker-bin: ## Build `skywire-visor`, `skywire-cli`, `hypervisor`. `go build` with ${DOCKER_OPTS} ${DOCKER_OPTS} go build -race -o ./node/skywire-visor ./cmd/skywire-visor docker-volume: dep docker-apps docker-bin bin ## Prepare docker volume for dockerized skywire-visor @@ -186,9 +175,6 @@ integration-run-messaging: ## Runs the messaging interactive testing environment integration-run-proxy: ## Runs the proxy interactive testing environment ./integration/run-proxy-env.sh -integration-run-ssh: ## Runs the ssh interactive testing environment - ./integration/run-ssh-env.sh - mod-comm: ## Comments the 'replace' rule in go.mod ./ci_scripts/go_mod_replace.sh comment go.mod From a67e3bc707c6d43071560d7076ba7b092cb8ea0e Mon Sep 17 00:00:00 2001 From: Sir Darkrengarius Date: Thu, 26 Dec 2019 10:29:04 +0300 Subject: [PATCH 11/33] Fix app server socket file generation for default config --- cmd/skywire-cli/commands/node/gen-config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/skywire-cli/commands/node/gen-config.go b/cmd/skywire-cli/commands/node/gen-config.go index a9f1141f6..3dba6f016 100644 --- a/cmd/skywire-cli/commands/node/gen-config.go +++ b/cmd/skywire-cli/commands/node/gen-config.go @@ -138,7 +138,7 @@ func defaultConfig() *visor.Config { conf.Interfaces.RPCAddress = "localhost:3435" - conf.AppServerSockFile = "app_server.sock" + conf.AppServerSockFile = "/tmp/visor_" + pk.Hex() + ".sock" return conf } From 985ccae70e54521bec5d78eacc01c778bbe86820 Mon Sep 17 00:00:00 2001 From: Sir Darkrengarius Date: Thu, 26 Dec 2019 10:54:10 +0300 Subject: [PATCH 12/33] Update vendor --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 7ce3b0da9..3b849bd2d 100644 --- a/go.mod +++ b/go.mod @@ -24,4 +24,4 @@ require ( golang.org/x/net v0.0.0-20191204025024-5ee1b9f4859a ) -// replace github.com/SkycoinProject/dmsg => ../dmsg +//replace github.com/SkycoinProject/dmsg => ../dmsg From e936d73adcc5bdaa27f5f2f14f1c689b3fd2c3af Mon Sep 17 00:00:00 2001 From: Sir Darkrengarius Date: Thu, 26 Dec 2019 13:34:12 +0300 Subject: [PATCH 13/33] Update vendor --- go.mod | 3 +- go.sum | 2 + vendor/github.com/SkycoinProject/dmsg/go.mod | 4 +- vendor/github.com/SkycoinProject/dmsg/go.sum | 5 ++- .../mattn/go-colorable/colorable_appengine.go | 6 +-- .../mattn/go-colorable/colorable_others.go | 6 +-- .../mattn/go-colorable/colorable_windows.go | 43 +++++++++++++++---- .../mattn/go-colorable/noncolorable.go | 6 +-- vendor/modules.txt | 4 +- 9 files changed, 55 insertions(+), 24 deletions(-) diff --git a/go.mod b/go.mod index 3b849bd2d..3f7cf7d01 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/SkycoinProject/skywire-mainnet go 1.13 require ( - github.com/SkycoinProject/dmsg v0.0.0-20191106075825-cabc26522b11 + github.com/SkycoinProject/dmsg v0.0.0-20191107094546-85c27858fca6 github.com/SkycoinProject/skycoin v0.26.0 github.com/SkycoinProject/yamux v0.0.0-20191213015001-a36efeefbf6a github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 @@ -17,6 +17,7 @@ require ( github.com/prometheus/client_golang v1.2.1 github.com/prometheus/common v0.7.0 github.com/sirupsen/logrus v1.4.2 + github.com/skycoin/dmsg v0.0.0-20190805065636-70f4c32a994f // indirect github.com/spf13/cobra v0.0.5 github.com/stretchr/testify v1.4.0 go.etcd.io/bbolt v1.3.3 diff --git a/go.sum b/go.sum index afc2caf24..fda3ae904 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/SkycoinProject/dmsg v0.0.0-20191106075825-cabc26522b11 h1:OpkHFoRtTKkcaNy/iCdBOyuFqLyy0geXtLz3vOD1FfE= github.com/SkycoinProject/dmsg v0.0.0-20191106075825-cabc26522b11/go.mod h1:aJrtm4X13hJDh+EX4amx51EBaLvSKjhFH8tf0E8Xxx4= +github.com/SkycoinProject/dmsg v0.0.0-20191107094546-85c27858fca6 h1:qL8+QqCaEzNO4vesE50kZyX1o7BOiwxUMYi1OX/J6KM= +github.com/SkycoinProject/dmsg v0.0.0-20191107094546-85c27858fca6/go.mod h1:Omi1J0gOWWriHkHn/9aGw8JXHtsEfnYwithZY6fIEQY= github.com/SkycoinProject/skycoin v0.26.0 h1:8/ZRZb2VM2DM4YTIitRJMZ3Yo/3H1FFmbCMx5o6ekmA= github.com/SkycoinProject/skycoin v0.26.0/go.mod h1:xqPLOKh5B6GBZlGA7B5IJfQmCy7mwimD9NlqxR3gMXo= github.com/SkycoinProject/yamux v0.0.0-20191213015001-a36efeefbf6a h1:6nHCJqh7trsuRcpMC5JmtDukUndn2VC9sY64K6xQ7hQ= diff --git a/vendor/github.com/SkycoinProject/dmsg/go.mod b/vendor/github.com/SkycoinProject/dmsg/go.mod index 72283c2b4..a60278f79 100644 --- a/vendor/github.com/SkycoinProject/dmsg/go.mod +++ b/vendor/github.com/SkycoinProject/dmsg/go.mod @@ -5,8 +5,10 @@ go 1.12 require ( github.com/SkycoinProject/skycoin v0.26.0 github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6 + github.com/mattn/go-colorable v0.1.4 // indirect + github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect github.com/sirupsen/logrus v1.4.2 - github.com/skycoin/dmsg v0.0.0-20190805065636-70f4c32a994f + github.com/skycoin/skycoin v0.26.0 // indirect github.com/stretchr/testify v1.3.0 golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 // indirect golang.org/x/net v0.0.0-20191014212845-da9a3fd4c582 diff --git a/vendor/github.com/SkycoinProject/dmsg/go.sum b/vendor/github.com/SkycoinProject/dmsg/go.sum index 037462e79..5c54bb13d 100644 --- a/vendor/github.com/SkycoinProject/dmsg/go.sum +++ b/vendor/github.com/SkycoinProject/dmsg/go.sum @@ -5,6 +5,7 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6 h1:u/UEqS66A5ckRmS4yNpjmVH56sVtS/RfclBAYocb4as= github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6/go.mod h1:1i71OnUq3iUe1ma7Lr6yG6/rjvM3emb6yoL7xLFzcVQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -13,6 +14,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4= @@ -21,8 +24,6 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/skycoin/dmsg v0.0.0-20190805065636-70f4c32a994f h1:WWjaxOXoj6oYelm67MNtJbg51HQALjKAyhs2WAHgpZs= -github.com/skycoin/dmsg v0.0.0-20190805065636-70f4c32a994f/go.mod h1:obZYZp8eKR7Xqz+KNhJdUE6Gvp6rEXbDO8YTlW2YXgU= github.com/skycoin/skycoin v0.26.0 h1:xDxe2r8AclMntZ550Y/vUQgwgLtwrf9Wu5UYiYcN5/o= github.com/skycoin/skycoin v0.26.0/go.mod h1:78nHjQzd8KG0jJJVL/j0xMmrihXi70ti63fh8vXScJw= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go index 1f28d773d..0b0aef837 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_appengine.go +++ b/vendor/github.com/mattn/go-colorable/colorable_appengine.go @@ -9,7 +9,7 @@ import ( _ "github.com/mattn/go-isatty" ) -// NewColorable return new instance of Writer which handle escape sequence. +// NewColorable returns new instance of Writer which handles escape sequence. func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") @@ -18,12 +18,12 @@ func NewColorable(file *os.File) io.Writer { return file } -// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. +// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. func NewColorableStdout() io.Writer { return os.Stdout } -// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. +// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. func NewColorableStderr() io.Writer { return os.Stderr } diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go index 887f203dc..3fb771dcc 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_others.go +++ b/vendor/github.com/mattn/go-colorable/colorable_others.go @@ -10,7 +10,7 @@ import ( _ "github.com/mattn/go-isatty" ) -// NewColorable return new instance of Writer which handle escape sequence. +// NewColorable returns new instance of Writer which handles escape sequence. func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") @@ -19,12 +19,12 @@ func NewColorable(file *os.File) io.Writer { return file } -// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. +// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. func NewColorableStdout() io.Writer { return os.Stdout } -// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. +// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. func NewColorableStderr() io.Writer { return os.Stderr } diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go index 404e10ca0..1bd628f25 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -81,7 +81,7 @@ var ( procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") ) -// Writer provide colorable Writer to the console +// Writer provides colorable Writer to the console type Writer struct { out io.Writer handle syscall.Handle @@ -91,7 +91,7 @@ type Writer struct { rest bytes.Buffer } -// NewColorable return new instance of Writer which handle escape sequence from File. +// NewColorable returns new instance of Writer which handles escape sequence from File. func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") @@ -106,12 +106,12 @@ func NewColorable(file *os.File) io.Writer { return file } -// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. +// NewColorableStdout returns new instance of Writer which handles escape sequence for stdout. func NewColorableStdout() io.Writer { return NewColorable(os.Stdout) } -// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. +// NewColorableStderr returns new instance of Writer which handles escape sequence for stderr. func NewColorableStderr() io.Writer { return NewColorable(os.Stderr) } @@ -414,7 +414,15 @@ func doTitleSequence(er *bytes.Reader) error { return nil } -// Write write data on console +// returns Atoi(s) unless s == "" in which case it returns def +func atoiWithDefault(s string, def int) (int, error) { + if s == "" { + return def, nil + } + return strconv.Atoi(s) +} + +// Write writes data on console func (w *Writer) Write(data []byte) (n int, err error) { var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) @@ -500,7 +508,7 @@ loop: switch m { case 'A': - n, err = strconv.Atoi(buf.String()) + n, err = atoiWithDefault(buf.String(), 1) if err != nil { continue } @@ -508,7 +516,7 @@ loop: csbi.cursorPosition.y -= short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'B': - n, err = strconv.Atoi(buf.String()) + n, err = atoiWithDefault(buf.String(), 1) if err != nil { continue } @@ -516,7 +524,7 @@ loop: csbi.cursorPosition.y += short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'C': - n, err = strconv.Atoi(buf.String()) + n, err = atoiWithDefault(buf.String(), 1) if err != nil { continue } @@ -524,7 +532,7 @@ loop: csbi.cursorPosition.x += short(n) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'D': - n, err = strconv.Atoi(buf.String()) + n, err = atoiWithDefault(buf.String(), 1) if err != nil { continue } @@ -557,6 +565,9 @@ loop: if err != nil { continue } + if n < 1 { + n = 1 + } procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = short(n - 1) procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) @@ -635,6 +646,20 @@ loop: } procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + case 'X': + n := 0 + if buf.Len() > 0 { + n, err = strconv.Atoi(buf.String()) + if err != nil { + continue + } + } + procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + var cursor coord + var written dword + cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} + procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(n), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'm': procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) attr := csbi.attributes diff --git a/vendor/github.com/mattn/go-colorable/noncolorable.go b/vendor/github.com/mattn/go-colorable/noncolorable.go index 9721e16f4..95f2c6be2 100644 --- a/vendor/github.com/mattn/go-colorable/noncolorable.go +++ b/vendor/github.com/mattn/go-colorable/noncolorable.go @@ -5,17 +5,17 @@ import ( "io" ) -// NonColorable hold writer but remove escape sequence. +// NonColorable holds writer but removes escape sequence. type NonColorable struct { out io.Writer } -// NewNonColorable return new instance of Writer which remove escape sequence from Writer. +// NewNonColorable returns new instance of Writer which removes escape sequence from Writer. func NewNonColorable(w io.Writer) io.Writer { return &NonColorable{out: w} } -// Write write data on console +// Write writes data on console func (w *NonColorable) Write(data []byte) (n int, err error) { er := bytes.NewReader(data) var bw [1]byte diff --git a/vendor/modules.txt b/vendor/modules.txt index cf0988743..596630099 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,4 +1,4 @@ -# github.com/SkycoinProject/dmsg v0.0.0-20191106075825-cabc26522b11 +# github.com/SkycoinProject/dmsg v0.0.0-20191107094546-85c27858fca6 github.com/SkycoinProject/dmsg github.com/SkycoinProject/dmsg/cipher github.com/SkycoinProject/dmsg/disc @@ -42,7 +42,7 @@ github.com/gorilla/securecookie github.com/inconshreveable/mousetrap # github.com/konsorten/go-windows-terminal-sequences v1.0.2 github.com/konsorten/go-windows-terminal-sequences -# github.com/mattn/go-colorable v0.1.2 +# github.com/mattn/go-colorable v0.1.4 github.com/mattn/go-colorable # github.com/mattn/go-isatty v0.0.8 github.com/mattn/go-isatty From d01737637cb21d00c343ff957b0dc8e3dabc84ce Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Thu, 26 Dec 2019 22:10:23 +0400 Subject: [PATCH 14/33] Fix bugs & make different improvements --- cmd/skywire-visor/commands/root.go | 16 ++++++++ pkg/restart/restart.go | 61 +++++++++++++++++++++--------- pkg/restart/restart_test.go | 16 ++++---- pkg/visor/rpc.go | 16 +++++++- pkg/visor/visor.go | 1 + 5 files changed, 82 insertions(+), 28 deletions(-) diff --git a/cmd/skywire-visor/commands/root.go b/cmd/skywire-visor/commands/root.go index b0213cce7..9eb51f5e7 100644 --- a/cmd/skywire-visor/commands/root.go +++ b/cmd/skywire-visor/commands/root.go @@ -40,6 +40,7 @@ type runCfg struct { cfgFromStdin bool profileMode string port string + startDelay string args []string profileStop func() @@ -75,6 +76,7 @@ func init() { rootCmd.Flags().BoolVarP(&cfg.cfgFromStdin, "stdin", "i", false, "read config from STDIN") rootCmd.Flags().StringVarP(&cfg.profileMode, "profile", "p", "none", "enable profiling with pprof. Mode: none or one of: [cpu, mem, mutex, block, trace, http]") rootCmd.Flags().StringVarP(&cfg.port, "port", "", "6060", "port for http-mode of pprof") + rootCmd.Flags().StringVarP(&cfg.startDelay, "delay", "", "0ns", "delay before visor start") restartCtx, err := restart.CaptureContext() if err != nil { @@ -157,6 +159,18 @@ func (cfg *runCfg) readConfig() *runCfg { } func (cfg *runCfg) runNode() *runCfg { + startDelay, err := time.ParseDuration(cfg.startDelay) + if err != nil { + cfg.logger.Warnf("Using no visor start delay due to parsing failure: %v", err) + startDelay = time.Duration(0) + } + + if startDelay != 0 { + cfg.logger.Infof("Visor start delay is %v, waiting...", startDelay) + } + + time.Sleep(startDelay) + node, err := visor.NewNode(&cfg.conf, cfg.masterLogger, cfg.restartCtx) if err != nil { cfg.logger.Fatal("Failed to initialize node: ", err) @@ -190,7 +204,9 @@ func (cfg *runCfg) runNode() *runCfg { if cfg.conf.ShutdownTimeout == 0 { cfg.conf.ShutdownTimeout = defaultShutdownTimeout } + cfg.node = node + return cfg } diff --git a/pkg/restart/restart.go b/pkg/restart/restart.go index edeb68818..b26016c6c 100644 --- a/pkg/restart/restart.go +++ b/pkg/restart/restart.go @@ -20,7 +20,7 @@ var ( ) // DefaultCheckDelay is a default delay for checking if a new instance is started successfully. -const DefaultCheckDelay = 5 * time.Second +const DefaultCheckDelay = 1 * time.Second // Context describes data required for restarting visor. type Context struct { @@ -28,8 +28,8 @@ type Context struct { checkDelay time.Duration workingDirectory string args []string - needsExit bool // disable in (c *Context) Restart() tests isRestarting int32 + appendDelay bool // disabled in tests } // CaptureContext captures data required for restarting visor. @@ -47,7 +47,7 @@ func CaptureContext() (*Context, error) { checkDelay: DefaultCheckDelay, workingDirectory: wd, args: args, - needsExit: true, + appendDelay: true, } return context, nil @@ -67,8 +67,8 @@ func (c *Context) SetCheckDelay(delay time.Duration) { } } -// Restart restarts executable using Context. -func (c *Context) Restart() error { +// Start starts a new executable using Context. +func (c *Context) Start() error { if !atomic.CompareAndSwapInt32(&c.isRestarting, 0, 1) { return ErrAlreadyRestarting } @@ -79,12 +79,12 @@ func (c *Context) Restart() error { return ErrMalformedArgs } - executableRelPath := c.args[0] - executableAbsPath := filepath.Join(c.workingDirectory, executableRelPath) - - c.infoLogger()("Starting new instance of executable (path: %q)", executableAbsPath) + execPath := c.args[0] + if !filepath.IsAbs(execPath) { + execPath = filepath.Join(c.workingDirectory, execPath) + } - errCh := c.start(executableAbsPath) + errCh := c.startExec(execPath) ticker := time.NewTicker(c.checkDelay) defer ticker.Stop() @@ -95,17 +95,11 @@ func (c *Context) Restart() error { return err case <-ticker.C: c.infoLogger()("New instance started successfully, exiting") - - if c.needsExit { - os.Exit(0) - } - - // unreachable unless run in tests return nil } } -func (c *Context) start(path string) chan error { +func (c *Context) startExec(path string) chan error { errCh := make(chan error, 1) go func(path string) { @@ -122,9 +116,16 @@ func (c *Context) start(path string) chan error { return } - args := c.args[1:] + args := c.startArgs() cmd := exec.Command(normalizedPath, args...) // nolint:gosec + cmd.Stdout = os.Stdout + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr + cmd.Env = os.Environ() + + c.infoLogger()("Starting new instance of executable (path: %q, args: %q)", path, args) + if err := cmd.Start(); err != nil { errCh <- err return @@ -139,6 +140,30 @@ func (c *Context) start(path string) chan error { return errCh } +const extraWaitingTime = 1 * time.Second + +func (c *Context) startArgs() []string { + args := c.args[1:] + + const delayArgName = "--delay" + + l := len(args) + for i := 0; i < l; i++ { + if args[i] == delayArgName && i < len(args)-1 { + args = append(args[:i], args[i+2:]...) + i-- + l -= 2 + } + } + + if c.appendDelay { + delay := c.checkDelay + extraWaitingTime + args = append(args, delayArgName, delay.String()) + } + + return args +} + func (c *Context) infoLogger() func(string, ...interface{}) { if c.log != nil { return c.log.Infof diff --git a/pkg/restart/restart_test.go b/pkg/restart/restart_test.go index e0c118add..29cbb6f96 100644 --- a/pkg/restart/restart_test.go +++ b/pkg/restart/restart_test.go @@ -21,7 +21,6 @@ func TestCaptureContext(t *testing.T) { require.Equal(t, DefaultCheckDelay, cc.checkDelay) require.Equal(t, os.Args, cc.args) require.Nil(t, cc.log) - require.True(t, cc.needsExit) } func TestContext_RegisterLogger(t *testing.T) { @@ -34,21 +33,21 @@ func TestContext_RegisterLogger(t *testing.T) { require.Equal(t, logger, cc.log) } -func TestContext_Restart(t *testing.T) { +func TestContext_Start(t *testing.T) { cc, err := CaptureContext() require.NoError(t, err) assert.NotZero(t, len(cc.args)) cc.workingDirectory = "" - cc.needsExit = false t.Run("executable started", func(t *testing.T) { cmd := "touch" path := "/tmp/test_restart" args := []string{cmd, path} cc.args = args + cc.appendDelay = false - assert.NoError(t, cc.Restart()) + assert.NoError(t, cc.Start()) assert.NoError(t, os.Remove(path)) }) @@ -58,13 +57,13 @@ func TestContext_Restart(t *testing.T) { cc.args = args // TODO(nkryuchkov): Check if it works on Linux and Windows, if not then change the error text. - assert.EqualError(t, cc.Restart(), `exec: "bad_command": executable file not found in $PATH`) + assert.EqualError(t, cc.Start(), `exec: "bad_command": executable file not found in $PATH`) }) t.Run("empty args", func(t *testing.T) { cc.args = nil - assert.Equal(t, ErrMalformedArgs, cc.Restart()) + assert.Equal(t, ErrMalformedArgs, cc.Start()) }) t.Run("already restarting", func(t *testing.T) { @@ -74,13 +73,14 @@ func TestContext_Restart(t *testing.T) { path := "/tmp/test_restart" args := []string{cmd, path} cc.args = args + cc.appendDelay = false ch := make(chan error, 1) go func() { - ch <- cc.Restart() + ch <- cc.Start() }() - assert.NoError(t, cc.Restart()) + assert.NoError(t, cc.Start()) assert.NoError(t, os.Remove(path)) assert.Equal(t, ErrAlreadyRestarting, <-ch) diff --git a/pkg/visor/rpc.go b/pkg/visor/rpc.go index 9f733e182..7ddd95834 100644 --- a/pkg/visor/rpc.go +++ b/pkg/visor/rpc.go @@ -4,6 +4,7 @@ import ( "context" "errors" "net/http" + "os" "path/filepath" "time" @@ -398,11 +399,22 @@ func (r *RPC) Loops(_ *struct{}, out *[]LoopInfo) error { <<< VISOR MANAGEMENT >>> */ +const exitDelay = 100 * time.Millisecond + // Restart restarts visor. -func (r *RPC) Restart(_ *struct{}, _ *struct{}) error { +func (r *RPC) Restart(_ *struct{}, _ *struct{}) (err error) { + defer func() { + if err == nil { + go func() { + time.Sleep(exitDelay) + os.Exit(0) + }() + } + }() + if r.node.restartCtx == nil { return ErrMalformedRestartContext } - return r.node.restartCtx.Restart() + return r.node.restartCtx.Start() } diff --git a/pkg/visor/visor.go b/pkg/visor/visor.go index c316a5152..5992f12fc 100644 --- a/pkg/visor/visor.go +++ b/pkg/visor/visor.go @@ -84,6 +84,7 @@ type Node struct { appsConf []AppConfig startedAt time.Time + startDelay time.Duration restartCtx *restart.Context pidMu sync.Mutex From a754316e4b702af4a8889ec8dd500c3aad2d0639 Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Thu, 26 Dec 2019 22:35:44 +0400 Subject: [PATCH 15/33] Simplify restart logic --- cmd/skywire-visor/commands/root.go | 7 +- pkg/restart/restart.go | 113 ++++++++++------------------- pkg/restart/restart_test.go | 48 ++++-------- 3 files changed, 57 insertions(+), 111 deletions(-) diff --git a/cmd/skywire-visor/commands/root.go b/cmd/skywire-visor/commands/root.go index 9eb51f5e7..ed47be729 100644 --- a/cmd/skywire-visor/commands/root.go +++ b/cmd/skywire-visor/commands/root.go @@ -78,12 +78,7 @@ func init() { rootCmd.Flags().StringVarP(&cfg.port, "port", "", "6060", "port for http-mode of pprof") rootCmd.Flags().StringVarP(&cfg.startDelay, "delay", "", "0ns", "delay before visor start") - restartCtx, err := restart.CaptureContext() - if err != nil { - log.Printf("Failed to capture context: %v", err) - } else { - cfg.restartCtx = restartCtx - } + cfg.restartCtx = restart.CaptureContext() } // Execute executes root CLI command. diff --git a/pkg/restart/restart.go b/pkg/restart/restart.go index b26016c6c..1313097ec 100644 --- a/pkg/restart/restart.go +++ b/pkg/restart/restart.go @@ -5,7 +5,6 @@ import ( "log" "os" "os/exec" - "path/filepath" "sync/atomic" "time" @@ -13,44 +12,42 @@ import ( ) var ( - // ErrMalformedArgs is returned when executable args are malformed. - ErrMalformedArgs = errors.New("malformed args") - // ErrAlreadyRestarting is returned on restarting attempt when restarting is in progress. - ErrAlreadyRestarting = errors.New("already restarting") + // ErrAlreadyStarting is returned on starting attempt when starting is in progress. + ErrAlreadyStarting = errors.New("already starting") ) -// DefaultCheckDelay is a default delay for checking if a new instance is started successfully. -const DefaultCheckDelay = 1 * time.Second +const ( + // DefaultCheckDelay is a default delay for checking if a new instance is started successfully. + DefaultCheckDelay = 1 * time.Second + extraWaitingTime = 1 * time.Second + delayArgName = "--delay" +) // Context describes data required for restarting visor. type Context struct { - log logrus.FieldLogger - checkDelay time.Duration - workingDirectory string - args []string - isRestarting int32 - appendDelay bool // disabled in tests + log logrus.FieldLogger + isStarting int32 + checkDelay time.Duration + appendDelay bool // disabled in tests + cmd *exec.Cmd } // CaptureContext captures data required for restarting visor. // Data used by CaptureContext must not be modified before, // therefore calling CaptureContext immediately after starting executable is recommended. -func CaptureContext() (*Context, error) { - wd, err := os.Getwd() - if err != nil { - return nil, err +func CaptureContext() *Context { + cmd := exec.Command(os.Args[0], os.Args[1:]...) + + cmd.Stdout = os.Stdout + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr + cmd.Env = os.Environ() + + return &Context{ + cmd: cmd, + checkDelay: DefaultCheckDelay, + appendDelay: true, } - - args := os.Args - - context := &Context{ - checkDelay: DefaultCheckDelay, - workingDirectory: wd, - args: args, - appendDelay: true, - } - - return context, nil } // RegisterLogger registers a logger instead of standard one. @@ -69,22 +66,13 @@ func (c *Context) SetCheckDelay(delay time.Duration) { // Start starts a new executable using Context. func (c *Context) Start() error { - if !atomic.CompareAndSwapInt32(&c.isRestarting, 0, 1) { - return ErrAlreadyRestarting + if !atomic.CompareAndSwapInt32(&c.isStarting, 0, 1) { + return ErrAlreadyStarting } - defer atomic.StoreInt32(&c.isRestarting, 0) + defer atomic.StoreInt32(&c.isStarting, 0) - if len(c.args) == 0 { - return ErrMalformedArgs - } - - execPath := c.args[0] - if !filepath.IsAbs(execPath) { - execPath = filepath.Join(c.workingDirectory, execPath) - } - - errCh := c.startExec(execPath) + errCh := c.startExec() ticker := time.NewTicker(c.checkDelay) defer ticker.Stop() @@ -94,58 +82,37 @@ func (c *Context) Start() error { c.errorLogger()("Failed to start new instance: %v", err) return err case <-ticker.C: - c.infoLogger()("New instance started successfully, exiting") + c.infoLogger()("New instance started successfully, exiting from the old one") return nil } } -func (c *Context) startExec(path string) chan error { +func (c *Context) startExec() chan error { errCh := make(chan error, 1) - go func(path string) { + go func() { defer close(errCh) - normalizedPath, err := exec.LookPath(path) - if err != nil { - errCh <- err - return - } - - if len(c.args) == 0 { - errCh <- ErrMalformedArgs - return - } + c.adjustArgs() - args := c.startArgs() - cmd := exec.Command(normalizedPath, args...) // nolint:gosec + c.infoLogger()("Starting new instance of executable (args: %q)", c.cmd.Args) - cmd.Stdout = os.Stdout - cmd.Stdin = os.Stdin - cmd.Stderr = os.Stderr - cmd.Env = os.Environ() - - c.infoLogger()("Starting new instance of executable (path: %q, args: %q)", path, args) - - if err := cmd.Start(); err != nil { + if err := c.cmd.Start(); err != nil { errCh <- err return } - if err := cmd.Wait(); err != nil { + if err := c.cmd.Wait(); err != nil { errCh <- err return } - }(path) + }() return errCh } -const extraWaitingTime = 1 * time.Second - -func (c *Context) startArgs() []string { - args := c.args[1:] - - const delayArgName = "--delay" +func (c *Context) adjustArgs() { + args := c.cmd.Args l := len(args) for i := 0; i < l; i++ { @@ -161,7 +128,7 @@ func (c *Context) startArgs() []string { args = append(args, delayArgName, delay.String()) } - return args + c.cmd.Args = args } func (c *Context) infoLogger() func(string, ...interface{}) { diff --git a/pkg/restart/restart_test.go b/pkg/restart/restart_test.go index 29cbb6f96..e75c88079 100644 --- a/pkg/restart/restart_test.go +++ b/pkg/restart/restart_test.go @@ -2,6 +2,7 @@ package restart import ( "os" + "os/exec" "testing" "time" @@ -11,21 +12,19 @@ import ( ) func TestCaptureContext(t *testing.T) { - cc, err := CaptureContext() - require.NoError(t, err) + cc := CaptureContext() - wd, err := os.Getwd() - assert.NoError(t, err) - - require.Equal(t, wd, cc.workingDirectory) require.Equal(t, DefaultCheckDelay, cc.checkDelay) - require.Equal(t, os.Args, cc.args) + require.Equal(t, os.Args, cc.cmd.Args) + require.Equal(t, os.Stdout, cc.cmd.Stdout) + require.Equal(t, os.Stdin, cc.cmd.Stdin) + require.Equal(t, os.Stderr, cc.cmd.Stderr) + require.Equal(t, os.Environ(), cc.cmd.Env) require.Nil(t, cc.log) } func TestContext_RegisterLogger(t *testing.T) { - cc, err := CaptureContext() - require.NoError(t, err) + cc := CaptureContext() require.Nil(t, cc.log) logger := logging.MustGetLogger("test") @@ -34,17 +33,13 @@ func TestContext_RegisterLogger(t *testing.T) { } func TestContext_Start(t *testing.T) { - cc, err := CaptureContext() - require.NoError(t, err) - assert.NotZero(t, len(cc.args)) - - cc.workingDirectory = "" + cc := CaptureContext() + assert.NotZero(t, len(cc.cmd.Args)) t.Run("executable started", func(t *testing.T) { cmd := "touch" path := "/tmp/test_restart" - args := []string{cmd, path} - cc.args = args + cc.cmd = exec.Command(cmd, path) cc.appendDelay = false assert.NoError(t, cc.Start()) @@ -53,26 +48,16 @@ func TestContext_Start(t *testing.T) { t.Run("bad args", func(t *testing.T) { cmd := "bad_command" - args := []string{cmd} - cc.args = args + cc.cmd = exec.Command(cmd) // TODO(nkryuchkov): Check if it works on Linux and Windows, if not then change the error text. assert.EqualError(t, cc.Start(), `exec: "bad_command": executable file not found in $PATH`) }) - t.Run("empty args", func(t *testing.T) { - cc.args = nil - - assert.Equal(t, ErrMalformedArgs, cc.Start()) - }) - t.Run("already restarting", func(t *testing.T) { - cc.args = nil - cmd := "touch" path := "/tmp/test_restart" - args := []string{cmd, path} - cc.args = args + cc.cmd = exec.Command(cmd, path) cc.appendDelay = false ch := make(chan error, 1) @@ -81,15 +66,14 @@ func TestContext_Start(t *testing.T) { }() assert.NoError(t, cc.Start()) - assert.NoError(t, os.Remove(path)) + assert.Equal(t, ErrAlreadyStarting, <-ch) - assert.Equal(t, ErrAlreadyRestarting, <-ch) + assert.NoError(t, os.Remove(path)) }) } func TestContext_SetCheckDelay(t *testing.T) { - cc, err := CaptureContext() - require.NoError(t, err) + cc := CaptureContext() require.Equal(t, DefaultCheckDelay, cc.checkDelay) const oneSecond = 1 * time.Second From 2756eccb54b0e25f157164b73eb39667a24bf87e Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Thu, 26 Dec 2019 22:37:31 +0400 Subject: [PATCH 16/33] Fix linter errors --- pkg/restart/restart.go | 2 +- pkg/visor/visor.go | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/pkg/restart/restart.go b/pkg/restart/restart.go index 1313097ec..f108cc16d 100644 --- a/pkg/restart/restart.go +++ b/pkg/restart/restart.go @@ -36,7 +36,7 @@ type Context struct { // Data used by CaptureContext must not be modified before, // therefore calling CaptureContext immediately after starting executable is recommended. func CaptureContext() *Context { - cmd := exec.Command(os.Args[0], os.Args[1:]...) + cmd := exec.Command(os.Args[0], os.Args[1:]...) // nolint:gosec cmd.Stdout = os.Stdout cmd.Stdin = os.Stdin diff --git a/pkg/visor/visor.go b/pkg/visor/visor.go index 5992f12fc..c316a5152 100644 --- a/pkg/visor/visor.go +++ b/pkg/visor/visor.go @@ -84,7 +84,6 @@ type Node struct { appsConf []AppConfig startedAt time.Time - startDelay time.Duration restartCtx *restart.Context pidMu sync.Mutex From 0dc3a763ad3ae9a445e4c0c0d1cf757278f3c891 Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Thu, 26 Dec 2019 22:43:39 +0400 Subject: [PATCH 17/33] Make minor linter improvements --- pkg/restart/restart.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/pkg/restart/restart.go b/pkg/restart/restart.go index f108cc16d..0c485ebb8 100644 --- a/pkg/restart/restart.go +++ b/pkg/restart/restart.go @@ -26,10 +26,10 @@ const ( // Context describes data required for restarting visor. type Context struct { log logrus.FieldLogger - isStarting int32 + cmd *exec.Cmd checkDelay time.Duration + isStarting int32 appendDelay bool // disabled in tests - cmd *exec.Cmd } // CaptureContext captures data required for restarting visor. @@ -114,12 +114,15 @@ func (c *Context) startExec() chan error { func (c *Context) adjustArgs() { args := c.cmd.Args + i := 0 l := len(args) - for i := 0; i < l; i++ { + + for i < l { if args[i] == delayArgName && i < len(args)-1 { args = append(args[:i], args[i+2:]...) - i-- l -= 2 + } else { + i++ } } From df0797f8d59f6f4d108d65ff9b9f2fb959a6e9bc Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Thu, 26 Dec 2019 23:14:13 +0400 Subject: [PATCH 18/33] Fix linter errors --- pkg/restart/restart_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/restart/restart_test.go b/pkg/restart/restart_test.go index e75c88079..bb9825349 100644 --- a/pkg/restart/restart_test.go +++ b/pkg/restart/restart_test.go @@ -39,7 +39,7 @@ func TestContext_Start(t *testing.T) { t.Run("executable started", func(t *testing.T) { cmd := "touch" path := "/tmp/test_restart" - cc.cmd = exec.Command(cmd, path) + cc.cmd = exec.Command(cmd, path) // nolint:gosec cc.appendDelay = false assert.NoError(t, cc.Start()) @@ -48,7 +48,7 @@ func TestContext_Start(t *testing.T) { t.Run("bad args", func(t *testing.T) { cmd := "bad_command" - cc.cmd = exec.Command(cmd) + cc.cmd = exec.Command(cmd) // nolint:gosec // TODO(nkryuchkov): Check if it works on Linux and Windows, if not then change the error text. assert.EqualError(t, cc.Start(), `exec: "bad_command": executable file not found in $PATH`) @@ -57,7 +57,7 @@ func TestContext_Start(t *testing.T) { t.Run("already restarting", func(t *testing.T) { cmd := "touch" path := "/tmp/test_restart" - cc.cmd = exec.Command(cmd, path) + cc.cmd = exec.Command(cmd, path) // nolint:gosec cc.appendDelay = false ch := make(chan error, 1) From b27533728ee9f570df6392c321b2ecf4b93e28af Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Mon, 30 Dec 2019 20:45:54 +0400 Subject: [PATCH 19/33] Remove therealssh --- README.md | 33 +- ci_scripts/run-internal-tests.sh | 14 - cmd/apps/therealssh-client/README.md | 8 - .../therealssh-client/therealssh-client.go | 66 ---- cmd/apps/therealssh/README.md | 74 ---- cmd/apps/therealssh/therealssh.go | 93 ----- cmd/skywire-visor/config.json | 7 - cmd/therealssh-cli/README.md | 6 - cmd/therealssh-cli/commands/root.go | 230 ----------- cmd/therealssh-cli/therealssh-cli.go | 12 - docker/images/node/Dockerfile | 4 +- integration/InteractiveEnvironments.md | 57 +-- integration/generic/nodeA.json | 7 - integration/generic/nodeC.json | 7 - integration/run-ssh-env.sh | 26 -- integration/ssh/env-vars.sh | 24 -- integration/ssh/nodeA.json | 55 --- integration/ssh/nodeC.json | 61 --- integration/test-proxy.sh | 40 -- integration/test-ssh.sh | 31 -- internal/skyenv/const.go | 4 - pkg/therealssh/auth.go | 92 ----- pkg/therealssh/auth_test.go | 43 --- pkg/therealssh/chan_list.go | 54 --- pkg/therealssh/channel.go | 364 ------------------ pkg/therealssh/channel_pty_test.go | 91 ----- pkg/therealssh/channel_test.go | 130 ------- pkg/therealssh/client.go | 314 --------------- pkg/therealssh/client_test.go | 106 ----- pkg/therealssh/dialer.go | 12 - pkg/therealssh/pty_test.go | 100 ----- pkg/therealssh/server.go | 196 ---------- pkg/therealssh/server_test.go | 124 ------ pkg/therealssh/session.go | 200 ---------- pkg/therealssh/shell.go | 20 - pkg/therealssh/shell_darwin.go | 25 -- pkg/visor/visor.go | 2 +- 37 files changed, 16 insertions(+), 2716 deletions(-) delete mode 100644 cmd/apps/therealssh-client/README.md delete mode 100644 cmd/apps/therealssh-client/therealssh-client.go delete mode 100644 cmd/apps/therealssh/README.md delete mode 100644 cmd/apps/therealssh/therealssh.go delete mode 100644 cmd/therealssh-cli/README.md delete mode 100644 cmd/therealssh-cli/commands/root.go delete mode 100644 cmd/therealssh-cli/therealssh-cli.go delete mode 100644 integration/run-ssh-env.sh delete mode 100644 integration/ssh/env-vars.sh delete mode 100644 integration/ssh/nodeA.json delete mode 100644 integration/ssh/nodeC.json delete mode 100644 integration/test-proxy.sh delete mode 100644 integration/test-ssh.sh delete mode 100644 pkg/therealssh/auth.go delete mode 100644 pkg/therealssh/auth_test.go delete mode 100644 pkg/therealssh/chan_list.go delete mode 100644 pkg/therealssh/channel.go delete mode 100644 pkg/therealssh/channel_pty_test.go delete mode 100644 pkg/therealssh/channel_test.go delete mode 100644 pkg/therealssh/client.go delete mode 100644 pkg/therealssh/client_test.go delete mode 100644 pkg/therealssh/dialer.go delete mode 100644 pkg/therealssh/pty_test.go delete mode 100644 pkg/therealssh/server.go delete mode 100644 pkg/therealssh/server_test.go delete mode 100644 pkg/therealssh/session.go delete mode 100644 pkg/therealssh/shell.go delete mode 100644 pkg/therealssh/shell_darwin.go diff --git a/README.md b/README.md index 5ea3e12a8..30e67ff05 100644 --- a/README.md +++ b/README.md @@ -18,25 +18,25 @@ - [Testing](#testing) - [Testing with default settings](#testing-with-default-settings) - [Customization with environment variables](#customization-with-environment-variables) - - [$TEST_OPTS](#testopts) - - [$TEST_LOGGING_LEVEL](#testlogginglevel) - - [$SYSLOG_OPTS](#syslogopts) + - [$TEST_OPTS](#test_opts) + - [$TEST_LOGGING_LEVEL](#test_logging_level) + - [$SYSLOG_OPTS](#syslog_opts) - [Running skywire in docker containers](#running-skywire-in-docker-containers) - [Run dockerized `skywire-visor`](#run-dockerized-skywire-visor) - [Structure of `./node`](#structure-of-node) - [Refresh and restart `SKY01`](#refresh-and-restart-sky01) - [Customization of dockers](#customization-of-dockers) - - [1. DOCKER_IMAGE](#1-dockerimage) - - [2. DOCKER_NETWORK](#2-dockernetwork) - - [3. DOCKER_NODE](#3-dockernode) - - [4. DOCKER_OPTS](#4-dockeropts) + - [1. DOCKER_IMAGE](#1-docker_image) + - [2. DOCKER_NETWORK](#2-docker_network) + - [3. DOCKER_NODE](#3-docker_node) + - [4. DOCKER_OPTS](#4-docker_opts) - [Dockerized `skywire-visor` recipes](#dockerized-skywire-visor-recipes) - [1. Get Public Key of docker-node](#1-get-public-key-of-docker-node) - [2. Get an IP of node](#2-get-an-ip-of-node) - [3. Open in browser containerized `skychat` application](#3-open-in-browser-containerized-skychat-application) - [4. Create new dockerized `skywire-visor`s](#4-create-new-dockerized-skywire-visors) - [5. Env-vars for development-/testing- purposes](#5-env-vars-for-development-testing--purposes) - - [6. "Hello-Mike-Hello-Joe" test](#6-%22hello-mike-hello-joe%22-test) + - [6. "Hello-Mike-Hello-Joe" test](#6-hello-mike-hello-joe-test) **NOTE:** The project is still under heavy development and should only be used for testing purposes right now. Miners should not switch over to this project if they want to receive testnet rewards. @@ -186,7 +186,6 @@ After `skywire-visor` is up and running with default environment, default apps a - [Chat](/cmd/apps/skychat) - [Hello World](/cmd/apps/helloworld) - [The Real Proxy](/cmd/apps/therealproxy) ([Client](/cmd/apps/therealproxy-client)) -- [The Real SSH](/cmd/apps/therealssh) ([Client](/cmd/apps/therealssh-client)) ### Transports @@ -306,13 +305,10 @@ This will: │   ├── skychat.v1.0 # │   ├── helloworld.v1.0 # │   ├── socksproxy-client.v1.0 # -│   ├── socksproxy.v1.0 # -│   ├── SSH-client.v1.0 # -│   └── SSH.v1.0 # +│   └── socksproxy.v1.0 # ├── local # **Created inside docker** │   ├── skychat # according to "local_path" in skywire-config.json -│   ├── socksproxy # -│   └── SSH # +│   └── socksproxy # ├── PK # contains public key of node ├── skywire # db & logs. **Created inside docker** │   ├── routing.db # @@ -413,8 +409,6 @@ $ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/skywire-visor ./cmd/skywire $ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/skychat.v1.0 ./cmd/apps/skychat $ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/helloworld.v1.0 ./cmd/apps/helloworld $ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/socksproxy.v1.0 ./cmd/apps/therealproxy -$ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/SSH.v1.0 ./cmd/apps/SSH -$ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/SSH-client.v1.0 ./cmd/apps/SSH-client # 4. Create skywire-config.json for node $ skywire-cli node gen-config -o /tmp/SKYNODE/skywire-config.json # 2019/03/15 16:43:49 Done! @@ -423,9 +417,7 @@ $ tree /tmp/SKYNODE # ├── apps # │   ├── skychat.v1.0 # │   ├── helloworld.v1.0 -# │   ├── socksproxy.v1.0 -# │   ├── SSH-client.v1.0 -# │   └── SSH.v1.0 +# │   └── socksproxy.v1.0 # ├── skywire-config.json # └── skywire-visor # So far so good. We prepared docker volume. Now we can: @@ -436,15 +428,12 @@ $ docker run -it -v /tmp/SKYNODE:/sky --network=SKYNET --name=SKYNODE skywire-ru # [2019-03-15T13:55:10Z] INFO [skywire]: Starting skychat.v1.0 # [2019-03-15T13:55:10Z] INFO [skywire]: Starting RPC interface on 127.0.0.1:3435 # [2019-03-15T13:55:10Z] INFO [skywire]: Starting socksproxy.v1.0 -# [2019-03-15T13:55:10Z] INFO [skywire]: Starting SSH.v1.0 # [2019-03-15T13:55:10Z] INFO [skywire]: Starting packet router # [2019-03-15T13:55:10Z] INFO [router]: Starting router # [2019-03-15T13:55:10Z] INFO [trmanager]: Starting transport manager # [2019-03-15T13:55:10Z] INFO [router]: Got new App request with type Init: {"app-name":"skychat",# "app-version":"1.0","protocol-version":"0.0.1"} # [2019-03-15T13:55:10Z] INFO [router]: Handshaked new connection with the app skychat.v1.0 # [2019-03-15T13:55:10Z] INFO [skychat.v1.0]: 2019/03/15 13:55:10 Serving HTTP on :8000 -# [2019-03-15T13:55:10Z] INFO [router]: Got new App request with type Init: {"app-name":"SSH",# "app-version":"1.0","protocol-version":"0.0.1"} -# [2019-03-15T13:55:10Z] INFO [router]: Handshaked new connection with the app SSH.v1.0 # [2019-03-15T13:55:10Z] INFO [router]: Got new App request with type Init: {"app-name":"socksproxy",# "app-version":"1.0","protocol-version":"0.0.1"} # [2019-03-15T13:55:10Z] INFO [router]: Handshaked new connection with the app socksproxy.v1.0 ``` diff --git a/ci_scripts/run-internal-tests.sh b/ci_scripts/run-internal-tests.sh index 57be9caf4..f16b93346 100755 --- a/ci_scripts/run-internal-tests.sh +++ b/ci_scripts/run-internal-tests.sh @@ -18,17 +18,3 @@ go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/noise -run TestReadWriterConcurrentTCP >> ./logs/internal/TestReadWriterConcurrentTCP.log go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealproxy -run TestProxy >> ./logs/internal/TestProxy.log - -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestListAuthorizer >> ./logs/internal/TestListAuthorizer.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestFileAuthorizer >> ./logs/internal/TestFileAuthorizer.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestChannelServe >> ./logs/internal/TestChannelServe.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestChannelSendWrite >> ./logs/internal/TestChannelSendWrite.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestChannelRead >> ./logs/internal/TestChannelRead.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestChannelRequest >> ./logs/internal/TestChannelRequest.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestChannelServeSocket >> ./logs/internal/TestChannelServeSocket.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestClientOpenChannel >> ./logs/internal/TestClientOpenChannel.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestClientHandleResponse >> ./logs/internal/TestClientHandleResponse.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestClientHandleData >> ./logs/internal/TestClientHandleData.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestServerOpenChannel >> ./logs/internal/TestServerOpenChannel.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestServerHandleRequest >> ./logs/internal/TestServerHandleRequest.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealssh -run TestServerHandleData >> ./logs/internal/TestServerHandleData.log diff --git a/cmd/apps/therealssh-client/README.md b/cmd/apps/therealssh-client/README.md deleted file mode 100644 index 3aaec4525..000000000 --- a/cmd/apps/therealssh-client/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Skywire SSH client app - -`SSH-client` app implements client for the SSH app. - -It starts RCP interface for `SSH-cli` and handles incoming requests to -the remote node via `skywire` connection. - -Please check docs for `SSH` app for further instructions. diff --git a/cmd/apps/therealssh-client/therealssh-client.go b/cmd/apps/therealssh-client/therealssh-client.go deleted file mode 100644 index 41113089a..000000000 --- a/cmd/apps/therealssh-client/therealssh-client.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -ssh client app for skywire visor -*/ -package main - -import ( - "flag" - "fmt" - "net/http" - - "github.com/SkycoinProject/skywire-mainnet/internal/skyenv" - - "github.com/SkycoinProject/skycoin/src/util/logging" - "github.com/sirupsen/logrus" - - "github.com/SkycoinProject/skywire-mainnet/pkg/app" - ssh "github.com/SkycoinProject/skywire-mainnet/pkg/therealssh" -) - -const ( - appName = "SSH-client" -) - -var log *logging.MasterLogger - -func main() { - log = app.NewLogger(appName) - ssh.Log = log.PackageLogger("therealssh") - - // TODO(evanlinjin): Change "rpc" to "addr". - var rpcAddr = flag.String("rpc", skyenv.SkysshClientAddr, "Client RPC address to listen on") - var debug = flag.Bool("debug", false, "enable debug messages") - flag.Parse() - - config, err := app.ClientConfigFromEnv() - if err != nil { - log.Fatalf("Error getting client config: %v\n", err) - } - - sshApp, err := app.NewClient(logging.MustGetLogger(fmt.Sprintf("app_%s", appName)), config) - if err != nil { - log.Fatal("Setup failure: ", err) - } - defer func() { - sshApp.Close() - }() - - ssh.Debug = *debug - if !ssh.Debug { - logging.SetLevel(logrus.InfoLevel) - } - - rpc, client, err := ssh.NewClient(*rpcAddr, sshApp) - if err != nil { - log.Fatal("Client setup failure: ", err) - } - defer func() { - if err := client.Close(); err != nil { - log.Println("Failed to close client:", err) - } - }() - - if err := http.Serve(rpc, nil); err != nil { - log.Fatal("Failed to start RPC interface: ", err) - } -} diff --git a/cmd/apps/therealssh/README.md b/cmd/apps/therealssh/README.md deleted file mode 100644 index c61dfb028..000000000 --- a/cmd/apps/therealssh/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# Skywire SSH app - -`SSH` app implements SSH functionality over skywirenet. - -`SSH-cli` is used to initiate communication via client RPC -exposed by `SSH` app. - -`SSH` app implements common SSH operations: - -- starting remote shell -- and executing commands remotely - -PubKey whitelisting is performed by adding public key to the -authentication file (`$HOME/.therealssh/authorized_keys` by default). - -** Local setup - -Create 2 node config files: - -`skywire1.json` - -```json -{ - "apps": [ - { - "app": "SSH", - "version": "1.0", - "auto_start": true, - "port": 2 - } - ] -} -``` - -`skywire2.json` - -```json -{ - "apps": [ - { - "app": "SSH-client", - "version": "1.0", - "auto_start": true, - "port": 22 - } - ] -} -``` - -Compile binaries and start 2 nodes: - -```bash -$ go build -o apps/SSH.v1.0 ./cmd/apps/therealssh -$ go build -o apps/SSH-client.v1.0 ./cmd/apps/therealssh-client -$ go build ./cmd/SSH-cli -$ ./skywire-visor skywire1.json -$ ./skywire-visor skywire2.json -``` - -Add public key of the second node to the auth file: - -```bash -$ mkdir /.therealssh -$ echo "0348c941c5015a05c455ff238af2e57fb8f914c399aab604e9abb5b32b91a4c1fe" > /.SSH/authorized_keys -``` - -Connect to the first node using CLI: - -```bash -$ ./SSH-cli 024ec47420176680816e0406250e7156465e4531f5b26057c9f6297bb0303558c7 -``` - -This should get you to the $HOME folder of the user(you in this case), which -will indicate that you are seeing remote PTY session. diff --git a/cmd/apps/therealssh/therealssh.go b/cmd/apps/therealssh/therealssh.go deleted file mode 100644 index 73bec6fe7..000000000 --- a/cmd/apps/therealssh/therealssh.go +++ /dev/null @@ -1,93 +0,0 @@ -/* -ssh server app for skywire visor -*/ -package main - -import ( - "flag" - "fmt" - - "github.com/SkycoinProject/skywire-mainnet/pkg/app/appnet" - "github.com/SkycoinProject/skywire-mainnet/pkg/routing" - - "github.com/SkycoinProject/skycoin/src/util/logging" - "github.com/mitchellh/go-homedir" - "github.com/sirupsen/logrus" - - "github.com/SkycoinProject/skywire-mainnet/pkg/app" - ssh "github.com/SkycoinProject/skywire-mainnet/pkg/therealssh" -) - -var log *logging.MasterLogger - -const ( - appName = "SSH" - netType = appnet.TypeSkynet - port = routing.Port(1000) -) - -func main() { - log = app.NewLogger(appName) - ssh.Log = log.PackageLogger("therealssh") - - // TODO: change back to the tilda-like home path - var authFile = flag.String("auth", "/Users/darkrengarius/.therealssh/authorized_keys", "Auth file location. Should contain one PubKey per line.") - var debug = flag.Bool("debug", false, "enable debug messages") - - flag.Parse() - - config, err := app.ClientConfigFromEnv() - if err != nil { - log.Fatalf("Error getting client config: %v\n", err) - } - - sshApp, err := app.NewClient(logging.MustGetLogger(fmt.Sprintf("app_%s", appName)), config) - - if err != nil { - log.Fatal("Setup failure: ", err) - } - defer func() { - sshApp.Close() - }() - - path, err := homedir.Expand(*authFile) - if err != nil { - log.Errorf("Error expanding auth file path %s: %v\n", *authFile, err) - log.Fatal("Failed to resolve auth file path: ", err) - } - - ssh.Debug = *debug - if !ssh.Debug { - logging.SetLevel(logrus.InfoLevel) - } - - auth, err := ssh.NewFileAuthorizer(path) - if err != nil { - log.Fatal("Failed to setup Authorizer: ", err) - } - - server := ssh.NewServer(auth, log) - defer func() { - if err := server.Close(); err != nil { - log.Println("Failed to close server:", err) - } - }() - - l, err := sshApp.Listen(netType, port) - if err != nil { - log.Fatalf("Error listening network %v on port %d: %v\n", netType, port, err) - } - - for { - conn, err := l.Accept() - if err != nil { - log.Fatal("failed to receive packet: ", err) - } - - go func() { - if err := server.Serve(conn); err != nil { - log.Println("Failed to serve conn:", err) - } - }() - } -} diff --git a/cmd/skywire-visor/config.json b/cmd/skywire-visor/config.json index f0200db8e..3ee1687fa 100644 --- a/cmd/skywire-visor/config.json +++ b/cmd/skywire-visor/config.json @@ -23,13 +23,6 @@ "ports": [ 1 ] - }, - { - "app": "SSH-server", - "auto_start": true, - "ports": [ - 2 - ] } ], "messaging_path": "./messaging", diff --git a/cmd/therealssh-cli/README.md b/cmd/therealssh-cli/README.md deleted file mode 100644 index 90df7c21c..000000000 --- a/cmd/therealssh-cli/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# CLI for SSH app - -`SSH-cli` implements PTY related operations for SSH app. - -It connects to SSH client's RPC server, configures terminal for raw pty -data and handles pty data exchange. diff --git a/cmd/therealssh-cli/commands/root.go b/cmd/therealssh-cli/commands/root.go deleted file mode 100644 index c3bb4d65b..000000000 --- a/cmd/therealssh-cli/commands/root.go +++ /dev/null @@ -1,230 +0,0 @@ -package commands - -import ( - "fmt" - "io" - "log" - "net" - "net/rpc" - "os" - "os/signal" - "os/user" - "strings" - "syscall" - "time" - - "github.com/SkycoinProject/dmsg/cipher" - "github.com/creack/pty" - "github.com/spf13/cobra" - "golang.org/x/crypto/ssh/terminal" - - ssh "github.com/SkycoinProject/skywire-mainnet/pkg/therealssh" -) - -var ( - rpcAddr string - ptyMode bool - ptyRows uint16 - ptyCols uint16 - ptyX uint16 - ptyY uint16 - ptyBufferSize uint32 -) - -var rootCmd = &cobra.Command{ - Use: "SSH-cli [user@]remotePK [command] [args...]", - Short: "Client for the SSH-client app", - Args: cobra.MinimumNArgs(1), - Run: func(_ *cobra.Command, args []string) { - if ptyMode { - runInPTY(args) - return - } - client, err := rpc.DialHTTP("tcp", rpcAddr) - if err != nil { - log.Fatal("RPC connection failed:", err) - } - - size, err := pty.GetsizeFull(os.Stdin) - if err != nil { - log.Fatal("Failed to get TTY size:", err) - } - - username, pk, err := resolveUser(args[0]) - if err != nil { - log.Fatal("Invalid user/pk pair: ", err) - } - - remotePK := cipher.PubKey{} - if err := remotePK.UnmarshalText([]byte(pk)); err != nil { - log.Fatal("Invalid remote PubKey: ", err) - } - - ptyArgs := &ssh.RequestPTYArgs{Username: username, RemotePK: remotePK, Size: size} - var channelID uint32 - if err := client.Call("RPCClient.RequestPTY", ptyArgs, &channelID); err != nil { - log.Fatal("Failed to request PTY:", err) - } - defer func() { - if err := client.Call("RPCClient.Close", &channelID, nil); err != nil { - log.Printf("Failed to close RPC client: %v", err) - } - }() - - var socketPath string - execArgs := &ssh.ExecArgs{ChannelID: channelID, CommandWithArgs: args[1:]} - if err := client.Call("RPCClient.Exec", execArgs, &socketPath); err != nil { - log.Fatal("Failed to start shell:", err) - } - - conn, err := dialUnix(socketPath) - if err != nil { - log.Fatal("Failed dial ssh socket:", err) - } - - ch := make(chan os.Signal) - signal.Notify(ch, syscall.SIGWINCH) - go func() { - for range ch { - size, err := pty.GetsizeFull(os.Stdin) - if err != nil { - log.Println("Failed to change pty size:", err) - return - } - - var result int - if err := client.Call("RPCClient.WindowChange", &ssh.WindowChangeArgs{ChannelID: channelID, Size: size}, &result); err != nil { - log.Println("Failed to change pty size:", err) - } - } - }() - - oldState, err := terminal.MakeRaw(int(os.Stdin.Fd())) - if err != nil { - log.Fatal("Failed to set terminal to raw mode:", err) - } - defer func() { - if err := terminal.Restore(int(os.Stdin.Fd()), oldState); err != nil { - log.Printf("Failed to restore terminal: %v", err) - } - }() - - go func() { - if _, err := io.Copy(conn, os.Stdin); err != nil { - log.Fatal("Failed to write to ssh socket:", err) - } - }() - - if _, err := io.Copy(os.Stdout, conn); err != nil { - log.Fatal("Failed to read from ssh socket:", err) - } - }, -} - -func dialUnix(socketPath string) (net.Conn, error) { - var conn net.Conn - var err error - - for i := 0; i < 5; i++ { - conn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: socketPath, Net: "unix"}) - if err == nil { - break - } - - time.Sleep(time.Second) - } - - return conn, err -} - -func runInPTY(args []string) { - client, err := rpc.DialHTTP("tcp", rpcAddr) - if err != nil { - log.Fatal("RPC connection failed:", err) - } - - username, pk, err := resolveUser(args[0]) - if err != nil { - log.Fatal("Invalid user/pk pair: ", err) - } - - remotePK := cipher.PubKey{} - if err := remotePK.UnmarshalText([]byte(pk)); err != nil { - log.Fatal("Invalid remote PubKey: ", err) - } - - ptyArgs := &ssh.RequestPTYArgs{ - Username: username, - RemotePK: remotePK, - Size: &pty.Winsize{ - Rows: uint16(ptyRows), - Cols: ptyCols, - X: ptyX, - Y: ptyY, - }, - } - - var channelID uint32 - if err := client.Call("RPCClient.RequestPTY", ptyArgs, &channelID); err != nil { - log.Fatal("Failed to request PTY:", err) - } - - var socketPath string - execArgs := &ssh.ExecArgs{ - ChannelID: channelID, - CommandWithArgs: args[1:], - } - - err = client.Call("RPCClient.Run", execArgs, &socketPath) - if err != nil { - log.Fatal(err) - } - - conn, err := dialUnix(socketPath) - if err != nil { - log.Fatal(err) - } - - b := make([]byte, ptyBufferSize) - _, err = conn.Read(b) - if err != nil { - log.Fatal(err) - } - - fmt.Print(string(b)) -} - -func resolveUser(arg string) (username string, pk string, err error) { - components := strings.Split(arg, "@") - if len(components) == 1 { - if u, uErr := user.Current(); uErr != nil { - err = fmt.Errorf("failed to resolve current user: %s", uErr) - } else { - username = u.Username - pk = components[0] - } - - return - } - - username = components[0] - pk = components[1] - return -} - -func init() { - rootCmd.Flags().StringVarP(&rpcAddr, "rpc", "", ":2222", "RPC address to connect to") - rootCmd.Flags().BoolVarP(&ptyMode, "pty", "", false, "Whether to run the command in a simulated PTY or not") - rootCmd.Flags().Uint16VarP(&ptyRows, "ptyrows", "", 100, "PTY Rows. Applicable if run with pty flag") - rootCmd.Flags().Uint16VarP(&ptyCols, "ptycols", "", 100, "PTY Cols. Applicable if run with pty flag") - rootCmd.Flags().Uint16VarP(&ptyX, "ptyx", "", 100, "PTY X. Applicable if run with pty flag") - rootCmd.Flags().Uint16VarP(&ptyY, "ptyy", "", 100, "PTY Y. Applicable if run with pty flag") - rootCmd.Flags().Uint32VarP(&ptyBufferSize, "ptybuffer", "", 1024, "PTY Buffer size to store command output") -} - -// Execute executes root CLI command. -func Execute() { - if err := rootCmd.Execute(); err != nil { - log.Fatal(err) - } -} diff --git a/cmd/therealssh-cli/therealssh-cli.go b/cmd/therealssh-cli/therealssh-cli.go deleted file mode 100644 index 410fcf4ec..000000000 --- a/cmd/therealssh-cli/therealssh-cli.go +++ /dev/null @@ -1,12 +0,0 @@ -/* -CLI for SSH app -*/ -package main - -import ( - "github.com/SkycoinProject/skywire-mainnet/cmd/therealssh-cli/commands" -) - -func main() { - commands.Execute() -} diff --git a/docker/images/node/Dockerfile b/docker/images/node/Dockerfile index 4956fa5ed..4b779dfc1 100644 --- a/docker/images/node/Dockerfile +++ b/docker/images/node/Dockerfile @@ -19,9 +19,7 @@ RUN go build -mod=vendor -tags netgo -ldflags="-w -s" \ go build -mod=vendor -ldflags="-w -s" -o ./apps/skychat.v1.0 ./cmd/apps/skychat &&\ go build -mod=vendor -ldflags="-w -s" -o ./apps/helloworld.v1.0 ./cmd/apps/helloworld &&\ go build -mod=vendor -ldflags="-w -s" -o ./apps/socksproxy.v1.0 ./cmd/apps/therealproxy &&\ - go build -mod=vendor -ldflags="-w -s" -o ./apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-client &&\ - go build -mod=vendor -ldflags="-w -s" -o ./apps/SSH.v1.0 ./cmd/apps/therealssh &&\ - go build -mod=vendor -ldflags="-w -s" -o ./apps/SSH-client.v1.0 ./cmd/apps/therealssh-client + go build -mod=vendor -ldflags="-w -s" -o ./apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-client ## Resulting image diff --git a/integration/InteractiveEnvironments.md b/integration/InteractiveEnvironments.md index b7caa920e..978d8a69e 100644 --- a/integration/InteractiveEnvironments.md +++ b/integration/InteractiveEnvironments.md @@ -9,7 +9,6 @@ - [Environments & scenarios](#environments--scenarios) - [Base Environment](#base-environment) - [Generic Test Environment](#generic-test-environment) - - [SSH Test Environment](#ssh-test-environment) - [Proxy test environment](#proxy-test-environment) - [Preparation](#preparation) - [Scenario. Proxy test #1](#scenario-proxy-test-1) @@ -34,23 +33,17 @@ integration │   ├── env-vars.sh # │   ├── nodeA.json # │   └── nodeC.json # -├── ssh # ssh testing environment -│   ├── env-vars.sh # -│   ├── nodeA.json # -│   └── nodeC.json # ├── InteractiveEnvironments.md # You're reading it ├── intermediary-nodeB.json # NodeB configurationS ├── run-base-env.sh # base environment in detached tmux session ├── run-generic-env.sh # generic environment in tmux ├── run-proxy-env.sh # proxy environment in tmux -├── run-ssh-env.sh # ssh environment in tmux ├── start-restart-nodeB.sh # script for restart in cycle NodeB ├── startup.sh # add transports between nodes ├── tear-down.sh # tear down everything ├── test-messaging-loop.sh # Test script for messaging in infinite loop ├── test-messaging.sh # Test one message between NodeA-NodeC, NodeC-NodeA -├── test-proxy.sh # Test script for proxy -├── test-ssh.sh # Test script for ssh +└── test-proxy.sh # Test script for proxy ``` ## Dependencies @@ -162,56 +155,15 @@ The following steps will be performed: 4. $CHAT_A, $CHAT_B - addresses and ports for `skychat`-apps on node_A and node_C 4. Aliases in shell-window: `CLI_A`, `CLI_B`, `CLI_C` -### SSH Test Environment - -The SSH Test Environment will define the following: - -- skywire-services running on localhost -- 3 `skywire-visor`s: - - NodeA - running `SSH` app - - NodeB - intermediary node without apps - - NodeC - running `SSH-client` app - -**Run** - -```bash -# Tear down everything -$ make integration-teardown - -# Prerequisite -$ echo $PK_C > ~/.therealssh/authorized_keys - -# Start all services and nodes -$ make integration-run-ssh - -# Adds pre-defined transports -$ make integration-startup -``` - -**Tests** - -- **TEST 1** - 1. Run `./integration/run-ssh-env.sh` - it will run: - 1. skywire-services on localhost - 2. NodeA with configured `SSH` app - 3. NodeB - intermediary - 4. NodeC with configured `SSH-client` app - 2. Run `./integration/test-ssh.sh` which will run in cycle: - 1. `./SSH-cli $PK_A "export n=1; loop -n $n echo A"` - 2. kill all `skywire-visor`s - 3. Collect logs - 4. Increase n by power of 2 - 5. Repeat - ### Proxy test environment The proxy test environment will define the following: - skywire-services running on localhost - 3 `skywire-visor`s: - - NodeA - running `SSH` app + - NodeA - running `proxy` app - NodeB - intermediary node without apps - - NodeC - running `SSH-client` app + - NodeC - running `proxy-client` app #### Preparation @@ -248,9 +200,6 @@ It's possible that a service could start earlier or later than needed. Examine windows, in case of failed service - restart it (E.g. `KeyUp`-`Enter`) -Problem still exists in proxy test environment: - - NodeC cannot start `SSH-client` when NodeA is still starting `SSH` - ### Tmux for new users 1. Read `man tmux` diff --git a/integration/generic/nodeA.json b/integration/generic/nodeA.json index 8fe38dd06..eaa8f4ebd 100644 --- a/integration/generic/nodeA.json +++ b/integration/generic/nodeA.json @@ -29,13 +29,6 @@ "port": 1, "args": [] }, - { - "app": "SSH", - "version": "1.0", - "auto_start": true, - "port": 2, - "args": [] - }, { "app": "socksproxy", "version": "1.0", diff --git a/integration/generic/nodeC.json b/integration/generic/nodeC.json index 38d08b5d4..35205b3db 100644 --- a/integration/generic/nodeC.json +++ b/integration/generic/nodeC.json @@ -32,13 +32,6 @@ ":8001" ] }, - { - "app": "SSH-client", - "version": "1.0", - "auto_start": true, - "port": 12, - "args": [] - }, { "app": "socksproxy-client", "version": "1.0", diff --git a/integration/run-ssh-env.sh b/integration/run-ssh-env.sh deleted file mode 100644 index 758d8b01f..000000000 --- a/integration/run-ssh-env.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash - -## SKYWIRE - -tmux new -s skywire -d - -source ./integration/ssh/env-vars.sh - -echo "Checking transport-discovery is up" -curl --retry 5 --retry-connrefused 1 --connect-timeout 5 https://transport.discovery.skywire.skycoin.net/security/nonces/$PK_A - -tmux rename-window -t skywire NodeA -tmux send-keys -t NodeA -l "./skywire-visor ./integration/ssh/nodeA.json --tag NodeA $SYSLOG_OPTS" -tmux send-keys C-m -tmux new-window -t skywire -n NodeB -tmux send-keys -t NodeB -l "./skywire-visor ./integration/intermediary-nodeB.json --tag NodeB $SYSLOG_OPTS" -tmux send-keys C-m -tmux new-window -t skywire -n NodeC -tmux send-keys -t NodeC -l "./skywire-visor ./integration/ssh/nodeC.json --tag NodeC $SYSLOG_OPTS" -tmux send-keys C-m - -tmux new-window -t skywire -n shell - -tmux send-keys -t shell 'source ./integration/ssh/env-vars.sh' C-m - -tmux attach -t skywire diff --git a/integration/ssh/env-vars.sh b/integration/ssh/env-vars.sh deleted file mode 100644 index bf0cab2ad..000000000 --- a/integration/ssh/env-vars.sh +++ /dev/null @@ -1,24 +0,0 @@ -# This script needs to be `source`d from bash-compatible shell -# E.g. `source ./integration/ssh/env-vars.sh` or `. ./integration/ssh/env-vars.sh` -export PK_A=$(jq -r ".node.static_public_key" ./integration/ssh/nodeA.json) -export RPC_A=$(jq -r ".interfaces.rpc" ./integration/ssh/nodeA.json) -export PK_B=$(jq -r ".node.static_public_key" ./integration/intermediary-nodeB.json) -export RPC_B=$(jq -r ".interfaces.rpc" ./integration/intermediary-nodeB.json) -export PK_C=$(jq -r ".node.static_public_key" ./integration/ssh/nodeC.json) -export RPC_C=$(jq -r ".interfaces.rpc" ./integration/ssh/nodeC.json) - -alias CLI_A='./skywire-cli --rpc $RPC_A' -alias CLI_B='./skywire-cli --rpc $RPC_B' -alias CLI_C='./skywire-cli --rpc $RPC_C' - -export MSGD=https://messaging.discovery.skywire.skycoin.net -export TRD=https://transport.discovery.skywire.skycoin.net -export RF=https://routefinder.skywire.skycoin.net - -alias RUN_A='go run ./cmd/skywire-visor ./integration/messaging/nodeA.json --tag NodeA' -alias RUN_B='go run ./cmd/skywire-visor ./integration/intermediary-nodeB.json --tag NodeB' -alias RUN_C='go run ./cmd/skywire-visor ./integration/messaging/nodeC.json --tag NodeC' - -echo PK_A: $PK_A -echo PK_B: $PK_B -echo PK_C: $PK_C diff --git a/integration/ssh/nodeA.json b/integration/ssh/nodeA.json deleted file mode 100644 index 8fe38dd06..000000000 --- a/integration/ssh/nodeA.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "version": "1.0", - "node": { - "static_public_key": "02072dd1e2ccd761e717096e1a264de1d8917e78e3176ca99dbf7ccf7292969845", - "static_secret_key": "7073e557aa2308b448525397ea2f45d56c9962c4dcdf82c5fdb5cc02fca0481c" - }, - "messaging": { - "discovery": "https://messaging.discovery.skywire.skycoin.net", - "server_count": 1 - }, - "transport": { - "discovery": "https://transport.discovery.skywire.skycoin.net", - "log_store": { - "type": "file", - "location": "./local/nodeA/transport_logs" - } - }, - "routing": { - "setup_nodes": [ - "0324579f003e6b4048bae2def4365e634d8e0e3054a20fc7af49daf2a179658557" - ], - "route_finder": "https://routefinder.skywire.skycoin.net/" - }, - "apps": [ - { - "app": "skychat", - "version": "1.0", - "auto_start": true, - "port": 1, - "args": [] - }, - { - "app": "SSH", - "version": "1.0", - "auto_start": true, - "port": 2, - "args": [] - }, - { - "app": "socksproxy", - "version": "1.0", - "auto_start": true, - "port": 3, - "args": [] - } - ], - "trusted_nodes": [], - "hypervisors": [], - "apps_path": "./apps", - "local_path": "./local/nodeA", - "log_level": "info", - "interfaces": { - "rpc": "localhost:3436" - } -} diff --git a/integration/ssh/nodeC.json b/integration/ssh/nodeC.json deleted file mode 100644 index 38d08b5d4..000000000 --- a/integration/ssh/nodeC.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "version": "1.0", - "node": { - "static_public_key": "02c9ddf5c2ae6a5a2166028dafbc814eff3ec2352f429fb0aa37d96e1aa668f332", - "static_secret_key": "5ab3744ab56e4d0b82f9a915e07b8f05d51ec0f16ff8496bd92f4e378ca6c1fc" - }, - "messaging": { - "discovery": "https://messaging.discovery.skywire.skycoin.net", - "server_count": 1 - }, - "transport": { - "discovery": "https://transport.discovery.skywire.skycoin.net", - "log_store": { - "type": "file", - "location": "./local/nodeC/transport_logs" - } - }, - "routing": { - "setup_nodes": [ - "0324579f003e6b4048bae2def4365e634d8e0e3054a20fc7af49daf2a179658557" - ], - "route_finder": "https://routefinder.skywire.skycoin.net/" - }, - "apps": [ - { - "app": "skychat", - "version": "1.0", - "auto_start": true, - "port": 1, - "args": [ - "-addr", - ":8001" - ] - }, - { - "app": "SSH-client", - "version": "1.0", - "auto_start": true, - "port": 12, - "args": [] - }, - { - "app": "socksproxy-client", - "version": "1.0", - "auto_start": true, - "port": 13, - "args": [ - "-srv", - "024ec47420176680816e0406250e7156465e4531f5b26057c9f6297bb0303558c7" - ] - } - ], - "trusted_nodes": [], - "hypervisors": [], - "apps_path": "./apps", - "local_path": "./local/nodeC", - "log_level": "info", - "interfaces": { - "rpc": "localhost:3438" - } -} diff --git a/integration/test-proxy.sh b/integration/test-proxy.sh deleted file mode 100644 index 5ccf5f9e6..000000000 --- a/integration/test-proxy.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env bash - -echo Starting ssh test -echo Press Ctrl-C to exit - -source ./integration/proxy/env-vars.sh - -export N=1 -for i in {1..16} -do - echo Test with $N requests - mkdir -p ./logs/proxy/$N - - echo Killing nodes - echo Killing $(ps aux |grep "[N]odeA\|[N]odeB\|[N]odeC" |awk '{print $2}') - kill $(ps aux |grep "[N]odeA\|[N]odeB\|[N]odeC" |awk '{print $2}') - - # This sleep needed to allow clean exit of node - sleep 10 - - echo Restarting nodeA and NodeB - ./bin/skywire-visor ./integration/proxy/nodeA.json --tag NodeA &> ./logs/proxy/$N/nodeA.log & - ./bin/skywire-visor ./integration/intermediary-nodeB.json --tag NodeB &> ./logs/proxy/$N/nodeB.log & - - # TODO: improve this sleep - sleep 5 - echo Restarting nodeC - ./bin/skywire-visor ./integration/proxy/nodeC.json --tag NodeC &> ./logs/proxy/$N/nodeC.log & - - sleep 20 - echo Trying socks5 proxy - - for ((j=0; j<$N; j++)) - do - echo Request $j - curl -v --retry 5 --retry-connrefused 1 --connect-timeout 5 -x socks5://123456:@localhost:9999 https://www.google.com &>> ./logs/proxy/$N/curl.out - done - - export N=$(($N*2)) -done diff --git a/integration/test-ssh.sh b/integration/test-ssh.sh deleted file mode 100644 index 5bcb91cc4..000000000 --- a/integration/test-ssh.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash - -echo Starting ssh test -echo Press Ctrl-C to exit - -source ./integration/ssh/env-vars.sh - -export N=1 -for i in {1..16} -do - echo Test with $N lines - mkdir -p ./logs/ssh/$N - - echo Killing nodes and SSH-cli - echo Killing $(ps aux |grep "[N]odeA\|[N]odeB\|[N]odeC\|[s]kywire/SSH-cli" |awk '{print $2}') - kill $(ps aux |grep "[N]odeA\|[N]odeB\|[N]odeC\|[s]kywire/SSH-cli" |awk '{print $2}') - - echo Restarting nodes - ./bin/skywire-visor ./integration/ssh/nodeA.json --tag NodeA &> ./logs/ssh/$N/nodeA.log & - ./bin/skywire-visor ./integration/intermediary-nodeB.json --tag NodeB &> ./logs/ssh/$N/nodeB.log & - ./bin/skywire-visor ./integration/ssh/nodeC.json --tag NodeC &> ./logs/ssh/$N/nodeC.log & - - sleep 20 - echo Trying SSH-cli - export CMD=$(echo ./bin/SSH-cli $PK_A \"loop -n $N echo A\") - echo $CMD - eval $CMD &>./logs/ssh/$N/SSH-cli.out - - - export N=$(($N*2)) -done diff --git a/internal/skyenv/const.go b/internal/skyenv/const.go index d2d17c317..25014054e 100644 --- a/internal/skyenv/const.go +++ b/internal/skyenv/const.go @@ -41,14 +41,10 @@ const ( SkychatPort = uint16(1) SkychatAddr = ":8000" - SkysshPort = uint16(2) - SkyproxyName = "socksproxy" SkyproxyVersion = "1.0" SkyproxyPort = uint16(3) - SkysshClientAddr = ":2222" - SkyproxyClientName = "socksproxy-client" SkyproxyClientVersion = "1.0" SkyproxyClientPort = uint16(13) diff --git a/pkg/therealssh/auth.go b/pkg/therealssh/auth.go deleted file mode 100644 index 86115b7e2..000000000 --- a/pkg/therealssh/auth.go +++ /dev/null @@ -1,92 +0,0 @@ -package therealssh - -import ( - "bufio" - "errors" - "fmt" - "os" - "path/filepath" - - "github.com/SkycoinProject/dmsg/cipher" -) - -// Authorizer defines interface for authorization providers. -type Authorizer interface { - Authorize(pk cipher.PubKey) error -} - -// ListAuthorizer performs authorization against static list. -type ListAuthorizer struct { - AuthorizedKeys []cipher.PubKey -} - -// Authorize implements Authorizer for ListAuthorizer -func (auth *ListAuthorizer) Authorize(remotePK cipher.PubKey) error { - for _, key := range auth.AuthorizedKeys { - if remotePK == key { - return nil - } - } - - return errors.New("unknown PubKey") -} - -// FileAuthorizer performs authorization against file that has PubKey per line. -type FileAuthorizer struct { - authFile *os.File -} - -// NewFileAuthorizer constructs new FileAuthorizer -func NewFileAuthorizer(authFile string) (*FileAuthorizer, error) { - path, err := filepath.Abs(authFile) - if err != nil { - return nil, fmt.Errorf("failed to resolve auth file path: %s", err) - } - - f, err := os.Open(filepath.Clean(path)) - if err != nil { - if os.IsNotExist(err) { - if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { - return nil, fmt.Errorf("failed to create auth file: %s", err) - } - if f, err = os.Create(path); err != nil { - return nil, fmt.Errorf("failed to create auth file: %s", err) - } - } else { - return nil, fmt.Errorf("failed to open auth file: %s", err) - } - } - - return &FileAuthorizer{f}, nil -} - -// Close releases underlying file pointer. -func (auth *FileAuthorizer) Close() error { - if auth == nil { - return nil - } - return auth.authFile.Close() -} - -// Authorize implements Authorizer for FileAuthorizer -func (auth *FileAuthorizer) Authorize(remotePK cipher.PubKey) error { - defer func() { - if _, err := auth.authFile.Seek(0, 0); err != nil { - Log.WithError(err).Warn("Failed to seek to the beginning of auth file") - } - }() - - hexPK := remotePK.Hex() - scanner := bufio.NewScanner(auth.authFile) - for scanner.Scan() { - if hexPK == scanner.Text() { - return nil - } - } - - if err := scanner.Err(); err != nil { - return fmt.Errorf("failed to read from auth file: %s", err) - } - - return errors.New("unknown PubKey") -} diff --git a/pkg/therealssh/auth_test.go b/pkg/therealssh/auth_test.go deleted file mode 100644 index 2dd2d3791..000000000 --- a/pkg/therealssh/auth_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package therealssh - -import ( - "io/ioutil" - "os" - "testing" - - "github.com/SkycoinProject/dmsg/cipher" - "github.com/stretchr/testify/require" -) - -func TestListAuthorizer(t *testing.T) { - pk, _ := cipher.GenerateKeyPair() - auth := &ListAuthorizer{[]cipher.PubKey{pk}} - require.Error(t, auth.Authorize(cipher.PubKey{})) - require.NoError(t, auth.Authorize(pk)) -} - -func TestFileAuthorizer(t *testing.T) { - pk, _ := cipher.GenerateKeyPair() - anotherPK, _ := cipher.GenerateKeyPair() - - tmpfile, err := ioutil.TempFile("", "authorized_keys") - require.NoError(t, err) - defer func() { - require.NoError(t, os.Remove(tmpfile.Name())) - }() - - _, err = tmpfile.Write([]byte(pk.Hex() + "\n")) - require.NoError(t, err) - - auth, err := NewFileAuthorizer(tmpfile.Name()) - require.NoError(t, err) - - require.Error(t, auth.Authorize(anotherPK)) - require.NoError(t, auth.Authorize(pk)) - - _, err = tmpfile.Write([]byte(anotherPK.Hex() + "\n")) - require.NoError(t, err) - - require.NoError(t, auth.Authorize(anotherPK)) - require.NoError(t, auth.Authorize(pk)) -} diff --git a/pkg/therealssh/chan_list.go b/pkg/therealssh/chan_list.go deleted file mode 100644 index 5f76ac10d..000000000 --- a/pkg/therealssh/chan_list.go +++ /dev/null @@ -1,54 +0,0 @@ -package therealssh - -import "sync" - -type chanList struct { - sync.Mutex - - chans []*SSHChannel -} - -func newChanList() *chanList { - return &chanList{chans: []*SSHChannel{}} -} - -func (c *chanList) add(sshCh *SSHChannel) uint32 { - c.Lock() - defer c.Unlock() - - for i := range c.chans { - if c.chans[i] == nil { - c.chans[i] = sshCh - return uint32(i) - } - } - - c.chans = append(c.chans, sshCh) - return uint32(len(c.chans) - 1) -} - -func (c *chanList) getChannel(id uint32) *SSHChannel { - c.Lock() - defer c.Unlock() - - if id < uint32(len(c.chans)) { - return c.chans[id] - } - - return nil -} - -func (c *chanList) dropAll() []*SSHChannel { - c.Lock() - defer c.Unlock() - var r []*SSHChannel - - for _, ch := range c.chans { - if ch == nil { - continue - } - r = append(r, ch) - } - c.chans = nil - return r -} diff --git a/pkg/therealssh/channel.go b/pkg/therealssh/channel.go deleted file mode 100644 index a2d1a4f02..000000000 --- a/pkg/therealssh/channel.go +++ /dev/null @@ -1,364 +0,0 @@ -package therealssh - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "net" - "os" - "os/user" - "path/filepath" - "strings" - "sync" - - "github.com/SkycoinProject/skywire-mainnet/internal/skyenv" - - "github.com/SkycoinProject/dmsg/cipher" - "github.com/creack/pty" - - "github.com/SkycoinProject/skywire-mainnet/pkg/routing" -) - -// Port reserved for SSH app -const Port = routing.Port(skyenv.SkysshPort) - -// Debug enables debug messages. -var Debug = false - -// SSHChannel defines communication channel parameters. -type SSHChannel struct { - RemoteID uint32 - RemoteAddr routing.Addr - - conn net.Conn - msgCh chan []byte - - session *Session - listenerMx sync.Mutex - listener *net.UnixListener - - dataChMx sync.Mutex - dataCh chan []byte - - doneOnce sync.Once - done chan struct{} -} - -// OpenChannel constructs new SSHChannel with empty Session. -func OpenChannel(remoteID uint32, remoteAddr routing.Addr, conn net.Conn) *SSHChannel { - return &SSHChannel{RemoteID: remoteID, conn: conn, RemoteAddr: remoteAddr, msgCh: make(chan []byte), - dataCh: make(chan []byte), done: make(chan struct{})} -} - -// OpenClientChannel constructs new client SSHChannel with empty Session. -func OpenClientChannel(remoteID uint32, remotePK cipher.PubKey, conn net.Conn) *SSHChannel { - ch := OpenChannel(remoteID, routing.Addr{PubKey: remotePK, Port: Port}, conn) - return ch -} - -// Send sends command message. -func (sshCh *SSHChannel) Send(cmd CommandType, payload []byte) error { - data := appendU32([]byte{byte(cmd)}, sshCh.RemoteID) - _, err := sshCh.conn.Write(append(data, payload...)) - return err -} - -func (sshCh *SSHChannel) Read(p []byte) (int, error) { - data, more := <-sshCh.dataCh - if !more { - return 0, io.EOF - } - - return copy(p, data), nil -} - -func (sshCh *SSHChannel) Write(p []byte) (n int, err error) { - n = len(p) - err = sshCh.Send(CmdChannelData, p) - return -} - -// Request sends request message and waits for response. -func (sshCh *SSHChannel) Request(requestType RequestType, payload []byte) ([]byte, error) { - Log.Debugf("sending request %x", requestType) - req := append([]byte{byte(requestType)}, payload...) - - if err := sshCh.Send(CmdChannelRequest, req); err != nil { - return nil, fmt.Errorf("request failure: %s", err) - } - - data := <-sshCh.msgCh - if data[0] == ResponseFail { - return nil, fmt.Errorf("request failure: %s", string(data[1:])) - } - - return data[1:], nil -} - -// Serve starts request handling loop. -func (sshCh *SSHChannel) Serve() error { - for data := range sshCh.msgCh { - var err error - Log.Debugf("new request %x", data[0]) - switch RequestType(data[0]) { - case RequestPTY: - var u *user.User - u, err = user.Lookup(string(data[17:])) - if err != nil { - break - } - - cols := binary.BigEndian.Uint32(data[1:]) - rows := binary.BigEndian.Uint32(data[5:]) - width := binary.BigEndian.Uint32(data[9:]) - height := binary.BigEndian.Uint32(data[13:]) - size := &pty.Winsize{Cols: uint16(cols), Rows: uint16(rows), X: uint16(width), Y: uint16(height)} - err = sshCh.OpenPTY(u, size) - case RequestShell: - err = sshCh.Shell() - case RequestExec: - err = sshCh.Start(string(data[1:])) - case RequestExecWithoutShell: - err = sshCh.Run(string(data[1:])) - case RequestWindowChange: - cols := binary.BigEndian.Uint32(data[1:]) - rows := binary.BigEndian.Uint32(data[5:]) - width := binary.BigEndian.Uint32(data[9:]) - height := binary.BigEndian.Uint32(data[13:]) - err = sshCh.WindowChange(&pty.Winsize{Cols: uint16(cols), Rows: uint16(rows), X: uint16(width), Y: uint16(height)}) - } - - var res []byte - if err != nil { - res = append([]byte{ResponseFail}, []byte(err.Error())...) - } else { - res = []byte{ResponseConfirm} - } - - if err := sshCh.Send(CmdChannelResponse, res); err != nil { - return fmt.Errorf("failed to respond: %s", err) - } - } - - return nil -} - -// SocketPath returns unix socket location. This socket is normally -// used by the CLI to exchange PTY data with a client app. -func (sshCh *SSHChannel) SocketPath() string { - return filepath.Join(os.TempDir(), fmt.Sprintf("therealsshd-%d", sshCh.RemoteID)) -} - -// ServeSocket starts socket handling loop. -func (sshCh *SSHChannel) ServeSocket() error { - if err := os.Remove(sshCh.SocketPath()); err != nil { - Log.WithError(err).Warn("Failed to remove SSH channel socket file") - } - - Log.Debugf("waiting for new socket connections on: %s", sshCh.SocketPath()) - l, err := net.ListenUnix("unix", &net.UnixAddr{Name: sshCh.SocketPath(), Net: "unix"}) - if err != nil { - return fmt.Errorf("failed to open unix socket: %s", err) - } - - sshCh.listenerMx.Lock() - sshCh.listener = l - sshCh.listenerMx.Unlock() - conn, err := l.AcceptUnix() - if err != nil { - return fmt.Errorf("failed to accept connection: %s", err) - } - - Log.Debugln("got new socket connection") - defer func() { - if err := conn.Close(); err != nil { - Log.WithError(err).Warn("Failed to close connection") - } - if err := sshCh.closeListener(); err != nil { - Log.WithError(err).Warn("Failed to close listener") - } - if err := os.Remove(sshCh.SocketPath()); err != nil { - Log.WithError(err).Warn("Failed to close SSH channel socket file") - } - }() - - go func() { - if _, err := io.Copy(sshCh, conn); err != nil && !strings.Contains(err.Error(), "use of closed network connection") { - Log.Errorf("failed to write to server:", err) - return - } - }() - - if _, err := io.Copy(conn, sshCh); err != nil { - return fmt.Errorf("failed to write to client: %s", err) - } - - return nil -} - -// OpenPTY creates new PTY Session for the Channel. -func (sshCh *SSHChannel) OpenPTY(user *user.User, sz *pty.Winsize) (err error) { - if sshCh.session != nil { - return errors.New("session is already started") - } - - Log.Debugf("starting new session for %s with %#v", user.Username, sz) - sshCh.session, err = OpenSession(user, sz) - if err != nil { - sshCh.session = nil - return - } - - return -} - -// Shell starts shell process on Channel's PTY session. -func (sshCh *SSHChannel) Shell() error { - return sshCh.Start("shell") -} - -// Start executes provided command on Channel's PTY session. -func (sshCh *SSHChannel) Start(command string) error { - if sshCh.session == nil { - return errors.New("session is not started") - } - - go func() { - if err := sshCh.serveSession(); err != nil { - Log.Error("Session failure:", err) - } - }() - - Log.Debugf("starting new pty process %s", command) - return sshCh.session.Start(command) -} - -// Run executes provided command on Channel's PTY session and returns output as []byte. -func (sshCh *SSHChannel) Run(command string) error { - if sshCh.session == nil { - return errors.New("session is not started") - } - - out, err := sshCh.session.Run(command) - if err != nil { - return err - } - - go func() { - _, err := sshCh.Write(out) - if err != nil { - Log.Warn("error writing to channel: ", err) - } - }() - return err -} - -func (sshCh *SSHChannel) serveSession() error { - defer func() { - if err := sshCh.Send(CmdChannelServerClose, nil); err != nil { - Log.WithError(err).Warn("Failed to send to SSH channel") - } - if err := sshCh.Close(); err != nil { - Log.WithError(err).Warn("Failed to close SSH channel") - } - }() - - go func() { - if _, err := io.Copy(sshCh.session, sshCh); err != nil { - Log.Error("PTY copy: ", err) - return - } - }() - - _, err := io.Copy(sshCh, sshCh.session) - if err != nil && !strings.Contains(err.Error(), "input/output error") { - return fmt.Errorf("client copy: %s", err) - } - - return nil -} - -// WindowChange resize PTY Session size. -func (sshCh *SSHChannel) WindowChange(sz *pty.Winsize) error { - if sshCh.session == nil { - return errors.New("session is not started") - } - - return sshCh.session.WindowChange(sz) -} - -func (sshCh *SSHChannel) close() (closed bool, err error) { - sshCh.doneOnce.Do(func() { - closed = true - - close(sshCh.done) - - select { - case <-sshCh.dataCh: - default: - sshCh.dataChMx.Lock() - close(sshCh.dataCh) - sshCh.dataChMx.Unlock() - } - close(sshCh.msgCh) - - var sErr, lErr error - if sshCh.session != nil { - sErr = sshCh.session.Close() - } - - lErr = sshCh.closeListener() - - if sErr != nil { - err = sErr - return - } - - if lErr != nil { - err = lErr - } - }) - - return closed, err -} - -// Close safely closes Channel resources. -func (sshCh *SSHChannel) Close() error { - if sshCh == nil { - return nil - } - - closed, err := sshCh.close() - if err != nil { - return err - } - if !closed { - return errors.New("channel is already closed") - } - - return nil -} - -// IsClosed returns whether the Channel is closed. -func (sshCh *SSHChannel) IsClosed() bool { - select { - case <-sshCh.done: - return true - default: - return false - } -} - -func (sshCh *SSHChannel) closeListener() error { - sshCh.listenerMx.Lock() - defer sshCh.listenerMx.Unlock() - - return sshCh.listener.Close() -} - -func appendU32(buf []byte, n uint32) []byte { - uintBuf := make([]byte, 4) - binary.BigEndian.PutUint32(uintBuf[0:], n) - return append(buf, uintBuf...) -} diff --git a/pkg/therealssh/channel_pty_test.go b/pkg/therealssh/channel_pty_test.go deleted file mode 100644 index 8b2004e7e..000000000 --- a/pkg/therealssh/channel_pty_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// +build !no_ci - -package therealssh - -import ( - "net" - "os/user" - "testing" - "time" - - "github.com/SkycoinProject/dmsg/cipher" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/SkycoinProject/skywire-mainnet/pkg/routing" -) - -func TestChannelServe(t *testing.T) { - in, out := net.Pipe() - ch := OpenChannel(1, routing.Addr{PubKey: cipher.PubKey{}, Port: Port}, in) - - errCh := make(chan error) - go func() { - errCh <- ch.Serve() - }() - - req := appendU32([]byte{byte(RequestPTY)}, 10) - req = appendU32(req, 20) - req = appendU32(req, 0) - req = appendU32(req, 0) - u, err := user.Current() - require.NoError(t, err) - req = append(req, []byte(u.Username)...) - ch.msgCh <- req - time.Sleep(100 * time.Millisecond) - - buf := make([]byte, 6) - _, err = out.Read(buf) - require.NoError(t, err) - assert.EqualValues(t, CmdChannelResponse, buf[0]) - assert.Equal(t, ResponseConfirm, buf[5]) - - require.NotNil(t, ch.session) - - ch.msgCh <- []byte{byte(RequestShell)} - time.Sleep(100 * time.Millisecond) - - buf = make([]byte, 6) - _, err = out.Read(buf) - require.NoError(t, err) - assert.EqualValues(t, CmdChannelResponse, buf[0]) - assert.Equal(t, ResponseConfirm, buf[5]) - - buf = make([]byte, 10) - _, err = out.Read(buf) - require.NoError(t, err) - assert.EqualValues(t, CmdChannelData, buf[0]) - assert.NotNil(t, buf[5:]) - - require.NotNil(t, ch.dataCh) - ch.dataCh <- []byte("echo foo\n") - time.Sleep(100 * time.Millisecond) - - buf = make([]byte, 15) - _, err = out.Read(buf) - require.NoError(t, err) - assert.EqualValues(t, CmdChannelData, buf[0]) - assert.Contains(t, string(buf[5:]), "echo foo") - - buf = make([]byte, 15) - _, err = out.Read(buf) - require.NoError(t, err) - assert.EqualValues(t, CmdChannelData, buf[0]) - assert.Contains(t, string(buf[5:]), "foo") - - req = appendU32([]byte{byte(RequestWindowChange)}, 40) - req = appendU32(req, 50) - req = appendU32(req, 0) - req = appendU32(req, 0) - ch.msgCh <- req - time.Sleep(100 * time.Millisecond) - - buf = make([]byte, 6) - _, err = out.Read(buf) - require.NoError(t, err) - assert.EqualValues(t, CmdChannelResponse, buf[0]) - assert.Equal(t, ResponseConfirm, buf[5]) - - require.NoError(t, ch.Close()) - require.NoError(t, <-errCh) -} diff --git a/pkg/therealssh/channel_test.go b/pkg/therealssh/channel_test.go deleted file mode 100644 index b92ab90ba..000000000 --- a/pkg/therealssh/channel_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package therealssh - -import ( - "encoding/binary" - "io" - "net" - "os" - "path/filepath" - "testing" - "time" - - "github.com/SkycoinProject/dmsg/cipher" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/SkycoinProject/skywire-mainnet/internal/testhelpers" - "github.com/SkycoinProject/skywire-mainnet/pkg/routing" -) - -func TestChannelSendWrite(t *testing.T) { - pk, _ := cipher.GenerateKeyPair() - in, out := net.Pipe() - ch := OpenChannel(1, routing.Addr{PubKey: pk, Port: Port}, in) - - errCh := make(chan error) - go func() { - errCh <- ch.Send(CmdChannelOpen, []byte("foo")) - }() - - buf := make([]byte, 8) - _, err := out.Read(buf) - require.NoError(t, err) - require.NoError(t, <-errCh) - assert.Equal(t, byte(CmdChannelOpen), buf[0]) - assert.Equal(t, uint32(1), binary.BigEndian.Uint32(buf[1:])) - assert.Equal(t, []byte("foo"), buf[5:]) - - go func() { - _, err := ch.Write([]byte("foo")) - errCh <- err - }() - - buf = make([]byte, 8) - _, err = out.Read(buf) - require.NoError(t, err) - require.NoError(t, <-errCh) - assert.Equal(t, byte(CmdChannelData), buf[0]) - assert.Equal(t, []byte("foo"), buf[5:]) -} - -func TestChannelRead(t *testing.T) { - ch := OpenChannel(1, routing.Addr{PubKey: cipher.PubKey{}, Port: Port}, nil) - - buf := make([]byte, 3) - go func() { - ch.dataCh <- []byte("foo") - }() - - _, err := ch.Read(buf) - require.NoError(t, err) - assert.Equal(t, []byte("foo"), buf) - - close(ch.dataCh) - _, err = ch.Read(buf) - require.Error(t, err) - assert.Equal(t, io.EOF, err) -} - -func TestChannelRequest(t *testing.T) { - in, out := net.Pipe() - ch := OpenChannel(1, routing.Addr{PubKey: cipher.PubKey{}, Port: Port}, in) - - type data struct { - res []byte - err error - } - resCh := make(chan data) - go func() { - res, err := ch.Request(RequestPTY, []byte("foo")) - resCh <- data{res, err} - }() - - buf := make([]byte, 9) - _, err := out.Read(buf) - require.NoError(t, err) - assert.Equal(t, byte(CmdChannelOpen), buf[5]) - assert.Equal(t, []byte("foo"), buf[6:]) - - ch.msgCh <- []byte{ResponseConfirm, 0x4} - d := <-resCh - require.NoError(t, d.err) - assert.Equal(t, []byte{0x4}, d.res) -} - -func TestChannelServeSocket(t *testing.T) { - in, out := net.Pipe() - ch := OpenChannel(1, routing.Addr{PubKey: cipher.PubKey{}, Port: Port}, in) - - assert.Equal(t, filepath.Join(os.TempDir(), "therealsshd-1"), ch.SocketPath()) - - serveErr := make(chan error, 1) - go func() { - serveErr <- ch.ServeSocket() - }() - - time.Sleep(100 * time.Millisecond) - conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: ch.SocketPath(), Net: "unix"}) - require.NoError(t, err) - - _, err = conn.Write([]byte("foo")) - require.NoError(t, err) - time.Sleep(100 * time.Millisecond) - - buf := make([]byte, 8) - _, err = out.Read(buf) - require.NoError(t, err) - assert.Equal(t, byte(CmdChannelData), buf[0]) - assert.Equal(t, []byte("foo"), buf[5:]) - - ch.dataCh <- []byte("bar") - time.Sleep(100 * time.Millisecond) - - buf = make([]byte, 3) - _, err = conn.Read(buf) - require.NoError(t, err) - assert.Equal(t, []byte("bar"), buf) - - require.NoError(t, ch.Close()) - require.NoError(t, testhelpers.WithinTimeout(serveErr)) -} diff --git a/pkg/therealssh/client.go b/pkg/therealssh/client.go deleted file mode 100644 index 162c35137..000000000 --- a/pkg/therealssh/client.go +++ /dev/null @@ -1,314 +0,0 @@ -package therealssh - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "net" - "net/rpc" - "strings" - "time" - - "github.com/SkycoinProject/dmsg/cipher" - "github.com/creack/pty" - - "github.com/SkycoinProject/skywire-mainnet/internal/netutil" - "github.com/SkycoinProject/skywire-mainnet/pkg/app/appnet" - "github.com/SkycoinProject/skywire-mainnet/pkg/routing" -) - -var r = netutil.NewRetrier(50*time.Millisecond, 5, 2) - -// Client proxies CLI's requests to a remote server. Control messages -// are sent via RPC interface. PTY data is exchanged via unix socket. -type Client struct { - dialer dialer - chans *chanList -} - -// NewClient construct new RPC listener and Client from a given RPC address and app dialer. -func NewClient(rpcAddr string, d dialer) (net.Listener, *Client, error) { - client := &Client{chans: newChanList(), dialer: d} - rpcClient := &RPCClient{client} - if err := rpc.Register(rpcClient); err != nil { - return nil, nil, fmt.Errorf("RPC register failure: %s", err) - } - rpc.HandleHTTP() - l, err := net.Listen("tcp", rpcAddr) - if err != nil { - return nil, nil, fmt.Errorf("RPC listen failure: %s", err) - } - - return l, client, nil -} - -// OpenChannel requests new Channel on the remote Server. -func (c *Client) OpenChannel(remotePK cipher.PubKey) (localID uint32, sshCh *SSHChannel, cErr error) { - var conn net.Conn - var err error - - err = r.Do(func() error { - conn, err = c.dialer.Dial(appnet.Addr{ - Net: appnet.TypeSkynet, - PubKey: remotePK, - Port: Port, - }) - return err - }) - if err != nil { - cErr = fmt.Errorf("dial failed: %s", err) - return - } - - sshCh = OpenClientChannel(0, remotePK, conn) - Log.Debugln("sending channel open command") - localID = c.chans.add(sshCh) - req := appendU32([]byte{byte(CmdChannelOpen)}, localID) - if _, err := conn.Write(req); err != nil { - cErr = fmt.Errorf("failed to send open channel request: %s", err) - return - } - - go func() { - if err := c.serveConn(conn); err != nil { - Log.Error(err) - } - }() - - Log.Debugln("waiting for channel open response") - data := <-sshCh.msgCh - Log.Debugln("got channel open response") - if data[0] == ResponseFail { - cErr = fmt.Errorf("failed to open channel: %s", string(data[1:])) - return - } - - sshCh.RemoteID = binary.BigEndian.Uint32(data[1:]) - return localID, sshCh, cErr -} - -func (c *Client) resolveChannel(remotePK cipher.PubKey, localID uint32) (*SSHChannel, error) { - sshCh := c.chans.getChannel(localID) - if sshCh == nil { - return nil, errors.New("channel is not opened") - } - - if sshCh.RemoteAddr.PubKey != remotePK { - return nil, errors.New("unauthorized") - } - - return sshCh, nil -} - -// Route defines routing rules for received App messages. -func (c *Client) serveConn(conn net.Conn) error { - for { - buf := make([]byte, 32*1024) - n, err := conn.Read(buf) - if err != nil { - if err == io.EOF { - return nil - } - return err - } - - raddr := conn.RemoteAddr().(routing.Addr) - payload := buf[:n] - - if len(payload) < 5 { - return errors.New("corrupted payload") - } - - sshCh, err := c.resolveChannel(raddr.PubKey, binary.BigEndian.Uint32(payload[1:])) - if err != nil { - return err - } - - data := payload[5:] - Log.Debugf("got new command: %x", payload[0]) - switch CommandType(payload[0]) { - case CmdChannelOpenResponse, CmdChannelResponse: - sshCh.msgCh <- data - case CmdChannelData: - sshCh.dataChMx.Lock() - if !sshCh.IsClosed() { - sshCh.dataCh <- data - } - sshCh.dataChMx.Unlock() - case CmdChannelServerClose: - err = sshCh.Close() - default: - err = fmt.Errorf("unknown command: %x", payload[0]) - } - - if err != nil { - return err - } - } -} - -// Close closes all opened channels. -func (c *Client) Close() error { - if c == nil { - return nil - } - - for _, sshCh := range c.chans.dropAll() { - if err := sshCh.Close(); err != nil { - Log.WithError(err).Warn("Failed to close SSH channel") - } - } - - return nil -} - -// RPCClient exposes Client's methods via RPC interface. -type RPCClient struct { - c *Client -} - -// RequestPTY defines RPC request for a new PTY session. -func (rpc *RPCClient) RequestPTY(args *RequestPTYArgs, channelID *uint32) error { - Log.Debugln("requesting SSH channel") - localID, channel, err := rpc.c.OpenChannel(args.RemotePK) - if err != nil { - return err - } - - Log.Debugln("requesting PTY session") - if _, err := channel.Request(RequestPTY, args.ToBinary()); err != nil { - return fmt.Errorf("PTY request failure: %s", err) - } - - *channelID = localID - return nil -} - -// Exec defines new remote execution RPC request. -func (rpc *RPCClient) Exec(args *ExecArgs, socketPath *string) error { - sshCh := rpc.c.chans.getChannel(args.ChannelID) - if sshCh == nil { - return errors.New("unknown channel") - } - - Log.Debugln("requesting shell process") - if args.CommandWithArgs == nil { - if _, err := sshCh.Request(RequestShell, nil); err != nil { - return fmt.Errorf("shell request failure: %s", err) - } - } else { - if _, err := sshCh.Request(RequestExec, args.ToBinary()); err != nil { - return fmt.Errorf("shell request failure: %s", err) - } - } - - waitCh := make(chan bool) - go func() { - Log.Debugln("starting socket listener") - waitCh <- true - if err := sshCh.ServeSocket(); err != nil { - Log.Error("Session failure:", err) - } - }() - - *socketPath = sshCh.SocketPath() - <-waitCh - return nil -} - -// Run defines new remote shell-less execution RPC request. -func (rpc *RPCClient) Run(args *ExecArgs, socketPath *string) error { - sshCh := rpc.c.chans.getChannel(args.ChannelID) - if sshCh == nil { - return errors.New("unknown channel") - } - - Log.Debugln("requesting shell-less process execution") - if _, err := sshCh.Request(RequestExecWithoutShell, args.ToBinary()); err != nil { - return fmt.Errorf("run command request failure: %s", err) - } - - waitCh := make(chan bool) - go func() { - Log.Debugln("starting socket listener") - waitCh <- true - if err := sshCh.ServeSocket(); err != nil { - Log.Error("Session failure:", err) - } - }() - - *socketPath = sshCh.SocketPath() - - <-waitCh - return nil -} - -// WindowChange defines window size change RPC request. -func (rpc *RPCClient) WindowChange(args *WindowChangeArgs, _ *int) error { - sshCh := rpc.c.chans.getChannel(args.ChannelID) - if sshCh == nil { - return errors.New("unknown ssh channel") - } - - if _, err := sshCh.Request(RequestWindowChange, args.ToBinary()); err != nil { - return fmt.Errorf("window change request failure: %s", err) - } - - return nil -} - -// Close defines close client RPC request. -func (rpc *RPCClient) Close(channelID *uint32, _ *struct{}) error { - if rpc == nil { - return nil - } - - sshCh := rpc.c.chans.getChannel(*channelID) - if sshCh == nil { - return errors.New("unknown ssh channel") - } - - return sshCh.conn.Close() -} - -// RequestPTYArgs defines RequestPTY request parameters. -type RequestPTYArgs struct { - Username string - RemotePK cipher.PubKey - Size *pty.Winsize -} - -// ToBinary returns binary representation of Args. -func (args *RequestPTYArgs) ToBinary() []byte { - req := appendU32([]byte{}, uint32(args.Size.Cols)) - req = appendU32(req, uint32(args.Size.Rows)) - req = appendU32(req, uint32(args.Size.X)) - req = appendU32(req, uint32(args.Size.Y)) - return append(req, []byte(args.Username)...) -} - -// ExecArgs represents Exec response parameters. -type ExecArgs struct { - ChannelID uint32 - CommandWithArgs []string -} - -// ToBinary returns binary representation of Args. -func (args *ExecArgs) ToBinary() []byte { - return append([]byte{}, []byte(strings.Join(args.CommandWithArgs, " "))...) -} - -// WindowChangeArgs defines WindowChange request parameters. -type WindowChangeArgs struct { - ChannelID uint32 - Size *pty.Winsize -} - -// ToBinary returns binary representation of Args. -func (args *WindowChangeArgs) ToBinary() []byte { - req := appendU32([]byte{}, uint32(args.Size.Cols)) - req = appendU32(req, uint32(args.Size.Rows)) - req = appendU32(req, uint32(args.Size.X)) - return appendU32(req, uint32(args.Size.Y)) -} diff --git a/pkg/therealssh/client_test.go b/pkg/therealssh/client_test.go deleted file mode 100644 index 7b49184ed..000000000 --- a/pkg/therealssh/client_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package therealssh - -import ( - "encoding/binary" - "net" - "testing" - - "github.com/SkycoinProject/dmsg/cipher" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/SkycoinProject/skywire-mainnet/pkg/app/appnet" - "github.com/SkycoinProject/skywire-mainnet/pkg/routing" -) - -func TestClientOpenChannel(t *testing.T) { - pk, _ := cipher.GenerateKeyPair() - conn, dialer := newPipeDialer() - c := &Client{dialer, newChanList()} - - type data struct { - ch *SSHChannel - err error - } - resCh := make(chan data) - go func() { - _, ch, err := c.OpenChannel(pk) - resCh <- data{ch, err} - }() - - buf := make([]byte, 5) - _, err := conn.Read(buf) - require.NoError(t, err) - assert.Equal(t, byte(CmdChannelOpen), buf[0]) - assert.Equal(t, uint32(0), binary.BigEndian.Uint32(buf[1:])) - - ch := c.chans.getChannel(0) - require.NotNil(t, ch) - ch.msgCh <- appendU32([]byte{ResponseConfirm}, 4) - - d := <-resCh - require.NoError(t, d.err) - require.NotNil(t, d.ch) - assert.Equal(t, uint32(4), d.ch.RemoteID) - assert.Equal(t, pk, d.ch.RemoteAddr.PubKey) -} - -func TestClientHandleResponse(t *testing.T) { - pk, _ := cipher.GenerateKeyPair() - c := &Client{nil, newChanList()} - in, out := net.Pipe() - errCh := make(chan error) - go func() { - errCh <- c.serveConn(&mockConn{out, routing.Addr{PubKey: pk, Port: Port}}) - }() - - _, err := in.Write(appendU32([]byte{byte(CmdChannelResponse)}, 0)) - require.NoError(t, err) - assert.Equal(t, "channel is not opened", (<-errCh).Error()) - - go func() { - errCh <- c.serveConn(&mockConn{out, routing.Addr{PubKey: cipher.PubKey{}, Port: Port}}) - }() - - ch := OpenChannel(4, routing.Addr{PubKey: pk, Port: Port}, nil) - c.chans.add(ch) - - _, err = in.Write(appendU32([]byte{byte(CmdChannelResponse)}, 0)) - require.NoError(t, err) - assert.Equal(t, "unauthorized", (<-errCh).Error()) - - go func() { - errCh <- c.serveConn(&mockConn{out, routing.Addr{PubKey: pk, Port: Port}}) - }() - dataCh := make(chan []byte) - go func() { - dataCh <- <-ch.msgCh - }() - - data := append(appendU32([]byte{byte(CmdChannelResponse)}, 0), []byte("foo")...) - _, err = in.Write(data) - require.NoError(t, err) - assert.Equal(t, []byte("foo"), <-dataCh) -} - -type pipeDialer struct { - conn net.Conn -} - -func newPipeDialer() (net.Conn, *pipeDialer) { - in, out := net.Pipe() - return out, &pipeDialer{in} -} - -func (d *pipeDialer) Dial(raddr appnet.Addr) (net.Conn, error) { - return d.conn, nil -} - -type mockConn struct { - net.Conn - addr routing.Addr -} - -func (conn *mockConn) RemoteAddr() net.Addr { - return conn.addr -} diff --git a/pkg/therealssh/dialer.go b/pkg/therealssh/dialer.go deleted file mode 100644 index 31af77942..000000000 --- a/pkg/therealssh/dialer.go +++ /dev/null @@ -1,12 +0,0 @@ -package therealssh - -import ( - "net" - - "github.com/SkycoinProject/skywire-mainnet/pkg/app/appnet" -) - -// dialer dials to a remote node. -type dialer interface { - Dial(raddr appnet.Addr) (net.Conn, error) -} diff --git a/pkg/therealssh/pty_test.go b/pkg/therealssh/pty_test.go deleted file mode 100644 index e65606f1b..000000000 --- a/pkg/therealssh/pty_test.go +++ /dev/null @@ -1,100 +0,0 @@ -// +build dragonfly freebsd linux netbsd openbsd - -package therealssh - -import ( - "net" - "net/http" - "net/rpc" - "os/user" - "testing" - - "github.com/SkycoinProject/dmsg/cipher" - "github.com/SkycoinProject/skycoin/src/util/logging" - "github.com/creack/pty" - "github.com/stretchr/testify/require" - - "github.com/SkycoinProject/skywire-mainnet/pkg/app/appnet" - "github.com/SkycoinProject/skywire-mainnet/pkg/routing" -) - -func TestRunRPC(t *testing.T) { - dialConn, acceptConn := net.Pipe() - pd := PipeDialer{PipeWithRoutingAddr{dialConn}, acceptConn} - rpcC, client, err := NewClient(":9998", pd) - require.NoError(t, err) - defer func() { - require.NoError(t, client.Close()) - }() - - server := NewServer(MockAuthorizer{}, logging.NewMasterLogger()) - go func() { - server.Serve(PipeWithRoutingAddr{acceptConn}) // nolint - }() - - go func() { - http.Serve(rpcC, nil) // nolint - }() - - rpcD, err := rpc.DialHTTP("tcp", ":9998") - require.NoError(t, err) - - cuser, err := user.Current() - require.NoError(t, err) - - ptyArgs := &RequestPTYArgs{ - Username: cuser.Username, - RemotePK: cipher.PubKey{}, - Size: &pty.Winsize{ - Rows: 100, - Cols: 100, - X: 100, - Y: 100, - }, - } - var channel uint32 - err = rpcD.Call("RPCClient.RequestPTY", ptyArgs, &channel) - require.NoError(t, err) - - var socketPath string - execArgs := &ExecArgs{ - ChannelID: channel, - CommandWithArgs: []string{"ls"}, - } - - err = rpcD.Call("RPCClient.Run", execArgs, &socketPath) - require.NoError(t, err) - - conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: socketPath, Net: "unix"}) - require.NoError(t, err) - - b := make([]byte, 6024) - _, err = conn.Read(b) - require.NoError(t, err) - require.Contains(t, string(b), "pty_test.go") -} - -type MockAuthorizer struct{} - -func (MockAuthorizer) Authorize(pk cipher.PubKey) error { - return nil -} - -type PipeDialer struct { - dialConn, acceptConn net.Conn -} - -func (p PipeDialer) Dial(raddr appnet.Addr) (c net.Conn, err error) { - return p.dialConn, nil -} - -type PipeWithRoutingAddr struct { - net.Conn -} - -func (p PipeWithRoutingAddr) RemoteAddr() net.Addr { - return routing.Addr{ - PubKey: cipher.PubKey{}, - Port: 9999, - } -} diff --git a/pkg/therealssh/server.go b/pkg/therealssh/server.go deleted file mode 100644 index 9b1c74958..000000000 --- a/pkg/therealssh/server.go +++ /dev/null @@ -1,196 +0,0 @@ -package therealssh - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "net" - - "github.com/SkycoinProject/dmsg/cipher" - "github.com/SkycoinProject/skycoin/src/util/logging" - - "github.com/SkycoinProject/skywire-mainnet/pkg/routing" -) - -// CommandType represents global protocol messages. -type CommandType byte - -const ( - // CmdChannelOpen represents channel open message. - CmdChannelOpen CommandType = iota - // CmdChannelOpenResponse represents channel open response message. - CmdChannelOpenResponse - // CmdChannelRequest represents request message. - CmdChannelRequest - // CmdChannelResponse represents response message. - CmdChannelResponse - // CmdChannelData represents data message. - CmdChannelData - // CmdChannelServerClose represents server message about closing channel. - CmdChannelServerClose -) - -// RequestType represents channel requests types. -type RequestType byte - -const ( - // RequestPTY represents request for new PTY session. - RequestPTY RequestType = iota - // RequestShell represents request for new shell. - RequestShell - // RequestExec represents request for new process. - RequestExec - // RequestExecWithoutShell for use in integration testing. - RequestExecWithoutShell - // RequestWindowChange represents request for PTY size change. - RequestWindowChange -) - -const ( - // ResponseFail represents failed response. - ResponseFail byte = iota - // ResponseConfirm represents successful response. - ResponseConfirm -) - -var responseUnauthorized = append([]byte{ResponseFail}, []byte("unauthorized")...) - -// Server handles remote PTY data exchange. -type Server struct { - log *logging.Logger - auth Authorizer - chans *chanList -} - -// NewServer constructs new Server. -func NewServer(auth Authorizer, log *logging.MasterLogger) *Server { - return &Server{log.PackageLogger("therealssh_server"), auth, newChanList()} -} - -// OpenChannel opens new client channel. -func (s *Server) OpenChannel(remoteAddr routing.Addr, remoteID uint32, conn net.Conn) error { - Log.Debugln("opening new channel") - channel := OpenChannel(remoteID, remoteAddr, conn) - var res []byte - - if s.auth.Authorize(remoteAddr.PubKey) != nil { - res = responseUnauthorized - } else { - res = appendU32([]byte{ResponseConfirm}, s.chans.add(channel)) - } - - s.log.Debugln("sending response") - if err := channel.Send(CmdChannelOpenResponse, res); err != nil { - if err := channel.Close(); err != nil { - Log.WithError(err).Warn("Failed to close channel") - } - return fmt.Errorf("channel response failure: %s", err) - } - - go func() { - s.log.Debugln("listening for channel requests") - if err := channel.Serve(); err != nil { - Log.Error("channel failure:", err) - } - }() - - return nil -} - -// HandleRequest implements multiplexing logic for request messages. -func (s *Server) HandleRequest(remotePK cipher.PubKey, localID uint32, data []byte) error { - channel := s.chans.getChannel(localID) - if channel == nil { - return errors.New("channel is not opened") - } - - if s.auth.Authorize(remotePK) != nil || channel.RemoteAddr.PubKey != remotePK { - if err := channel.Send(CmdChannelResponse, responseUnauthorized); err != nil { - Log.Error("failed to send response: ", err) - } - return nil - } - - channel.msgCh <- data - return nil -} - -// HandleData implements multiplexing logic for data messages. -func (s *Server) HandleData(remotePK cipher.PubKey, localID uint32, data []byte) error { - channel := s.chans.getChannel(localID) - if channel == nil { - return errors.New("channel is not opened") - } - - if s.auth.Authorize(remotePK) != nil || channel.RemoteAddr.PubKey != remotePK { - return errors.New("unauthorized") - } - - if channel.session == nil { - return errors.New("session is not started") - } - - channel.dataChMx.Lock() - if !channel.IsClosed() { - channel.dataCh <- data - } - channel.dataChMx.Unlock() - return nil -} - -// Serve defines routing rules for received App messages. -func (s *Server) Serve(conn net.Conn) error { - for { - buf := make([]byte, 32*1024) - n, err := conn.Read(buf) - if err != nil { - if err == io.EOF { - return nil - } - - return err - } - - raddr := conn.RemoteAddr().(routing.Addr) - payload := buf[:n] - - if len(payload) < 5 { - return errors.New("corrupted payload") - } - - payloadID := binary.BigEndian.Uint32(payload[1:]) - data := payload[5:] - - s.log.Debugf("got new command: %x", payload[0]) - switch CommandType(payload[0]) { - case CmdChannelOpen: - err = s.OpenChannel(raddr, payloadID, conn) - case CmdChannelRequest: - err = s.HandleRequest(raddr.PubKey, payloadID, data) - case CmdChannelData: - err = s.HandleData(raddr.PubKey, payloadID, data) - default: - err = fmt.Errorf("unknown command: %x", payload[0]) - } - - if err != nil { - return err - } - } -} - -// Close closes all opened channels. -func (s *Server) Close() error { - if s == nil { - return nil - } - - for _, channel := range s.chans.dropAll() { - if err := channel.Close(); err != nil { - Log.WithError(err).Warn("Failed to close channel") - } - } - - return nil -} diff --git a/pkg/therealssh/server_test.go b/pkg/therealssh/server_test.go deleted file mode 100644 index 237ff4455..000000000 --- a/pkg/therealssh/server_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package therealssh - -import ( - "encoding/binary" - "net" - "os" - "testing" - - "github.com/SkycoinProject/dmsg/cipher" - "github.com/SkycoinProject/skycoin/src/util/logging" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/SkycoinProject/skywire-mainnet/pkg/routing" -) - -func TestMain(m *testing.M) { - loggingLevel, ok := os.LookupEnv("TEST_LOGGING_LEVEL") - if ok { - lvl, err := logging.LevelFromString(loggingLevel) - if err != nil { - Log.Fatal(err) - } - logging.SetLevel(lvl) - } else { - logging.Disable() - } - - os.Exit(m.Run()) -} - -func TestServerOpenChannel(t *testing.T) { - pk, _ := cipher.GenerateKeyPair() - s := NewServer(&ListAuthorizer{[]cipher.PubKey{pk}}, logging.NewMasterLogger()) - - in, out := net.Pipe() - errCh := make(chan error) - go func() { - errCh <- s.OpenChannel(routing.Addr{PubKey: cipher.PubKey{}, Port: Port}, 4, in) - }() - - buf := make([]byte, 18) - _, err := out.Read(buf) - require.NoError(t, err) - require.NoError(t, <-errCh) - assert.Equal(t, byte(CmdChannelOpenResponse), buf[0]) - assert.Equal(t, ResponseFail, buf[5]) - assert.Equal(t, []byte("unauthorized"), buf[6:]) - - go func() { - errCh <- s.OpenChannel(routing.Addr{PubKey: pk, Port: Port}, 4, in) - }() - - buf = make([]byte, 10) - _, err = out.Read(buf) - require.NoError(t, err) - require.NoError(t, <-errCh) - assert.Equal(t, byte(CmdChannelOpenResponse), buf[0]) - assert.Equal(t, ResponseConfirm, buf[5]) - assert.Equal(t, uint32(0), binary.BigEndian.Uint32(buf[6:])) -} - -func TestServerHandleRequest(t *testing.T) { - pk, _ := cipher.GenerateKeyPair() - s := NewServer(&ListAuthorizer{[]cipher.PubKey{pk}}, logging.NewMasterLogger()) - - err := s.HandleRequest(pk, 0, []byte("foo")) - require.Error(t, err) - assert.Equal(t, "channel is not opened", err.Error()) - - in, out := net.Pipe() - ch := OpenChannel(4, routing.Addr{PubKey: pk, Port: Port}, in) - s.chans.add(ch) - - errCh := make(chan error) - go func() { - errCh <- s.HandleRequest(cipher.PubKey{}, 0, []byte("foo")) - }() - - buf := make([]byte, 18) - _, err = out.Read(buf) - require.NoError(t, err) - require.NoError(t, <-errCh) - assert.Equal(t, byte(CmdChannelResponse), buf[0]) - assert.Equal(t, ResponseFail, buf[5]) - assert.Equal(t, []byte("unauthorized"), buf[6:]) - - dataCh := make(chan []byte) - go func() { - dataCh <- <-ch.msgCh - }() - - require.NoError(t, s.HandleRequest(pk, 0, []byte("foo"))) - assert.Equal(t, []byte("foo"), <-dataCh) -} - -func TestServerHandleData(t *testing.T) { - pk, _ := cipher.GenerateKeyPair() - s := NewServer(&ListAuthorizer{[]cipher.PubKey{pk}}, logging.NewMasterLogger()) - - err := s.HandleData(pk, 0, []byte("foo")) - require.Error(t, err) - assert.Equal(t, "channel is not opened", err.Error()) - - ch := OpenChannel(4, routing.Addr{PubKey: pk, Port: Port}, nil) - s.chans.add(ch) - - err = s.HandleData(cipher.PubKey{}, 0, []byte("foo")) - require.Error(t, err) - assert.Equal(t, "unauthorized", err.Error()) - - err = s.HandleData(pk, 0, []byte("foo")) - require.Error(t, err) - assert.Equal(t, "session is not started", err.Error()) - - ch.session = &Session{} - dataCh := make(chan []byte) - go func() { - dataCh <- <-ch.dataCh - }() - - require.NoError(t, s.HandleData(pk, 0, []byte("foo"))) - assert.Equal(t, []byte("foo"), <-dataCh) -} diff --git a/pkg/therealssh/session.go b/pkg/therealssh/session.go deleted file mode 100644 index 2691ef70d..000000000 --- a/pkg/therealssh/session.go +++ /dev/null @@ -1,200 +0,0 @@ -package therealssh - -import ( - "fmt" - "io/ioutil" - "os" - "os/exec" - "os/user" - "strconv" - "strings" - "sync" - "syscall" - - "github.com/SkycoinProject/skycoin/src/util/logging" - "github.com/creack/pty" -) - -// Log is the package level logger, which can be replaced from outside -var Log = logging.MustGetLogger("therealssh") - -// Session represents PTY sessions. Channel normally handles Session's lifecycle. -type Session struct { - ptyMu sync.Mutex - pty *os.File - ttyMu sync.Mutex - tty *os.File - - user *user.User - cmd *exec.Cmd -} - -// OpenSession constructs new PTY sessions. -func OpenSession(user *user.User, sz *pty.Winsize) (s *Session, err error) { - s = &Session{user: user} - s.pty, s.tty, err = pty.Open() - if err != nil { - err = fmt.Errorf("failed to open PTY: %s", err) - return - } - - if sz == nil { - return - } - - s.ptyMu.Lock() - defer s.ptyMu.Unlock() - - if err = pty.Setsize(s.pty, sz); err != nil { - if closeErr := s.Close(); closeErr != nil { - Log.WithError(closeErr).Warn("Failed to close session") - } - err = fmt.Errorf("failed to set PTY size: %s", err) - } - - return -} - -// Start executes command on Session's PTY. -func (s *Session) Start(command string) (err error) { - defer func() { - s.ttyMu.Lock() - defer s.ttyMu.Unlock() - - if err := s.tty.Close(); err != nil { - Log.WithError(err).Warn("Failed to close TTY") - } - }() - - if command == "shell" { - if command, err = resolveShell(s.user); err != nil { - return err - } - } - - components := strings.Split(command, " ") - cmd := exec.Command(components[0], components[1:]...) // nolint:gosec - cmd.Dir = s.user.HomeDir - - s.ttyMu.Lock() - cmd.Stdout = s.tty - cmd.Stdin = s.tty - cmd.Stderr = s.tty - s.ttyMu.Unlock() - - if cmd.SysProcAttr == nil { - cmd.SysProcAttr = &syscall.SysProcAttr{} - } - cmd.SysProcAttr.Setctty = true - cmd.SysProcAttr.Setsid = true - cmd.SysProcAttr.Credential = s.credentials() - - s.cmd = cmd - return cmd.Start() -} - -// Run executes a command and returns it's output and error if any -func (s *Session) Run(command string) ([]byte, error) { - var err error - - if command == "shell" { - if command, err = resolveShell(s.user); err != nil { - return nil, err - } - } - - components := strings.Split(command, " ") - - c := exec.Command(components[0], components[1:]...) // nolint:gosec - ptmx, err := pty.Start(c) - if err != nil { - return nil, err - } - - // Make sure to close the pty at the end. - defer func() { - err = ptmx.Close() - if err != nil { - Log.Warn("unable to close pty") - } - }() // Best effort. - - // as stated in https://github.com/creack/pty/issues/21#issuecomment-513069505 we can ignore this error - res, err := ioutil.ReadAll(ptmx) - _ = err - return res, nil -} - -// Wait for pty process to exit. -func (s *Session) Wait() error { - if s.cmd == nil { - return nil - } - - return s.cmd.Wait() -} - -// WindowChange resize PTY Session size. -func (s *Session) WindowChange(sz *pty.Winsize) error { - s.ptyMu.Lock() - defer s.ptyMu.Unlock() - - if err := pty.Setsize(s.pty, sz); err != nil { - return fmt.Errorf("failed to set PTY size: %s", err) - } - - return nil -} - -func (s *Session) credentials() *syscall.Credential { - if s.user == nil { - return nil - } - - u, err := user.Current() - if err != nil { - return nil - } - - if u.Uid == s.user.Uid { - return nil - } - - uid, err := strconv.Atoi(s.user.Uid) - if err != nil { - return nil - } - - gid, err := strconv.Atoi(s.user.Gid) - if err != nil { - return nil - } - - return &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)} -} - -func (s *Session) Write(p []byte) (int, error) { - s.ptyMu.Lock() - defer s.ptyMu.Unlock() - - return s.pty.Write(p) -} - -func (s *Session) Read(p []byte) (int, error) { - s.ptyMu.Lock() - defer s.ptyMu.Unlock() - - return s.pty.Read(p) -} - -// Close releases PTY resources. -func (s *Session) Close() error { - if s == nil { - return nil - } - - s.ptyMu.Lock() - defer s.ptyMu.Unlock() - - return s.pty.Close() -} diff --git a/pkg/therealssh/shell.go b/pkg/therealssh/shell.go deleted file mode 100644 index f3c967adb..000000000 --- a/pkg/therealssh/shell.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build dragonfly freebsd linux netbsd openbsd - -package therealssh - -import ( - "fmt" - "os/exec" - "os/user" - "strings" -) - -func resolveShell(u *user.User) (string, error) { - out, err := exec.Command("getent", "passwd", u.Uid).Output() // nolint:gosec - if err != nil { - return "", fmt.Errorf("getent failure: %s", err) - } - - ent := strings.Split(strings.TrimSuffix(string(out), "\n"), ":") - return ent[6], nil -} diff --git a/pkg/therealssh/shell_darwin.go b/pkg/therealssh/shell_darwin.go deleted file mode 100644 index 8115aa9b9..000000000 --- a/pkg/therealssh/shell_darwin.go +++ /dev/null @@ -1,25 +0,0 @@ -package therealssh - -import ( - "fmt" - "os/exec" - "os/user" - "regexp" -) - -func resolveShell(u *user.User) (string, error) { - dir := "Local/Default/Users/" + u.Username - out, err := exec.Command("dscl", "localhost", "-read", dir, "UserShell").Output() // nolint:gosec - if err != nil { - return "", err - } - - re := regexp.MustCompile("UserShell: (/[^ ]+)\n") - matched := re.FindStringSubmatch(string(out)) - shell := matched[1] - if shell == "" { - return "", fmt.Errorf("invalid output: %s", string(out)) - } - - return shell, nil -} diff --git a/pkg/visor/visor.go b/pkg/visor/visor.go index c316a5152..f34235886 100644 --- a/pkg/visor/visor.go +++ b/pkg/visor/visor.go @@ -56,7 +56,7 @@ const Version = "0.0.1" const supportedProtocolVersion = "0.0.1" -var reservedPorts = map[routing.Port]string{0: "router", 1: "skychat", 2: "SSH", 3: "skysocks"} +var reservedPorts = map[routing.Port]string{0: "router", 1: "skychat", 3: "skysocks"} // AppState defines state parameters for a registered App. type AppState struct { From 2ebc32fe0cd235b866983448974bd8b8c84edfaf Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Mon, 30 Dec 2019 21:17:04 +0400 Subject: [PATCH 20/33] Fix tests --- pkg/app/appserver/mock_proc_manager.go | 13 +++++++++---- pkg/visor/visor_test.go | 4 ++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/pkg/app/appserver/mock_proc_manager.go b/pkg/app/appserver/mock_proc_manager.go index b9d2420ae..a103ca716 100644 --- a/pkg/app/appserver/mock_proc_manager.go +++ b/pkg/app/appserver/mock_proc_manager.go @@ -2,10 +2,15 @@ package appserver -import appcommon "github.com/SkycoinProject/skywire-mainnet/pkg/app/appcommon" -import io "io" -import logging "github.com/SkycoinProject/skycoin/src/util/logging" -import mock "github.com/stretchr/testify/mock" +import ( + io "io" + + appcommon "github.com/SkycoinProject/skywire-mainnet/pkg/app/appcommon" + + logging "github.com/SkycoinProject/skycoin/src/util/logging" + + mock "github.com/stretchr/testify/mock" +) // MockProcManager is an autogenerated mock type for the ProcManager type type MockProcManager struct { diff --git a/pkg/visor/visor_test.go b/pkg/visor/visor_test.go index 9dc786aec..6313693a6 100644 --- a/pkg/visor/visor_test.go +++ b/pkg/visor/visor_test.go @@ -248,9 +248,9 @@ func TestNodeSpawnAppValidations(t *testing.T) { app := AppConfig{ App: "skychat", Version: "1.0", - Port: 2, + Port: 3, } - wantErr := "can't bind to reserved port 2" + wantErr := "can't bind to reserved port 3" pm := &appserver.MockProcManager{} appCfg := appcommon.Config{ From 007c4af354d87ff36e9a9c99115a77cad34c56f2 Mon Sep 17 00:00:00 2001 From: Nikita Kryuchkov Date: Thu, 2 Jan 2020 13:18:01 +0400 Subject: [PATCH 21/33] Fix restart test --- pkg/restart/restart_test.go | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/pkg/restart/restart_test.go b/pkg/restart/restart_test.go index bb9825349..c29defd5f 100644 --- a/pkg/restart/restart_test.go +++ b/pkg/restart/restart_test.go @@ -38,7 +38,7 @@ func TestContext_Start(t *testing.T) { t.Run("executable started", func(t *testing.T) { cmd := "touch" - path := "/tmp/test_restart" + path := "/tmp/test_start" cc.cmd = exec.Command(cmd, path) // nolint:gosec cc.appendDelay = false @@ -50,23 +50,32 @@ func TestContext_Start(t *testing.T) { cmd := "bad_command" cc.cmd = exec.Command(cmd) // nolint:gosec - // TODO(nkryuchkov): Check if it works on Linux and Windows, if not then change the error text. - assert.EqualError(t, cc.Start(), `exec: "bad_command": executable file not found in $PATH`) + // TODO(nkryuchkov): Add error text for Windows + possibleErrors := []string{ + `exec: "bad_command": executable file not found in $PATH`, + } + err := cc.Start() + require.NotNil(t, err) + assert.Contains(t, possibleErrors, err.Error()) }) - t.Run("already restarting", func(t *testing.T) { + t.Run("already starting", func(t *testing.T) { cmd := "touch" - path := "/tmp/test_restart" + path := "/tmp/test_start" cc.cmd = exec.Command(cmd, path) // nolint:gosec cc.appendDelay = false - ch := make(chan error, 1) + errCh := make(chan error, 1) go func() { - ch <- cc.Start() + errCh <- cc.Start() }() - assert.NoError(t, cc.Start()) - assert.Equal(t, ErrAlreadyStarting, <-ch) + err1 := cc.Start() + err2 := <-errCh + errors := []error{err1, err2} + + assert.Contains(t, errors, ErrAlreadyStarting) + assert.Contains(t, errors, nil) assert.NoError(t, os.Remove(path)) }) From 3f6e9d5a2cfa9138c02d998c07df4b7ff12a904d Mon Sep 17 00:00:00 2001 From: kifen Date: Mon, 6 Jan 2020 14:32:45 +0100 Subject: [PATCH 22/33] change app config from slice to map --- go.mod | 1 - pkg/visor/config.go | 6 +- pkg/visor/config_test.go | 4 +- pkg/visor/visor.go | 15 +- .../github.com/mitchellh/go-homedir/LICENSE | 21 --- .../github.com/mitchellh/go-homedir/README.md | 14 -- vendor/github.com/mitchellh/go-homedir/go.mod | 1 - .../mitchellh/go-homedir/homedir.go | 167 ------------------ vendor/modules.txt | 2 - 9 files changed, 13 insertions(+), 218 deletions(-) delete mode 100644 vendor/github.com/mitchellh/go-homedir/LICENSE delete mode 100644 vendor/github.com/mitchellh/go-homedir/README.md delete mode 100644 vendor/github.com/mitchellh/go-homedir/go.mod delete mode 100644 vendor/github.com/mitchellh/go-homedir/homedir.go diff --git a/go.mod b/go.mod index 3f7cf7d01..02baeb188 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,6 @@ require ( github.com/google/uuid v1.1.1 github.com/gorilla/handlers v1.4.2 github.com/gorilla/securecookie v1.1.1 - github.com/mitchellh/go-homedir v1.1.0 github.com/pkg/profile v1.3.0 github.com/prometheus/client_golang v1.2.1 github.com/prometheus/common v0.7.0 diff --git a/pkg/visor/config.go b/pkg/visor/config.go index c4c1bbbb3..554c6e322 100644 --- a/pkg/visor/config.go +++ b/pkg/visor/config.go @@ -134,13 +134,13 @@ func (c *Config) RoutingTable() (routing.Table, error) { } // AppsConfig decodes AppsConfig from a local json config file. -func (c *Config) AppsConfig() ([]AppConfig, error) { - apps := make([]AppConfig, 0) +func (c *Config) AppsConfig() (map[string]AppConfig, error) { + apps := make(map[string]AppConfig) for _, app := range c.Apps { if app.Version == "" { app.Version = c.Version } - apps = append(apps, app) + apps[app.App] = app } return apps, nil diff --git a/pkg/visor/config_test.go b/pkg/visor/config_test.go index 3852a16e9..e0363a8e8 100644 --- a/pkg/visor/config_test.go +++ b/pkg/visor/config_test.go @@ -94,13 +94,13 @@ func TestAppsConfig(t *testing.T) { appsConf, err := conf.AppsConfig() require.NoError(t, err) - app1 := appsConf[0] + app1 := appsConf["foo"] assert.Equal(t, "foo", app1.App) assert.Equal(t, "1.1", app1.Version) assert.Equal(t, routing.Port(1), app1.Port) assert.False(t, app1.AutoStart) - app2 := appsConf[1] + app2 := appsConf["bar"] assert.Equal(t, "bar", app2.App) assert.Equal(t, "1.0", app2.Version) assert.Equal(t, routing.Port(2), app2.Port) diff --git a/pkg/visor/visor.go b/pkg/visor/visor.go index f34235886..114c26c92 100644 --- a/pkg/visor/visor.go +++ b/pkg/visor/visor.go @@ -81,7 +81,7 @@ type Node struct { appsPath string localPath string - appsConf []AppConfig + appsConf map[string]AppConfig startedAt time.Time restartCtx *restart.Context @@ -487,11 +487,12 @@ func (node *Node) StopApp(appName string) error { // SetAutoStart sets an app to auto start or not. func (node *Node) SetAutoStart(appName string, autoStart bool) error { - for i, ac := range node.appsConf { - if ac.App == appName { - node.appsConf[i].AutoStart = autoStart - return nil - } + appConf, ok := node.appsConf[appName] + if !ok { + return ErrUnknownApp } - return ErrUnknownApp + + appConf.AutoStart = autoStart + node.appsConf[appName] = appConf + return nil } diff --git a/vendor/github.com/mitchellh/go-homedir/LICENSE b/vendor/github.com/mitchellh/go-homedir/LICENSE deleted file mode 100644 index f9c841a51..000000000 --- a/vendor/github.com/mitchellh/go-homedir/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Mitchell Hashimoto - -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/vendor/github.com/mitchellh/go-homedir/README.md b/vendor/github.com/mitchellh/go-homedir/README.md deleted file mode 100644 index d70706d5b..000000000 --- a/vendor/github.com/mitchellh/go-homedir/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# go-homedir - -This is a Go library for detecting the user's home directory without -the use of cgo, so the library can be used in cross-compilation environments. - -Usage is incredibly simple, just call `homedir.Dir()` to get the home directory -for a user, and `homedir.Expand()` to expand the `~` in a path to the home -directory. - -**Why not just use `os/user`?** The built-in `os/user` package requires -cgo on Darwin systems. This means that any Go code that uses that package -cannot cross compile. But 99% of the time the use for `os/user` is just to -retrieve the home directory, which we can do for the current user without -cgo. This library does that, enabling cross-compilation. diff --git a/vendor/github.com/mitchellh/go-homedir/go.mod b/vendor/github.com/mitchellh/go-homedir/go.mod deleted file mode 100644 index 7efa09a04..000000000 --- a/vendor/github.com/mitchellh/go-homedir/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/mitchellh/go-homedir diff --git a/vendor/github.com/mitchellh/go-homedir/homedir.go b/vendor/github.com/mitchellh/go-homedir/homedir.go deleted file mode 100644 index 25378537e..000000000 --- a/vendor/github.com/mitchellh/go-homedir/homedir.go +++ /dev/null @@ -1,167 +0,0 @@ -package homedir - -import ( - "bytes" - "errors" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" -) - -// DisableCache will disable caching of the home directory. Caching is enabled -// by default. -var DisableCache bool - -var homedirCache string -var cacheLock sync.RWMutex - -// Dir returns the home directory for the executing user. -// -// This uses an OS-specific method for discovering the home directory. -// An error is returned if a home directory cannot be detected. -func Dir() (string, error) { - if !DisableCache { - cacheLock.RLock() - cached := homedirCache - cacheLock.RUnlock() - if cached != "" { - return cached, nil - } - } - - cacheLock.Lock() - defer cacheLock.Unlock() - - var result string - var err error - if runtime.GOOS == "windows" { - result, err = dirWindows() - } else { - // Unix-like system, so just assume Unix - result, err = dirUnix() - } - - if err != nil { - return "", err - } - homedirCache = result - return result, nil -} - -// Expand expands the path to include the home directory if the path -// is prefixed with `~`. If it isn't prefixed with `~`, the path is -// returned as-is. -func Expand(path string) (string, error) { - if len(path) == 0 { - return path, nil - } - - if path[0] != '~' { - return path, nil - } - - if len(path) > 1 && path[1] != '/' && path[1] != '\\' { - return "", errors.New("cannot expand user-specific home dir") - } - - dir, err := Dir() - if err != nil { - return "", err - } - - return filepath.Join(dir, path[1:]), nil -} - -// Reset clears the cache, forcing the next call to Dir to re-detect -// the home directory. This generally never has to be called, but can be -// useful in tests if you're modifying the home directory via the HOME -// env var or something. -func Reset() { - cacheLock.Lock() - defer cacheLock.Unlock() - homedirCache = "" -} - -func dirUnix() (string, error) { - homeEnv := "HOME" - if runtime.GOOS == "plan9" { - // On plan9, env vars are lowercase. - homeEnv = "home" - } - - // First prefer the HOME environmental variable - if home := os.Getenv(homeEnv); home != "" { - return home, nil - } - - var stdout bytes.Buffer - - // If that fails, try OS specific commands - if runtime.GOOS == "darwin" { - cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`) - cmd.Stdout = &stdout - if err := cmd.Run(); err == nil { - result := strings.TrimSpace(stdout.String()) - if result != "" { - return result, nil - } - } - } else { - cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - // If the error is ErrNotFound, we ignore it. Otherwise, return it. - if err != exec.ErrNotFound { - return "", err - } - } else { - if passwd := strings.TrimSpace(stdout.String()); passwd != "" { - // username:password:uid:gid:gecos:home:shell - passwdParts := strings.SplitN(passwd, ":", 7) - if len(passwdParts) > 5 { - return passwdParts[5], nil - } - } - } - } - - // If all else fails, try the shell - stdout.Reset() - cmd := exec.Command("sh", "-c", "cd && pwd") - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - return "", err - } - - result := strings.TrimSpace(stdout.String()) - if result == "" { - return "", errors.New("blank output when reading home directory") - } - - return result, nil -} - -func dirWindows() (string, error) { - // First prefer the HOME environmental variable - if home := os.Getenv("HOME"); home != "" { - return home, nil - } - - // Prefer standard environment variable USERPROFILE - if home := os.Getenv("USERPROFILE"); home != "" { - return home, nil - } - - drive := os.Getenv("HOMEDRIVE") - path := os.Getenv("HOMEPATH") - home := drive + path - if drive == "" || path == "" { - return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") - } - - return home, nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 596630099..88fab3997 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -50,8 +50,6 @@ github.com/mattn/go-isatty github.com/matttproud/golang_protobuf_extensions/pbutil # github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b github.com/mgutz/ansi -# github.com/mitchellh/go-homedir v1.1.0 -github.com/mitchellh/go-homedir # github.com/pkg/profile v1.3.0 github.com/pkg/profile # github.com/pmezard/go-difflib v1.0.0 From 8809d7acba4a31db3fa291142b4c2d645ebf297b Mon Sep 17 00:00:00 2001 From: kifen Date: Mon, 6 Jan 2020 15:43:11 +0100 Subject: [PATCH 23/33] update config_test, visor_test, rpc_test --- pkg/visor/rpc_test.go | 24 ++++++++++++++++-------- pkg/visor/visor_test.go | 22 +++++++++++++++------- 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/pkg/visor/rpc_test.go b/pkg/visor/rpc_test.go index f30b6c64e..e3f7ef426 100644 --- a/pkg/visor/rpc_test.go +++ b/pkg/visor/rpc_test.go @@ -68,7 +68,8 @@ func TestUptime(t *testing.T) { // TODO (Darkren): fix tests func TestListApps(t *testing.T) { - apps := []AppConfig{ + apps := make(map[string]AppConfig) + appCfg := []AppConfig{ { App: "foo", AutoStart: false, @@ -81,9 +82,13 @@ func TestListApps(t *testing.T) { }, } + for _, app := range appCfg { + apps[app.App] = app + } + pm := &appserver.MockProcManager{} - pm.On("Exists", apps[0].App).Return(false) - pm.On("Exists", apps[1].App).Return(true) + pm.On("Exists", apps["foo"].App).Return(false) + pm.On("Exists", apps["bar"].App).Return(true) n := Node{ appsConf: apps, @@ -119,7 +124,7 @@ func TestStartStopApp(t *testing.T) { require.NoError(t, os.RemoveAll("skychat")) }() - apps := []AppConfig{ + appCfg := []AppConfig{ { App: "foo", Version: "1.0", @@ -127,9 +132,12 @@ func TestStartStopApp(t *testing.T) { Port: 10, }, } + apps := map[string]AppConfig{ + "foo": appCfg[0], + } unknownApp := "bar" - app := apps[0].App + app := apps["foo"].App nodeCfg := Config{} nodeCfg.Node.StaticPubKey = pk @@ -148,12 +156,12 @@ func TestStartStopApp(t *testing.T) { pm := &appserver.MockProcManager{} appCfg1 := appcommon.Config{ Name: app, - Version: apps[0].Version, + Version: apps["foo"].Version, SockFilePath: nodeCfg.AppServerSockFile, VisorPK: nodeCfg.Node.StaticPubKey.Hex(), - WorkDir: filepath.Join("", app, fmt.Sprintf("v%s", apps[0].Version)), + WorkDir: filepath.Join("", app, fmt.Sprintf("v%s", apps["foo"].Version)), } - appArgs1 := append([]string{filepath.Join(node.dir(), app)}, apps[0].Args...) + appArgs1 := append([]string{filepath.Join(node.dir(), app)}, apps["foo"].Args...) appPID1 := appcommon.ProcID(10) pm.On("Run", mock.Anything, appCfg1, appArgs1, mock.Anything, mock.Anything). Return(appPID1, testhelpers.NoErr) diff --git a/pkg/visor/visor_test.go b/pkg/visor/visor_test.go index 6313693a6..8b658d539 100644 --- a/pkg/visor/visor_test.go +++ b/pkg/visor/visor_test.go @@ -88,7 +88,8 @@ func TestNodeStartClose(t *testing.T) { r.On("Serve", mock.Anything /* context */).Return(testhelpers.NoErr) r.On("Close").Return(testhelpers.NoErr) - apps := []AppConfig{ + apps := make(map[string]AppConfig) + appCfg := []AppConfig{ { App: "skychat", Version: "1.0", @@ -102,6 +103,10 @@ func TestNodeStartClose(t *testing.T) { }, } + for _, app := range appCfg { + apps[app.App] = app + } + defer func() { require.NoError(t, os.RemoveAll("skychat")) }() @@ -117,17 +122,17 @@ func TestNodeStartClose(t *testing.T) { pm := &appserver.MockProcManager{} appCfg1 := appcommon.Config{ - Name: apps[0].App, - Version: apps[0].Version, + Name: apps["skychat"].App, + Version: apps["skychat"].Version, SockFilePath: nodeCfg.AppServerSockFile, VisorPK: nodeCfg.Node.StaticPubKey.Hex(), - WorkDir: filepath.Join("", apps[0].App, fmt.Sprintf("v%s", apps[0].Version)), + WorkDir: filepath.Join("", apps["skychat"].App, fmt.Sprintf("v%s", apps["skychat"].Version)), } - appArgs1 := append([]string{filepath.Join(node.dir(), apps[0].App)}, apps[0].Args...) + appArgs1 := append([]string{filepath.Join(node.dir(), apps["skychat"].App)}, apps["skychat"].Args...) appPID1 := appcommon.ProcID(10) pm.On("Run", mock.Anything, appCfg1, appArgs1, mock.Anything, mock.Anything). Return(appPID1, testhelpers.NoErr) - pm.On("Wait", apps[0].App).Return(testhelpers.NoErr) + pm.On("Wait", apps["skychat"].App).Return(testhelpers.NoErr) pm.On("StopAll").Return() @@ -180,12 +185,15 @@ func TestNodeSpawnApp(t *testing.T) { Args: []string{"foo"}, } + apps := make(map[string]AppConfig) + apps["skychat"] = app + nodeCfg := Config{} nodeCfg.Node.StaticPubKey = pk node := &Node{ router: r, - appsConf: []AppConfig{app}, + appsConf: apps, logger: logging.MustGetLogger("test"), conf: &nodeCfg, } From 709d678f072440f21ccc4c927f9a6a675618c64b Mon Sep 17 00:00:00 2001 From: kifen Date: Fri, 3 Jan 2020 07:44:58 +0100 Subject: [PATCH 24/33] rename therealproxy to skysocks --- Makefile | 12 +- README.md | 7 +- ci_scripts/run-internal-tests.sh | 2 +- .../README.md | 0 .../skysocks-client.go} | 6 +- cmd/apps/{therealproxy => skysocks}/README.md | 4 +- .../therealproxy.go => skysocks/skysocks.go} | 6 +- docker/images/node/Dockerfile | 6 +- go.mod | 2 + go.sum | 1 + internal/{therealproxy => skysocks}/client.go | 12 +- internal/{therealproxy => skysocks}/server.go | 7 +- .../{therealproxy => skysocks}/server_test.go | 9 +- vendor/github.com/hashicorp/yamux/.gitignore | 23 + vendor/github.com/hashicorp/yamux/LICENSE | 362 ++++++++++ vendor/github.com/hashicorp/yamux/README.md | 86 +++ vendor/github.com/hashicorp/yamux/addr.go | 60 ++ vendor/github.com/hashicorp/yamux/const.go | 157 +++++ vendor/github.com/hashicorp/yamux/go.mod | 1 + vendor/github.com/hashicorp/yamux/mux.go | 98 +++ vendor/github.com/hashicorp/yamux/session.go | 653 ++++++++++++++++++ vendor/github.com/hashicorp/yamux/spec.md | 140 ++++ vendor/github.com/hashicorp/yamux/stream.go | 470 +++++++++++++ vendor/github.com/hashicorp/yamux/util.go | 43 ++ vendor/modules.txt | 2 + 25 files changed, 2138 insertions(+), 31 deletions(-) rename cmd/apps/{therealproxy-client => skysocks-client}/README.md (100%) rename cmd/apps/{therealproxy-client/therealproxy-client.go => skysocks-client/skysocks-client.go} (91%) rename cmd/apps/{therealproxy => skysocks}/README.md (89%) rename cmd/apps/{therealproxy/therealproxy.go => skysocks/skysocks.go} (86%) rename internal/{therealproxy => skysocks}/client.go (85%) rename internal/{therealproxy => skysocks}/server.go (92%) rename internal/{therealproxy => skysocks}/server_test.go (92%) create mode 100644 vendor/github.com/hashicorp/yamux/.gitignore create mode 100644 vendor/github.com/hashicorp/yamux/LICENSE create mode 100644 vendor/github.com/hashicorp/yamux/README.md create mode 100644 vendor/github.com/hashicorp/yamux/addr.go create mode 100644 vendor/github.com/hashicorp/yamux/const.go create mode 100644 vendor/github.com/hashicorp/yamux/go.mod create mode 100644 vendor/github.com/hashicorp/yamux/mux.go create mode 100644 vendor/github.com/hashicorp/yamux/session.go create mode 100644 vendor/github.com/hashicorp/yamux/spec.md create mode 100644 vendor/github.com/hashicorp/yamux/stream.go create mode 100644 vendor/github.com/hashicorp/yamux/util.go diff --git a/Makefile b/Makefile index f82df6aef..101e43a73 100644 --- a/Makefile +++ b/Makefile @@ -86,8 +86,8 @@ dep: ## Sorts dependencies host-apps: ## Build app ${OPTS} go build ${BUILD_OPTS} -o ./apps/skychat.v1.0 ./cmd/apps/skychat ${OPTS} go build ${BUILD_OPTS} -o ./apps/helloworld.v1.0 ./cmd/apps/helloworld - ${OPTS} go build ${BUILD_OPTS} -o ./apps/socksproxy.v1.0 ./cmd/apps/therealproxy - ${OPTS} go build ${BUILD_OPTS} -o ./apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-client + ${OPTS} go build ${BUILD_OPTS} -o ./apps/socksproxy.v1.0 ./cmd/apps/skysocks + ${OPTS} go build ${BUILD_OPTS} -o ./apps/socksproxy-client.v1.0 ./cmd/apps/skysocks-client # Bin bin: ## Build `skywire-visor`, `skywire-cli`, `hypervisor` @@ -105,8 +105,8 @@ release: ## Build `skywire-visor`, `skywire-cli`, `hypervisor` and apps without ${OPTS} go build -o ./hypervisor ./cmd/hypervisor ${OPTS} go build -o ./apps/skychat.v1.0 ./cmd/apps/skychat ${OPTS} go build -o ./apps/helloworld.v1.0 ./cmd/apps/helloworld - ${OPTS} go build -o ./apps/socksproxy.v1.0 ./cmd/apps/therealproxy - ${OPTS} go build -o ./apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-client + ${OPTS} go build -o ./apps/socksproxy.v1.0 ./cmd/apps/skysocks + ${OPTS} go build -o ./apps/socksproxy-client.v1.0 ./cmd/apps/skysocks-client # Dockerized skywire-visor docker-image: ## Build docker image `skywire-runner` @@ -122,8 +122,8 @@ docker-network: ## Create docker network ${DOCKER_NETWORK} docker-apps: ## Build apps binaries for dockerized skywire-visor. `go build` with ${DOCKER_OPTS} -${DOCKER_OPTS} go build -race -o ./node/apps/skychat.v1.0 ./cmd/apps/skychat -${DOCKER_OPTS} go build -race -o ./node/apps/helloworld.v1.0 ./cmd/apps/helloworld - -${DOCKER_OPTS} go build -race -o ./node/apps/socksproxy.v1.0 ./cmd/apps/therealproxy - -${DOCKER_OPTS} go build -race -o ./node/apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-client + -${DOCKER_OPTS} go build -race -o ./node/apps/socksproxy.v1.0 ./cmd/apps/skysocks + -${DOCKER_OPTS} go build -race -o ./node/apps/socksproxy-client.v1.0 ./cmd/apps/skysocks-client docker-bin: ## Build `skywire-visor`, `skywire-cli`, `hypervisor`. `go build` with ${DOCKER_OPTS} ${DOCKER_OPTS} go build -race -o ./node/skywire-visor ./cmd/skywire-visor diff --git a/README.md b/README.md index 30e67ff05..ede575c60 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,12 @@ After `skywire-visor` is up and running with default environment, default apps a - [Chat](/cmd/apps/skychat) - [Hello World](/cmd/apps/helloworld) +<<<<<<< HEAD - [The Real Proxy](/cmd/apps/therealproxy) ([Client](/cmd/apps/therealproxy-client)) +======= +- [The Real Proxy](/cmd/apps/skysocks) ([Client](/cmd/apps/skysocks-client)) +- [The Real SSH](/cmd/apps/therealssh) ([Client](/cmd/apps/therealssh-client)) +>>>>>>> rename therealproxy to skysocks ### Transports @@ -408,7 +413,7 @@ $ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/skywire-visor ./cmd/skywire # 3. compile apps $ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/skychat.v1.0 ./cmd/apps/skychat $ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/helloworld.v1.0 ./cmd/apps/helloworld -$ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/socksproxy.v1.0 ./cmd/apps/therealproxy +$ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/socksproxy.v1.0 ./cmd/apps/skysocks # 4. Create skywire-config.json for node $ skywire-cli node gen-config -o /tmp/SKYNODE/skywire-config.json # 2019/03/15 16:43:49 Done! diff --git a/ci_scripts/run-internal-tests.sh b/ci_scripts/run-internal-tests.sh index f16b93346..dff03bdae 100755 --- a/ci_scripts/run-internal-tests.sh +++ b/ci_scripts/run-internal-tests.sh @@ -17,4 +17,4 @@ go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/noise -run TestReadWriterXKPattern >> ./logs/internal/TestReadWriterXKPattern.log go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/noise -run TestReadWriterConcurrentTCP >> ./logs/internal/TestReadWriterConcurrentTCP.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/therealproxy -run TestProxy >> ./logs/internal/TestProxy.log +go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/skysocks -run TestProxy >> ./logs/internal/TestProxy.log \ No newline at end of file diff --git a/cmd/apps/therealproxy-client/README.md b/cmd/apps/skysocks-client/README.md similarity index 100% rename from cmd/apps/therealproxy-client/README.md rename to cmd/apps/skysocks-client/README.md diff --git a/cmd/apps/therealproxy-client/therealproxy-client.go b/cmd/apps/skysocks-client/skysocks-client.go similarity index 91% rename from cmd/apps/therealproxy-client/therealproxy-client.go rename to cmd/apps/skysocks-client/skysocks-client.go index bd38b49cc..0561c98f6 100644 --- a/cmd/apps/therealproxy-client/therealproxy-client.go +++ b/cmd/apps/skysocks-client/skysocks-client.go @@ -14,7 +14,7 @@ import ( "github.com/SkycoinProject/skywire-mainnet/internal/netutil" "github.com/SkycoinProject/skywire-mainnet/internal/skyenv" - "github.com/SkycoinProject/skywire-mainnet/internal/therealproxy" + "github.com/SkycoinProject/skywire-mainnet/internal/skysocks" "github.com/SkycoinProject/skywire-mainnet/pkg/app" "github.com/SkycoinProject/skywire-mainnet/pkg/app/appnet" "github.com/SkycoinProject/skywire-mainnet/pkg/routing" @@ -30,7 +30,7 @@ var r = netutil.NewRetrier(time.Second, 0, 1) func main() { log := app.NewLogger(appName) - therealproxy.Log = log.PackageLogger("therealproxy") + skysocks.Log = log.PackageLogger("skysocks") var addr = flag.String("addr", skyenv.SkyproxyClientAddr, "Client address to listen on") var serverPK = flag.String("srv", "", "PubKey of the server to connect to") @@ -74,7 +74,7 @@ func main() { log.Printf("Connected to %v\n", pk) - client, err := therealproxy.NewClient(conn) + client, err := skysocks.NewClient(conn) if err != nil { log.Fatal("Failed to create a new client: ", err) } diff --git a/cmd/apps/therealproxy/README.md b/cmd/apps/skysocks/README.md similarity index 89% rename from cmd/apps/therealproxy/README.md rename to cmd/apps/skysocks/README.md index 360b4e187..3e07a56b4 100644 --- a/cmd/apps/therealproxy/README.md +++ b/cmd/apps/skysocks/README.md @@ -47,8 +47,8 @@ Create 2 node config files: Compile binaries and start 2 nodes: ```sh -$ go build -o apps/socksproxy.v1.0 ./cmd/apps/therealproxy -$ go build -o apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-client +$ go build -o apps/socksproxy.v1.0 ./cmd/apps/skysocks +$ go build -o apps/socksproxy-client.v1.0 ./cmd/apps/skysocks-client $ ./skywire-visor skywire1.json $ ./skywire-visor skywire2.json ``` diff --git a/cmd/apps/therealproxy/therealproxy.go b/cmd/apps/skysocks/skysocks.go similarity index 86% rename from cmd/apps/therealproxy/therealproxy.go rename to cmd/apps/skysocks/skysocks.go index 3ab67e093..305c0d089 100644 --- a/cmd/apps/therealproxy/therealproxy.go +++ b/cmd/apps/skysocks/skysocks.go @@ -9,7 +9,7 @@ import ( "github.com/SkycoinProject/skycoin/src/util/logging" - "github.com/SkycoinProject/skywire-mainnet/internal/therealproxy" + "github.com/SkycoinProject/skywire-mainnet/internal/skysocks" "github.com/SkycoinProject/skywire-mainnet/pkg/app" "github.com/SkycoinProject/skywire-mainnet/pkg/app/appnet" "github.com/SkycoinProject/skywire-mainnet/pkg/routing" @@ -23,7 +23,7 @@ const ( func main() { log := app.NewLogger(appName) - therealproxy.Log = log.PackageLogger("therealproxy") + skysocks.Log = log.PackageLogger("skysocks") var passcode = flag.String("passcode", "", "Authorize user against this passcode") flag.Parse() @@ -41,7 +41,7 @@ func main() { socksApp.Close() }() - srv, err := therealproxy.NewServer(*passcode, log) + srv, err := skysocks.NewServer(*passcode, log) if err != nil { log.Fatal("Failed to create a new server: ", err) } diff --git a/docker/images/node/Dockerfile b/docker/images/node/Dockerfile index 4b779dfc1..0886aa548 100644 --- a/docker/images/node/Dockerfile +++ b/docker/images/node/Dockerfile @@ -18,9 +18,9 @@ RUN go build -mod=vendor -tags netgo -ldflags="-w -s" \ go build -mod=vendor -ldflags="-w -s" -o skywire-cli ./cmd/skywire-cli &&\ go build -mod=vendor -ldflags="-w -s" -o ./apps/skychat.v1.0 ./cmd/apps/skychat &&\ go build -mod=vendor -ldflags="-w -s" -o ./apps/helloworld.v1.0 ./cmd/apps/helloworld &&\ - go build -mod=vendor -ldflags="-w -s" -o ./apps/socksproxy.v1.0 ./cmd/apps/therealproxy &&\ - go build -mod=vendor -ldflags="-w -s" -o ./apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-client - + go build -mod=vendor -ldflags="-w -s" -o ./apps/socksproxy.v1.0 ./cmd/apps/skysocks &&\ + go build -mod=vendor -ldflags="-w -s" -o ./apps/socksproxy-client.v1.0 ./cmd/apps/skysocks-client &&\ + ## Resulting image FROM ${base} as node-runner diff --git a/go.mod b/go.mod index 02baeb188..edcc2796b 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,8 @@ require ( github.com/google/uuid v1.1.1 github.com/gorilla/handlers v1.4.2 github.com/gorilla/securecookie v1.1.1 + github.com/hashicorp/yamux v0.0.0-20190923154419-df201c70410d + github.com/mitchellh/go-homedir v1.1.0 github.com/pkg/profile v1.3.0 github.com/prometheus/client_golang v1.2.1 github.com/prometheus/common v0.7.0 diff --git a/go.sum b/go.sum index fda3ae904..c3cf11d7b 100644 --- a/go.sum +++ b/go.sum @@ -56,6 +56,7 @@ github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/ github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/yamux v0.0.0-20190923154419-df201c70410d h1:W+SIwDdl3+jXWeidYySAgzytE3piq6GumXeBjFBG67c= github.com/hashicorp/yamux v0.0.0-20190923154419-df201c70410d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= diff --git a/internal/therealproxy/client.go b/internal/skysocks/client.go similarity index 85% rename from internal/therealproxy/client.go rename to internal/skysocks/client.go index 54ff52c7e..9080edfad 100644 --- a/internal/therealproxy/client.go +++ b/internal/skysocks/client.go @@ -1,4 +1,4 @@ -package therealproxy +package skysocks import ( "fmt" @@ -9,8 +9,8 @@ import ( "github.com/SkycoinProject/yamux" ) -// Log is therealproxy package level logger, it can be replaced with a different one from outside the package -var Log = logging.MustGetLogger("therealproxy") +// Log is skysocks package level logger, it can be replaced with a different one from outside the package +var Log = logging.MustGetLogger("skysocks") // Client implement multiplexing proxy client using yamux. type Client struct { @@ -38,7 +38,7 @@ func (c *Client) ListenAndServe(addr string) error { return fmt.Errorf("listen: %s", err) } - Log.Printf("Listening therealproxy client on %s", addr) + Log.Printf("Listening skysocks client on %s", addr) c.listener = l for { @@ -48,13 +48,13 @@ func (c *Client) ListenAndServe(addr string) error { return fmt.Errorf("accept: %s", err) } - Log.Println("Accepted therealproxy client") + Log.Println("Accepted skysocks client") stream, err := c.session.Open() if err != nil { return fmt.Errorf("error on `ListenAndServe`: yamux: %s", err) } - Log.Println("Opened session therealproxy client") + Log.Println("Opened session skysocks client") go func() { errCh := make(chan error, 2) diff --git a/internal/therealproxy/server.go b/internal/skysocks/server.go similarity index 92% rename from internal/therealproxy/server.go rename to internal/skysocks/server.go index b4e999935..dbaae664f 100644 --- a/internal/therealproxy/server.go +++ b/internal/skysocks/server.go @@ -1,13 +1,12 @@ -package therealproxy +package skysocks import ( "fmt" "net" - "github.com/SkycoinProject/yamux" - "github.com/SkycoinProject/skycoin/src/util/logging" "github.com/armon/go-socks5" + "github.com/hashicorp/yamux" ) // Server implements multiplexing proxy server using yamux. @@ -44,7 +43,7 @@ func (s *Server) Serve(l net.Listener) error { session, err := yamux.Server(conn, nil) if err != nil { - return fmt.Errorf("error in `Serve`: yamux: %s", err) + return fmt.Errorf("yamux server failure: %s", err) } go func() { diff --git a/internal/therealproxy/server_test.go b/internal/skysocks/server_test.go similarity index 92% rename from internal/therealproxy/server_test.go rename to internal/skysocks/server_test.go index 9ba3dc114..123ed6f10 100644 --- a/internal/therealproxy/server_test.go +++ b/internal/skysocks/server_test.go @@ -1,4 +1,4 @@ -package therealproxy +package skysocks import ( "fmt" @@ -11,6 +11,7 @@ import ( "time" "github.com/SkycoinProject/skycoin/src/util/logging" + "github.com/hashicorp/yamux" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/net/nettest" @@ -49,9 +50,13 @@ func TestProxy(t *testing.T) { conn, err := net.Dial("tcp", l.Addr().String()) require.NoError(t, err) - client, err := NewClient(conn) + session, err := yamux.Client(conn, nil) require.NoError(t, err) + client := &Client{ + session: session, + } + errChan2 := make(chan error) go func() { errChan2 <- client.ListenAndServe(":10080") diff --git a/vendor/github.com/hashicorp/yamux/.gitignore b/vendor/github.com/hashicorp/yamux/.gitignore new file mode 100644 index 000000000..836562412 --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/.gitignore @@ -0,0 +1,23 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test diff --git a/vendor/github.com/hashicorp/yamux/LICENSE b/vendor/github.com/hashicorp/yamux/LICENSE new file mode 100644 index 000000000..f0e5c79e1 --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/LICENSE @@ -0,0 +1,362 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. "Contributor" + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. "Contributor Version" + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the terms of + a Secondary License. + +1.6. "Executable Form" + + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + + means a work that combines Covered Software with other material, in a + separate file or files, that is not Covered Software. + +1.8. "License" + + means this document. + +1.9. "Licensable" + + means having the right to grant, to the maximum extent possible, whether + at the time of the initial grant or subsequently, any and all of the + rights conveyed by this License. + +1.10. "Modifications" + + means any of the following: + + a. any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. "Patent Claims" of a Contributor + + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the License, + by the making, using, selling, offering for sale, having made, import, + or transfer of either its Contributions or its Contributor Version. + +1.12. "Secondary License" + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. "Source Code Form" + + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, "control" means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution + become effective for each Contribution on the date the Contributor first + distributes such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under + this License. No additional rights or licenses will be implied from the + distribution or licensing of Covered Software under this License. + Notwithstanding Section 2.1(b) above, no patent license is granted by a + Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of + its Contributions. + + This License does not grant any rights in the trademarks, service marks, + or logos of any Contributor (except as may be necessary to comply with + the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this + License (see Section 10.2) or under the terms of a Secondary License (if + permitted under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its + Contributions are its original creation(s) or it has sufficient rights to + grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under + applicable copyright doctrines of fair use, fair dealing, or other + equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under + the terms of this License. You must inform recipients that the Source + Code Form of the Covered Software is governed by the terms of this + License, and how they can obtain a copy of this License. You may not + attempt to alter or restrict the recipients' rights in the Source Code + Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter the + recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for + the Covered Software. If the Larger Work is a combination of Covered + Software with a work governed by one or more Secondary Licenses, and the + Covered Software is not Incompatible With Secondary Licenses, this + License permits You to additionally distribute such Covered Software + under the terms of such Secondary License(s), so that the recipient of + the Larger Work may, at their option, further distribute the Covered + Software under the terms of either this License or such Secondary + License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices + (including copyright notices, patent notices, disclaimers of warranty, or + limitations of liability) contained within the Source Code Form of the + Covered Software, except that You may alter any license notices to the + extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on + behalf of any Contributor. You must make it absolutely clear that any + such warranty, support, indemnity, or liability obligation is offered by + You alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, + judicial order, or regulation then You must: (a) comply with the terms of + this License to the maximum extent possible; and (b) describe the + limitations and the code they affect. Such description must be placed in a + text file included with all distributions of the Covered Software under + this License. Except to the extent prohibited by statute or regulation, + such description must be sufficiently detailed for a recipient of ordinary + skill to be able to understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing + basis, if such Contributor fails to notify You of the non-compliance by + some reasonable means prior to 60 days after You have come back into + compliance. Moreover, Your grants from a particular Contributor are + reinstated on an ongoing basis if such Contributor notifies You of the + non-compliance by some reasonable means, this is the first time You have + received notice of non-compliance with this License from such + Contributor, and You become compliant prior to 30 days after Your receipt + of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, + counter-claims, and cross-claims) alleging that a Contributor Version + directly or indirectly infringes any patent, then the rights granted to + You by any and all Contributors for the Covered Software under Section + 2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an "as is" basis, + without warranty of any kind, either expressed, implied, or statutory, + including, without limitation, warranties that the Covered Software is free + of defects, merchantable, fit for a particular purpose or non-infringing. + The entire risk as to the quality and performance of the Covered Software + is with You. Should any Covered Software prove defective in any respect, + You (not any Contributor) assume the cost of any necessary servicing, + repair, or correction. This disclaimer of warranty constitutes an essential + part of this License. No use of any Covered Software is authorized under + this License except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from + such party's negligence to the extent applicable law prohibits such + limitation. Some jurisdictions do not allow the exclusion or limitation of + incidental or consequential damages, so this exclusion and limitation may + not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts + of a jurisdiction where the defendant maintains its principal place of + business and such litigation shall be governed by laws of that + jurisdiction, without reference to its conflict-of-law provisions. Nothing + in this Section shall prevent a party's ability to bring cross-claims or + counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. Any law or regulation which provides that + the language of a contract shall be construed against the drafter shall not + be used to construe this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version + of the License under which You originally received the Covered Software, + or under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a + modified version of this License if you rename the license and remove + any references to the name of the license steward (except to note that + such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary + Licenses If You choose to distribute Source Code Form that is + Incompatible With Secondary Licenses under the terms of this version of + the License, the notice described in Exhibit B of this License must be + attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, +then You may include the notice in a location (such as a LICENSE file in a +relevant directory) where a recipient would be likely to look for such a +notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice + + This Source Code Form is "Incompatible + With Secondary Licenses", as defined by + the Mozilla Public License, v. 2.0. \ No newline at end of file diff --git a/vendor/github.com/hashicorp/yamux/README.md b/vendor/github.com/hashicorp/yamux/README.md new file mode 100644 index 000000000..d4db7fc99 --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/README.md @@ -0,0 +1,86 @@ +# Yamux + +Yamux (Yet another Multiplexer) is a multiplexing library for Golang. +It relies on an underlying connection to provide reliability +and ordering, such as TCP or Unix domain sockets, and provides +stream-oriented multiplexing. It is inspired by SPDY but is not +interoperable with it. + +Yamux features include: + +* Bi-directional streams + * Streams can be opened by either client or server + * Useful for NAT traversal + * Server-side push support +* Flow control + * Avoid starvation + * Back-pressure to prevent overwhelming a receiver +* Keep Alives + * Enables persistent connections over a load balancer +* Efficient + * Enables thousands of logical streams with low overhead + +## Documentation + +For complete documentation, see the associated [Godoc](http://godoc.org/github.com/hashicorp/yamux). + +## Specification + +The full specification for Yamux is provided in the `spec.md` file. +It can be used as a guide to implementors of interoperable libraries. + +## Usage + +Using Yamux is remarkably simple: + +```go + +func client() { + // Get a TCP connection + conn, err := net.Dial(...) + if err != nil { + panic(err) + } + + // Setup client side of yamux + session, err := yamux.Client(conn, nil) + if err != nil { + panic(err) + } + + // Open a new stream + stream, err := session.Open() + if err != nil { + panic(err) + } + + // Stream implements net.Conn + stream.Write([]byte("ping")) +} + +func server() { + // Accept a TCP connection + conn, err := listener.Accept() + if err != nil { + panic(err) + } + + // Setup server side of yamux + session, err := yamux.Server(conn, nil) + if err != nil { + panic(err) + } + + // Accept a stream + stream, err := session.Accept() + if err != nil { + panic(err) + } + + // Listen for a message + buf := make([]byte, 4) + stream.Read(buf) +} + +``` + diff --git a/vendor/github.com/hashicorp/yamux/addr.go b/vendor/github.com/hashicorp/yamux/addr.go new file mode 100644 index 000000000..f6a00199c --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/addr.go @@ -0,0 +1,60 @@ +package yamux + +import ( + "fmt" + "net" +) + +// hasAddr is used to get the address from the underlying connection +type hasAddr interface { + LocalAddr() net.Addr + RemoteAddr() net.Addr +} + +// yamuxAddr is used when we cannot get the underlying address +type yamuxAddr struct { + Addr string +} + +func (*yamuxAddr) Network() string { + return "yamux" +} + +func (y *yamuxAddr) String() string { + return fmt.Sprintf("yamux:%s", y.Addr) +} + +// Addr is used to get the address of the listener. +func (s *Session) Addr() net.Addr { + return s.LocalAddr() +} + +// LocalAddr is used to get the local address of the +// underlying connection. +func (s *Session) LocalAddr() net.Addr { + addr, ok := s.conn.(hasAddr) + if !ok { + return &yamuxAddr{"local"} + } + return addr.LocalAddr() +} + +// RemoteAddr is used to get the address of remote end +// of the underlying connection +func (s *Session) RemoteAddr() net.Addr { + addr, ok := s.conn.(hasAddr) + if !ok { + return &yamuxAddr{"remote"} + } + return addr.RemoteAddr() +} + +// LocalAddr returns the local address +func (s *Stream) LocalAddr() net.Addr { + return s.session.LocalAddr() +} + +// RemoteAddr returns the remote address +func (s *Stream) RemoteAddr() net.Addr { + return s.session.RemoteAddr() +} diff --git a/vendor/github.com/hashicorp/yamux/const.go b/vendor/github.com/hashicorp/yamux/const.go new file mode 100644 index 000000000..4f5293828 --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/const.go @@ -0,0 +1,157 @@ +package yamux + +import ( + "encoding/binary" + "fmt" +) + +var ( + // ErrInvalidVersion means we received a frame with an + // invalid version + ErrInvalidVersion = fmt.Errorf("invalid protocol version") + + // ErrInvalidMsgType means we received a frame with an + // invalid message type + ErrInvalidMsgType = fmt.Errorf("invalid msg type") + + // ErrSessionShutdown is used if there is a shutdown during + // an operation + ErrSessionShutdown = fmt.Errorf("session shutdown") + + // ErrStreamsExhausted is returned if we have no more + // stream ids to issue + ErrStreamsExhausted = fmt.Errorf("streams exhausted") + + // ErrDuplicateStream is used if a duplicate stream is + // opened inbound + ErrDuplicateStream = fmt.Errorf("duplicate stream initiated") + + // ErrReceiveWindowExceeded indicates the window was exceeded + ErrRecvWindowExceeded = fmt.Errorf("recv window exceeded") + + // ErrTimeout is used when we reach an IO deadline + ErrTimeout = fmt.Errorf("i/o deadline reached") + + // ErrStreamClosed is returned when using a closed stream + ErrStreamClosed = fmt.Errorf("stream closed") + + // ErrUnexpectedFlag is set when we get an unexpected flag + ErrUnexpectedFlag = fmt.Errorf("unexpected flag") + + // ErrRemoteGoAway is used when we get a go away from the other side + ErrRemoteGoAway = fmt.Errorf("remote end is not accepting connections") + + // ErrConnectionReset is sent if a stream is reset. This can happen + // if the backlog is exceeded, or if there was a remote GoAway. + ErrConnectionReset = fmt.Errorf("connection reset") + + // ErrConnectionWriteTimeout indicates that we hit the "safety valve" + // timeout writing to the underlying stream connection. + ErrConnectionWriteTimeout = fmt.Errorf("connection write timeout") + + // ErrKeepAliveTimeout is sent if a missed keepalive caused the stream close + ErrKeepAliveTimeout = fmt.Errorf("keepalive timeout") +) + +const ( + // protoVersion is the only version we support + protoVersion uint8 = 0 +) + +const ( + // Data is used for data frames. They are followed + // by length bytes worth of payload. + typeData uint8 = iota + + // WindowUpdate is used to change the window of + // a given stream. The length indicates the delta + // update to the window. + typeWindowUpdate + + // Ping is sent as a keep-alive or to measure + // the RTT. The StreamID and Length value are echoed + // back in the response. + typePing + + // GoAway is sent to terminate a session. The StreamID + // should be 0 and the length is an error code. + typeGoAway +) + +const ( + // SYN is sent to signal a new stream. May + // be sent with a data payload + flagSYN uint16 = 1 << iota + + // ACK is sent to acknowledge a new stream. May + // be sent with a data payload + flagACK + + // FIN is sent to half-close the given stream. + // May be sent with a data payload. + flagFIN + + // RST is used to hard close a given stream. + flagRST +) + +const ( + // initialStreamWindow is the initial stream window size + initialStreamWindow uint32 = 256 * 1024 +) + +const ( + // goAwayNormal is sent on a normal termination + goAwayNormal uint32 = iota + + // goAwayProtoErr sent on a protocol error + goAwayProtoErr + + // goAwayInternalErr sent on an internal error + goAwayInternalErr +) + +const ( + sizeOfVersion = 1 + sizeOfType = 1 + sizeOfFlags = 2 + sizeOfStreamID = 4 + sizeOfLength = 4 + headerSize = sizeOfVersion + sizeOfType + sizeOfFlags + + sizeOfStreamID + sizeOfLength +) + +type header []byte + +func (h header) Version() uint8 { + return h[0] +} + +func (h header) MsgType() uint8 { + return h[1] +} + +func (h header) Flags() uint16 { + return binary.BigEndian.Uint16(h[2:4]) +} + +func (h header) StreamID() uint32 { + return binary.BigEndian.Uint32(h[4:8]) +} + +func (h header) Length() uint32 { + return binary.BigEndian.Uint32(h[8:12]) +} + +func (h header) String() string { + return fmt.Sprintf("Vsn:%d Type:%d Flags:%d StreamID:%d Length:%d", + h.Version(), h.MsgType(), h.Flags(), h.StreamID(), h.Length()) +} + +func (h header) encode(msgType uint8, flags uint16, streamID uint32, length uint32) { + h[0] = protoVersion + h[1] = msgType + binary.BigEndian.PutUint16(h[2:4], flags) + binary.BigEndian.PutUint32(h[4:8], streamID) + binary.BigEndian.PutUint32(h[8:12], length) +} diff --git a/vendor/github.com/hashicorp/yamux/go.mod b/vendor/github.com/hashicorp/yamux/go.mod new file mode 100644 index 000000000..672a0e581 --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/go.mod @@ -0,0 +1 @@ +module github.com/hashicorp/yamux diff --git a/vendor/github.com/hashicorp/yamux/mux.go b/vendor/github.com/hashicorp/yamux/mux.go new file mode 100644 index 000000000..18a078c8a --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/mux.go @@ -0,0 +1,98 @@ +package yamux + +import ( + "fmt" + "io" + "log" + "os" + "time" +) + +// Config is used to tune the Yamux session +type Config struct { + // AcceptBacklog is used to limit how many streams may be + // waiting an accept. + AcceptBacklog int + + // EnableKeepalive is used to do a period keep alive + // messages using a ping. + EnableKeepAlive bool + + // KeepAliveInterval is how often to perform the keep alive + KeepAliveInterval time.Duration + + // ConnectionWriteTimeout is meant to be a "safety valve" timeout after + // we which will suspect a problem with the underlying connection and + // close it. This is only applied to writes, where's there's generally + // an expectation that things will move along quickly. + ConnectionWriteTimeout time.Duration + + // MaxStreamWindowSize is used to control the maximum + // window size that we allow for a stream. + MaxStreamWindowSize uint32 + + // LogOutput is used to control the log destination. Either Logger or + // LogOutput can be set, not both. + LogOutput io.Writer + + // Logger is used to pass in the logger to be used. Either Logger or + // LogOutput can be set, not both. + Logger *log.Logger +} + +// DefaultConfig is used to return a default configuration +func DefaultConfig() *Config { + return &Config{ + AcceptBacklog: 256, + EnableKeepAlive: true, + KeepAliveInterval: 30 * time.Second, + ConnectionWriteTimeout: 10 * time.Second, + MaxStreamWindowSize: initialStreamWindow, + LogOutput: os.Stderr, + } +} + +// VerifyConfig is used to verify the sanity of configuration +func VerifyConfig(config *Config) error { + if config.AcceptBacklog <= 0 { + return fmt.Errorf("backlog must be positive") + } + if config.KeepAliveInterval == 0 { + return fmt.Errorf("keep-alive interval must be positive") + } + if config.MaxStreamWindowSize < initialStreamWindow { + return fmt.Errorf("MaxStreamWindowSize must be larger than %d", initialStreamWindow) + } + if config.LogOutput != nil && config.Logger != nil { + return fmt.Errorf("both Logger and LogOutput may not be set, select one") + } else if config.LogOutput == nil && config.Logger == nil { + return fmt.Errorf("one of Logger or LogOutput must be set, select one") + } + return nil +} + +// Server is used to initialize a new server-side connection. +// There must be at most one server-side connection. If a nil config is +// provided, the DefaultConfiguration will be used. +func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) { + if config == nil { + config = DefaultConfig() + } + if err := VerifyConfig(config); err != nil { + return nil, err + } + return newSession(config, conn, false), nil +} + +// Client is used to initialize a new client-side connection. +// There must be at most one client-side connection. +func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) { + if config == nil { + config = DefaultConfig() + } + + if err := VerifyConfig(config); err != nil { + return nil, err + } + return newSession(config, conn, true), nil +} diff --git a/vendor/github.com/hashicorp/yamux/session.go b/vendor/github.com/hashicorp/yamux/session.go new file mode 100644 index 000000000..a80ddec35 --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/session.go @@ -0,0 +1,653 @@ +package yamux + +import ( + "bufio" + "fmt" + "io" + "io/ioutil" + "log" + "math" + "net" + "strings" + "sync" + "sync/atomic" + "time" +) + +// Session is used to wrap a reliable ordered connection and to +// multiplex it into multiple streams. +type Session struct { + // remoteGoAway indicates the remote side does + // not want futher connections. Must be first for alignment. + remoteGoAway int32 + + // localGoAway indicates that we should stop + // accepting futher connections. Must be first for alignment. + localGoAway int32 + + // nextStreamID is the next stream we should + // send. This depends if we are a client/server. + nextStreamID uint32 + + // config holds our configuration + config *Config + + // logger is used for our logs + logger *log.Logger + + // conn is the underlying connection + conn io.ReadWriteCloser + + // bufRead is a buffered reader + bufRead *bufio.Reader + + // pings is used to track inflight pings + pings map[uint32]chan struct{} + pingID uint32 + pingLock sync.Mutex + + // streams maps a stream id to a stream, and inflight has an entry + // for any outgoing stream that has not yet been established. Both are + // protected by streamLock. + streams map[uint32]*Stream + inflight map[uint32]struct{} + streamLock sync.Mutex + + // synCh acts like a semaphore. It is sized to the AcceptBacklog which + // is assumed to be symmetric between the client and server. This allows + // the client to avoid exceeding the backlog and instead blocks the open. + synCh chan struct{} + + // acceptCh is used to pass ready streams to the client + acceptCh chan *Stream + + // sendCh is used to mark a stream as ready to send, + // or to send a header out directly. + sendCh chan sendReady + + // recvDoneCh is closed when recv() exits to avoid a race + // between stream registration and stream shutdown + recvDoneCh chan struct{} + + // shutdown is used to safely close a session + shutdown bool + shutdownErr error + shutdownCh chan struct{} + shutdownLock sync.Mutex +} + +// sendReady is used to either mark a stream as ready +// or to directly send a header +type sendReady struct { + Hdr []byte + Body io.Reader + Err chan error +} + +// newSession is used to construct a new session +func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session { + logger := config.Logger + if logger == nil { + logger = log.New(config.LogOutput, "", log.LstdFlags) + } + + s := &Session{ + config: config, + logger: logger, + conn: conn, + bufRead: bufio.NewReader(conn), + pings: make(map[uint32]chan struct{}), + streams: make(map[uint32]*Stream), + inflight: make(map[uint32]struct{}), + synCh: make(chan struct{}, config.AcceptBacklog), + acceptCh: make(chan *Stream, config.AcceptBacklog), + sendCh: make(chan sendReady, 64), + recvDoneCh: make(chan struct{}), + shutdownCh: make(chan struct{}), + } + if client { + s.nextStreamID = 1 + } else { + s.nextStreamID = 2 + } + go s.recv() + go s.send() + if config.EnableKeepAlive { + go s.keepalive() + } + return s +} + +// IsClosed does a safe check to see if we have shutdown +func (s *Session) IsClosed() bool { + select { + case <-s.shutdownCh: + return true + default: + return false + } +} + +// CloseChan returns a read-only channel which is closed as +// soon as the session is closed. +func (s *Session) CloseChan() <-chan struct{} { + return s.shutdownCh +} + +// NumStreams returns the number of currently open streams +func (s *Session) NumStreams() int { + s.streamLock.Lock() + num := len(s.streams) + s.streamLock.Unlock() + return num +} + +// Open is used to create a new stream as a net.Conn +func (s *Session) Open() (net.Conn, error) { + conn, err := s.OpenStream() + if err != nil { + return nil, err + } + return conn, nil +} + +// OpenStream is used to create a new stream +func (s *Session) OpenStream() (*Stream, error) { + if s.IsClosed() { + return nil, ErrSessionShutdown + } + if atomic.LoadInt32(&s.remoteGoAway) == 1 { + return nil, ErrRemoteGoAway + } + + // Block if we have too many inflight SYNs + select { + case s.synCh <- struct{}{}: + case <-s.shutdownCh: + return nil, ErrSessionShutdown + } + +GET_ID: + // Get an ID, and check for stream exhaustion + id := atomic.LoadUint32(&s.nextStreamID) + if id >= math.MaxUint32-1 { + return nil, ErrStreamsExhausted + } + if !atomic.CompareAndSwapUint32(&s.nextStreamID, id, id+2) { + goto GET_ID + } + + // Register the stream + stream := newStream(s, id, streamInit) + s.streamLock.Lock() + s.streams[id] = stream + s.inflight[id] = struct{}{} + s.streamLock.Unlock() + + // Send the window update to create + if err := stream.sendWindowUpdate(); err != nil { + select { + case <-s.synCh: + default: + s.logger.Printf("[ERR] yamux: aborted stream open without inflight syn semaphore") + } + return nil, err + } + return stream, nil +} + +// Accept is used to block until the next available stream +// is ready to be accepted. +func (s *Session) Accept() (net.Conn, error) { + conn, err := s.AcceptStream() + if err != nil { + return nil, err + } + return conn, err +} + +// AcceptStream is used to block until the next available stream +// is ready to be accepted. +func (s *Session) AcceptStream() (*Stream, error) { + select { + case stream := <-s.acceptCh: + if err := stream.sendWindowUpdate(); err != nil { + return nil, err + } + return stream, nil + case <-s.shutdownCh: + return nil, s.shutdownErr + } +} + +// Close is used to close the session and all streams. +// Attempts to send a GoAway before closing the connection. +func (s *Session) Close() error { + s.shutdownLock.Lock() + defer s.shutdownLock.Unlock() + + if s.shutdown { + return nil + } + s.shutdown = true + if s.shutdownErr == nil { + s.shutdownErr = ErrSessionShutdown + } + close(s.shutdownCh) + s.conn.Close() + <-s.recvDoneCh + + s.streamLock.Lock() + defer s.streamLock.Unlock() + for _, stream := range s.streams { + stream.forceClose() + } + return nil +} + +// exitErr is used to handle an error that is causing the +// session to terminate. +func (s *Session) exitErr(err error) { + s.shutdownLock.Lock() + if s.shutdownErr == nil { + s.shutdownErr = err + } + s.shutdownLock.Unlock() + s.Close() +} + +// GoAway can be used to prevent accepting further +// connections. It does not close the underlying conn. +func (s *Session) GoAway() error { + return s.waitForSend(s.goAway(goAwayNormal), nil) +} + +// goAway is used to send a goAway message +func (s *Session) goAway(reason uint32) header { + atomic.SwapInt32(&s.localGoAway, 1) + hdr := header(make([]byte, headerSize)) + hdr.encode(typeGoAway, 0, 0, reason) + return hdr +} + +// Ping is used to measure the RTT response time +func (s *Session) Ping() (time.Duration, error) { + // Get a channel for the ping + ch := make(chan struct{}) + + // Get a new ping id, mark as pending + s.pingLock.Lock() + id := s.pingID + s.pingID++ + s.pings[id] = ch + s.pingLock.Unlock() + + // Send the ping request + hdr := header(make([]byte, headerSize)) + hdr.encode(typePing, flagSYN, 0, id) + if err := s.waitForSend(hdr, nil); err != nil { + return 0, err + } + + // Wait for a response + start := time.Now() + select { + case <-ch: + case <-time.After(s.config.ConnectionWriteTimeout): + s.pingLock.Lock() + delete(s.pings, id) // Ignore it if a response comes later. + s.pingLock.Unlock() + return 0, ErrTimeout + case <-s.shutdownCh: + return 0, ErrSessionShutdown + } + + // Compute the RTT + return time.Now().Sub(start), nil +} + +// keepalive is a long running goroutine that periodically does +// a ping to keep the connection alive. +func (s *Session) keepalive() { + for { + select { + case <-time.After(s.config.KeepAliveInterval): + _, err := s.Ping() + if err != nil { + if err != ErrSessionShutdown { + s.logger.Printf("[ERR] yamux: keepalive failed: %v", err) + s.exitErr(ErrKeepAliveTimeout) + } + return + } + case <-s.shutdownCh: + return + } + } +} + +// waitForSendErr waits to send a header, checking for a potential shutdown +func (s *Session) waitForSend(hdr header, body io.Reader) error { + errCh := make(chan error, 1) + return s.waitForSendErr(hdr, body, errCh) +} + +// waitForSendErr waits to send a header with optional data, checking for a +// potential shutdown. Since there's the expectation that sends can happen +// in a timely manner, we enforce the connection write timeout here. +func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error { + t := timerPool.Get() + timer := t.(*time.Timer) + timer.Reset(s.config.ConnectionWriteTimeout) + defer func() { + timer.Stop() + select { + case <-timer.C: + default: + } + timerPool.Put(t) + }() + + ready := sendReady{Hdr: hdr, Body: body, Err: errCh} + select { + case s.sendCh <- ready: + case <-s.shutdownCh: + return ErrSessionShutdown + case <-timer.C: + return ErrConnectionWriteTimeout + } + + select { + case err := <-errCh: + return err + case <-s.shutdownCh: + return ErrSessionShutdown + case <-timer.C: + return ErrConnectionWriteTimeout + } +} + +// sendNoWait does a send without waiting. Since there's the expectation that +// the send happens right here, we enforce the connection write timeout if we +// can't queue the header to be sent. +func (s *Session) sendNoWait(hdr header) error { + t := timerPool.Get() + timer := t.(*time.Timer) + timer.Reset(s.config.ConnectionWriteTimeout) + defer func() { + timer.Stop() + select { + case <-timer.C: + default: + } + timerPool.Put(t) + }() + + select { + case s.sendCh <- sendReady{Hdr: hdr}: + return nil + case <-s.shutdownCh: + return ErrSessionShutdown + case <-timer.C: + return ErrConnectionWriteTimeout + } +} + +// send is a long running goroutine that sends data +func (s *Session) send() { + for { + select { + case ready := <-s.sendCh: + // Send a header if ready + if ready.Hdr != nil { + sent := 0 + for sent < len(ready.Hdr) { + n, err := s.conn.Write(ready.Hdr[sent:]) + if err != nil { + s.logger.Printf("[ERR] yamux: Failed to write header: %v", err) + asyncSendErr(ready.Err, err) + s.exitErr(err) + return + } + sent += n + } + } + + // Send data from a body if given + if ready.Body != nil { + _, err := io.Copy(s.conn, ready.Body) + if err != nil { + s.logger.Printf("[ERR] yamux: Failed to write body: %v", err) + asyncSendErr(ready.Err, err) + s.exitErr(err) + return + } + } + + // No error, successful send + asyncSendErr(ready.Err, nil) + case <-s.shutdownCh: + return + } + } +} + +// recv is a long running goroutine that accepts new data +func (s *Session) recv() { + if err := s.recvLoop(); err != nil { + s.exitErr(err) + } +} + +// Ensure that the index of the handler (typeData/typeWindowUpdate/etc) matches the message type +var ( + handlers = []func(*Session, header) error{ + typeData: (*Session).handleStreamMessage, + typeWindowUpdate: (*Session).handleStreamMessage, + typePing: (*Session).handlePing, + typeGoAway: (*Session).handleGoAway, + } +) + +// recvLoop continues to receive data until a fatal error is encountered +func (s *Session) recvLoop() error { + defer close(s.recvDoneCh) + hdr := header(make([]byte, headerSize)) + for { + // Read the header + if _, err := io.ReadFull(s.bufRead, hdr); err != nil { + if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") { + s.logger.Printf("[ERR] yamux: Failed to read header: %v", err) + } + return err + } + + // Verify the version + if hdr.Version() != protoVersion { + s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version()) + return ErrInvalidVersion + } + + mt := hdr.MsgType() + if mt < typeData || mt > typeGoAway { + return ErrInvalidMsgType + } + + if err := handlers[mt](s, hdr); err != nil { + return err + } + } +} + +// handleStreamMessage handles either a data or window update frame +func (s *Session) handleStreamMessage(hdr header) error { + // Check for a new stream creation + id := hdr.StreamID() + flags := hdr.Flags() + if flags&flagSYN == flagSYN { + if err := s.incomingStream(id); err != nil { + return err + } + } + + // Get the stream + s.streamLock.Lock() + stream := s.streams[id] + s.streamLock.Unlock() + + // If we do not have a stream, likely we sent a RST + if stream == nil { + // Drain any data on the wire + if hdr.MsgType() == typeData && hdr.Length() > 0 { + s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id) + if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil { + s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err) + return nil + } + } else { + s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr) + } + return nil + } + + // Check if this is a window update + if hdr.MsgType() == typeWindowUpdate { + if err := stream.incrSendWindow(hdr, flags); err != nil { + if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { + s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) + } + return err + } + return nil + } + + // Read the new data + if err := stream.readData(hdr, flags, s.bufRead); err != nil { + if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { + s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) + } + return err + } + return nil +} + +// handlePing is invokde for a typePing frame +func (s *Session) handlePing(hdr header) error { + flags := hdr.Flags() + pingID := hdr.Length() + + // Check if this is a query, respond back in a separate context so we + // don't interfere with the receiving thread blocking for the write. + if flags&flagSYN == flagSYN { + go func() { + hdr := header(make([]byte, headerSize)) + hdr.encode(typePing, flagACK, 0, pingID) + if err := s.sendNoWait(hdr); err != nil { + s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err) + } + }() + return nil + } + + // Handle a response + s.pingLock.Lock() + ch := s.pings[pingID] + if ch != nil { + delete(s.pings, pingID) + close(ch) + } + s.pingLock.Unlock() + return nil +} + +// handleGoAway is invokde for a typeGoAway frame +func (s *Session) handleGoAway(hdr header) error { + code := hdr.Length() + switch code { + case goAwayNormal: + atomic.SwapInt32(&s.remoteGoAway, 1) + case goAwayProtoErr: + s.logger.Printf("[ERR] yamux: received protocol error go away") + return fmt.Errorf("yamux protocol error") + case goAwayInternalErr: + s.logger.Printf("[ERR] yamux: received internal error go away") + return fmt.Errorf("remote yamux internal error") + default: + s.logger.Printf("[ERR] yamux: received unexpected go away") + return fmt.Errorf("unexpected go away received") + } + return nil +} + +// incomingStream is used to create a new incoming stream +func (s *Session) incomingStream(id uint32) error { + // Reject immediately if we are doing a go away + if atomic.LoadInt32(&s.localGoAway) == 1 { + hdr := header(make([]byte, headerSize)) + hdr.encode(typeWindowUpdate, flagRST, id, 0) + return s.sendNoWait(hdr) + } + + // Allocate a new stream + stream := newStream(s, id, streamSYNReceived) + + s.streamLock.Lock() + defer s.streamLock.Unlock() + + // Check if stream already exists + if _, ok := s.streams[id]; ok { + s.logger.Printf("[ERR] yamux: duplicate stream declared") + if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil { + s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr) + } + return ErrDuplicateStream + } + + // Register the stream + s.streams[id] = stream + + // Check if we've exceeded the backlog + select { + case s.acceptCh <- stream: + return nil + default: + // Backlog exceeded! RST the stream + s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset") + delete(s.streams, id) + stream.sendHdr.encode(typeWindowUpdate, flagRST, id, 0) + return s.sendNoWait(stream.sendHdr) + } +} + +// closeStream is used to close a stream once both sides have +// issued a close. If there was an in-flight SYN and the stream +// was not yet established, then this will give the credit back. +func (s *Session) closeStream(id uint32) { + s.streamLock.Lock() + if _, ok := s.inflight[id]; ok { + select { + case <-s.synCh: + default: + s.logger.Printf("[ERR] yamux: SYN tracking out of sync") + } + } + delete(s.streams, id) + s.streamLock.Unlock() +} + +// establishStream is used to mark a stream that was in the +// SYN Sent state as established. +func (s *Session) establishStream(id uint32) { + s.streamLock.Lock() + if _, ok := s.inflight[id]; ok { + delete(s.inflight, id) + } else { + s.logger.Printf("[ERR] yamux: established stream without inflight SYN (no tracking entry)") + } + select { + case <-s.synCh: + default: + s.logger.Printf("[ERR] yamux: established stream without inflight SYN (didn't have semaphore)") + } + s.streamLock.Unlock() +} diff --git a/vendor/github.com/hashicorp/yamux/spec.md b/vendor/github.com/hashicorp/yamux/spec.md new file mode 100644 index 000000000..183d797bd --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/spec.md @@ -0,0 +1,140 @@ +# Specification + +We use this document to detail the internal specification of Yamux. +This is used both as a guide for implementing Yamux, but also for +alternative interoperable libraries to be built. + +# Framing + +Yamux uses a streaming connection underneath, but imposes a message +framing so that it can be shared between many logical streams. Each +frame contains a header like: + +* Version (8 bits) +* Type (8 bits) +* Flags (16 bits) +* StreamID (32 bits) +* Length (32 bits) + +This means that each header has a 12 byte overhead. +All fields are encoded in network order (big endian). +Each field is described below: + +## Version Field + +The version field is used for future backward compatibility. At the +current time, the field is always set to 0, to indicate the initial +version. + +## Type Field + +The type field is used to switch the frame message type. The following +message types are supported: + +* 0x0 Data - Used to transmit data. May transmit zero length payloads + depending on the flags. + +* 0x1 Window Update - Used to updated the senders receive window size. + This is used to implement per-session flow control. + +* 0x2 Ping - Used to measure RTT. It can also be used to heart-beat + and do keep-alives over TCP. + +* 0x3 Go Away - Used to close a session. + +## Flag Field + +The flags field is used to provide additional information related +to the message type. The following flags are supported: + +* 0x1 SYN - Signals the start of a new stream. May be sent with a data or + window update message. Also sent with a ping to indicate outbound. + +* 0x2 ACK - Acknowledges the start of a new stream. May be sent with a data + or window update message. Also sent with a ping to indicate response. + +* 0x4 FIN - Performs a half-close of a stream. May be sent with a data + message or window update. + +* 0x8 RST - Reset a stream immediately. May be sent with a data or + window update message. + +## StreamID Field + +The StreamID field is used to identify the logical stream the frame +is addressing. The client side should use odd ID's, and the server even. +This prevents any collisions. Additionally, the 0 ID is reserved to represent +the session. + +Both Ping and Go Away messages should always use the 0 StreamID. + +## Length Field + +The meaning of the length field depends on the message type: + +* Data - provides the length of bytes following the header +* Window update - provides a delta update to the window size +* Ping - Contains an opaque value, echoed back +* Go Away - Contains an error code + +# Message Flow + +There is no explicit connection setup, as Yamux relies on an underlying +transport to be provided. However, there is a distinction between client +and server side of the connection. + +## Opening a stream + +To open a stream, an initial data or window update frame is sent +with a new StreamID. The SYN flag should be set to signal a new stream. + +The receiver must then reply with either a data or window update frame +with the StreamID along with the ACK flag to accept the stream or with +the RST flag to reject the stream. + +Because we are relying on the reliable stream underneath, a connection +can begin sending data once the SYN flag is sent. The corresponding +ACK does not need to be received. This is particularly well suited +for an RPC system where a client wants to open a stream and immediately +fire a request without waiting for the RTT of the ACK. + +This does introduce the possibility of a connection being rejected +after data has been sent already. This is a slight semantic difference +from TCP, where the conection cannot be refused after it is opened. +Clients should be prepared to handle this by checking for an error +that indicates a RST was received. + +## Closing a stream + +To close a stream, either side sends a data or window update frame +along with the FIN flag. This does a half-close indicating the sender +will send no further data. + +Once both sides have closed the connection, the stream is closed. + +Alternatively, if an error occurs, the RST flag can be used to +hard close a stream immediately. + +## Flow Control + +When Yamux is initially starts each stream with a 256KB window size. +There is no window size for the session. + +To prevent the streams from stalling, window update frames should be +sent regularly. Yamux can be configured to provide a larger limit for +windows sizes. Both sides assume the initial 256KB window, but can +immediately send a window update as part of the SYN/ACK indicating a +larger window. + +Both sides should track the number of bytes sent in Data frames +only, as only they are tracked as part of the window size. + +## Session termination + +When a session is being terminated, the Go Away message should +be sent. The Length should be set to one of the following to +provide an error code: + +* 0x0 Normal termination +* 0x1 Protocol error +* 0x2 Internal error diff --git a/vendor/github.com/hashicorp/yamux/stream.go b/vendor/github.com/hashicorp/yamux/stream.go new file mode 100644 index 000000000..aa2391973 --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/stream.go @@ -0,0 +1,470 @@ +package yamux + +import ( + "bytes" + "io" + "sync" + "sync/atomic" + "time" +) + +type streamState int + +const ( + streamInit streamState = iota + streamSYNSent + streamSYNReceived + streamEstablished + streamLocalClose + streamRemoteClose + streamClosed + streamReset +) + +// Stream is used to represent a logical stream +// within a session. +type Stream struct { + recvWindow uint32 + sendWindow uint32 + + id uint32 + session *Session + + state streamState + stateLock sync.Mutex + + recvBuf *bytes.Buffer + recvLock sync.Mutex + + controlHdr header + controlErr chan error + controlHdrLock sync.Mutex + + sendHdr header + sendErr chan error + sendLock sync.Mutex + + recvNotifyCh chan struct{} + sendNotifyCh chan struct{} + + readDeadline atomic.Value // time.Time + writeDeadline atomic.Value // time.Time +} + +// newStream is used to construct a new stream within +// a given session for an ID +func newStream(session *Session, id uint32, state streamState) *Stream { + s := &Stream{ + id: id, + session: session, + state: state, + controlHdr: header(make([]byte, headerSize)), + controlErr: make(chan error, 1), + sendHdr: header(make([]byte, headerSize)), + sendErr: make(chan error, 1), + recvWindow: initialStreamWindow, + sendWindow: initialStreamWindow, + recvNotifyCh: make(chan struct{}, 1), + sendNotifyCh: make(chan struct{}, 1), + } + s.readDeadline.Store(time.Time{}) + s.writeDeadline.Store(time.Time{}) + return s +} + +// Session returns the associated stream session +func (s *Stream) Session() *Session { + return s.session +} + +// StreamID returns the ID of this stream +func (s *Stream) StreamID() uint32 { + return s.id +} + +// Read is used to read from the stream +func (s *Stream) Read(b []byte) (n int, err error) { + defer asyncNotify(s.recvNotifyCh) +START: + s.stateLock.Lock() + switch s.state { + case streamLocalClose: + fallthrough + case streamRemoteClose: + fallthrough + case streamClosed: + s.recvLock.Lock() + if s.recvBuf == nil || s.recvBuf.Len() == 0 { + s.recvLock.Unlock() + s.stateLock.Unlock() + return 0, io.EOF + } + s.recvLock.Unlock() + case streamReset: + s.stateLock.Unlock() + return 0, ErrConnectionReset + } + s.stateLock.Unlock() + + // If there is no data available, block + s.recvLock.Lock() + if s.recvBuf == nil || s.recvBuf.Len() == 0 { + s.recvLock.Unlock() + goto WAIT + } + + // Read any bytes + n, _ = s.recvBuf.Read(b) + s.recvLock.Unlock() + + // Send a window update potentially + err = s.sendWindowUpdate() + return n, err + +WAIT: + var timeout <-chan time.Time + var timer *time.Timer + readDeadline := s.readDeadline.Load().(time.Time) + if !readDeadline.IsZero() { + delay := readDeadline.Sub(time.Now()) + timer = time.NewTimer(delay) + timeout = timer.C + } + select { + case <-s.recvNotifyCh: + if timer != nil { + timer.Stop() + } + goto START + case <-timeout: + return 0, ErrTimeout + } +} + +// Write is used to write to the stream +func (s *Stream) Write(b []byte) (n int, err error) { + s.sendLock.Lock() + defer s.sendLock.Unlock() + total := 0 + for total < len(b) { + n, err := s.write(b[total:]) + total += n + if err != nil { + return total, err + } + } + return total, nil +} + +// write is used to write to the stream, may return on +// a short write. +func (s *Stream) write(b []byte) (n int, err error) { + var flags uint16 + var max uint32 + var body io.Reader +START: + s.stateLock.Lock() + switch s.state { + case streamLocalClose: + fallthrough + case streamClosed: + s.stateLock.Unlock() + return 0, ErrStreamClosed + case streamReset: + s.stateLock.Unlock() + return 0, ErrConnectionReset + } + s.stateLock.Unlock() + + // If there is no data available, block + window := atomic.LoadUint32(&s.sendWindow) + if window == 0 { + goto WAIT + } + + // Determine the flags if any + flags = s.sendFlags() + + // Send up to our send window + max = min(window, uint32(len(b))) + body = bytes.NewReader(b[:max]) + + // Send the header + s.sendHdr.encode(typeData, flags, s.id, max) + if err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil { + return 0, err + } + + // Reduce our send window + atomic.AddUint32(&s.sendWindow, ^uint32(max-1)) + + // Unlock + return int(max), err + +WAIT: + var timeout <-chan time.Time + writeDeadline := s.writeDeadline.Load().(time.Time) + if !writeDeadline.IsZero() { + delay := writeDeadline.Sub(time.Now()) + timeout = time.After(delay) + } + select { + case <-s.sendNotifyCh: + goto START + case <-timeout: + return 0, ErrTimeout + } + return 0, nil +} + +// sendFlags determines any flags that are appropriate +// based on the current stream state +func (s *Stream) sendFlags() uint16 { + s.stateLock.Lock() + defer s.stateLock.Unlock() + var flags uint16 + switch s.state { + case streamInit: + flags |= flagSYN + s.state = streamSYNSent + case streamSYNReceived: + flags |= flagACK + s.state = streamEstablished + } + return flags +} + +// sendWindowUpdate potentially sends a window update enabling +// further writes to take place. Must be invoked with the lock. +func (s *Stream) sendWindowUpdate() error { + s.controlHdrLock.Lock() + defer s.controlHdrLock.Unlock() + + // Determine the delta update + max := s.session.config.MaxStreamWindowSize + var bufLen uint32 + s.recvLock.Lock() + if s.recvBuf != nil { + bufLen = uint32(s.recvBuf.Len()) + } + delta := (max - bufLen) - s.recvWindow + + // Determine the flags if any + flags := s.sendFlags() + + // Check if we can omit the update + if delta < (max/2) && flags == 0 { + s.recvLock.Unlock() + return nil + } + + // Update our window + s.recvWindow += delta + s.recvLock.Unlock() + + // Send the header + s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta) + if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil { + return err + } + return nil +} + +// sendClose is used to send a FIN +func (s *Stream) sendClose() error { + s.controlHdrLock.Lock() + defer s.controlHdrLock.Unlock() + + flags := s.sendFlags() + flags |= flagFIN + s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0) + if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil { + return err + } + return nil +} + +// Close is used to close the stream +func (s *Stream) Close() error { + closeStream := false + s.stateLock.Lock() + switch s.state { + // Opened means we need to signal a close + case streamSYNSent: + fallthrough + case streamSYNReceived: + fallthrough + case streamEstablished: + s.state = streamLocalClose + goto SEND_CLOSE + + case streamLocalClose: + case streamRemoteClose: + s.state = streamClosed + closeStream = true + goto SEND_CLOSE + + case streamClosed: + case streamReset: + default: + panic("unhandled state") + } + s.stateLock.Unlock() + return nil +SEND_CLOSE: + s.stateLock.Unlock() + s.sendClose() + s.notifyWaiting() + if closeStream { + s.session.closeStream(s.id) + } + return nil +} + +// forceClose is used for when the session is exiting +func (s *Stream) forceClose() { + s.stateLock.Lock() + s.state = streamClosed + s.stateLock.Unlock() + s.notifyWaiting() +} + +// processFlags is used to update the state of the stream +// based on set flags, if any. Lock must be held +func (s *Stream) processFlags(flags uint16) error { + // Close the stream without holding the state lock + closeStream := false + defer func() { + if closeStream { + s.session.closeStream(s.id) + } + }() + + s.stateLock.Lock() + defer s.stateLock.Unlock() + if flags&flagACK == flagACK { + if s.state == streamSYNSent { + s.state = streamEstablished + } + s.session.establishStream(s.id) + } + if flags&flagFIN == flagFIN { + switch s.state { + case streamSYNSent: + fallthrough + case streamSYNReceived: + fallthrough + case streamEstablished: + s.state = streamRemoteClose + s.notifyWaiting() + case streamLocalClose: + s.state = streamClosed + closeStream = true + s.notifyWaiting() + default: + s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state) + return ErrUnexpectedFlag + } + } + if flags&flagRST == flagRST { + s.state = streamReset + closeStream = true + s.notifyWaiting() + } + return nil +} + +// notifyWaiting notifies all the waiting channels +func (s *Stream) notifyWaiting() { + asyncNotify(s.recvNotifyCh) + asyncNotify(s.sendNotifyCh) +} + +// incrSendWindow updates the size of our send window +func (s *Stream) incrSendWindow(hdr header, flags uint16) error { + if err := s.processFlags(flags); err != nil { + return err + } + + // Increase window, unblock a sender + atomic.AddUint32(&s.sendWindow, hdr.Length()) + asyncNotify(s.sendNotifyCh) + return nil +} + +// readData is used to handle a data frame +func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error { + if err := s.processFlags(flags); err != nil { + return err + } + + // Check that our recv window is not exceeded + length := hdr.Length() + if length == 0 { + return nil + } + + // Wrap in a limited reader + conn = &io.LimitedReader{R: conn, N: int64(length)} + + // Copy into buffer + s.recvLock.Lock() + + if length > s.recvWindow { + s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length) + return ErrRecvWindowExceeded + } + + if s.recvBuf == nil { + // Allocate the receive buffer just-in-time to fit the full data frame. + // This way we can read in the whole packet without further allocations. + s.recvBuf = bytes.NewBuffer(make([]byte, 0, length)) + } + if _, err := io.Copy(s.recvBuf, conn); err != nil { + s.session.logger.Printf("[ERR] yamux: Failed to read stream data: %v", err) + s.recvLock.Unlock() + return err + } + + // Decrement the receive window + s.recvWindow -= length + s.recvLock.Unlock() + + // Unblock any readers + asyncNotify(s.recvNotifyCh) + return nil +} + +// SetDeadline sets the read and write deadlines +func (s *Stream) SetDeadline(t time.Time) error { + if err := s.SetReadDeadline(t); err != nil { + return err + } + if err := s.SetWriteDeadline(t); err != nil { + return err + } + return nil +} + +// SetReadDeadline sets the deadline for future Read calls. +func (s *Stream) SetReadDeadline(t time.Time) error { + s.readDeadline.Store(t) + return nil +} + +// SetWriteDeadline sets the deadline for future Write calls +func (s *Stream) SetWriteDeadline(t time.Time) error { + s.writeDeadline.Store(t) + return nil +} + +// Shrink is used to compact the amount of buffers utilized +// This is useful when using Yamux in a connection pool to reduce +// the idle memory utilization. +func (s *Stream) Shrink() { + s.recvLock.Lock() + if s.recvBuf != nil && s.recvBuf.Len() == 0 { + s.recvBuf = nil + } + s.recvLock.Unlock() +} diff --git a/vendor/github.com/hashicorp/yamux/util.go b/vendor/github.com/hashicorp/yamux/util.go new file mode 100644 index 000000000..8a73e9249 --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/util.go @@ -0,0 +1,43 @@ +package yamux + +import ( + "sync" + "time" +) + +var ( + timerPool = &sync.Pool{ + New: func() interface{} { + timer := time.NewTimer(time.Hour * 1e6) + timer.Stop() + return timer + }, + } +) + +// asyncSendErr is used to try an async send of an error +func asyncSendErr(ch chan error, err error) { + if ch == nil { + return + } + select { + case ch <- err: + default: + } +} + +// asyncNotify is used to signal a waiting goroutine +func asyncNotify(ch chan struct{}) { + select { + case ch <- struct{}{}: + default: + } +} + +// min computes the minimum of two values +func min(a, b uint32) uint32 { + if a < b { + return a + } + return b +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 88fab3997..831e5b965 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -38,6 +38,8 @@ github.com/google/uuid github.com/gorilla/handlers # github.com/gorilla/securecookie v1.1.1 github.com/gorilla/securecookie +# github.com/hashicorp/yamux v0.0.0-20190923154419-df201c70410d +github.com/hashicorp/yamux # github.com/inconshreveable/mousetrap v1.0.0 github.com/inconshreveable/mousetrap # github.com/konsorten/go-windows-terminal-sequences v1.0.2 From 7a3ab83afe4420f906905838e5fdeda491b1377f Mon Sep 17 00:00:00 2001 From: kifen Date: Fri, 3 Jan 2020 07:52:31 +0100 Subject: [PATCH 25/33] rename skyproxy to skysocks --- cmd/apps/skysocks-client/skysocks-client.go | 2 +- cmd/skywire-cli/commands/node/gen-config.go | 22 ++++++++++----------- internal/skyenv/const.go | 16 +++++++-------- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/cmd/apps/skysocks-client/skysocks-client.go b/cmd/apps/skysocks-client/skysocks-client.go index 0561c98f6..1d1dde9d8 100644 --- a/cmd/apps/skysocks-client/skysocks-client.go +++ b/cmd/apps/skysocks-client/skysocks-client.go @@ -32,7 +32,7 @@ func main() { log := app.NewLogger(appName) skysocks.Log = log.PackageLogger("skysocks") - var addr = flag.String("addr", skyenv.SkyproxyClientAddr, "Client address to listen on") + var addr = flag.String("addr", skyenv.SkysocksClientAddr, "Client address to listen on") var serverPK = flag.String("srv", "", "PubKey of the server to connect to") flag.Parse() diff --git a/cmd/skywire-cli/commands/node/gen-config.go b/cmd/skywire-cli/commands/node/gen-config.go index 3dba6f016..b2f2a0e12 100644 --- a/cmd/skywire-cli/commands/node/gen-config.go +++ b/cmd/skywire-cli/commands/node/gen-config.go @@ -94,12 +94,12 @@ func defaultConfig() *visor.Config { ptyConf := defaultDmsgPtyConfig() conf.DmsgPty = &ptyConf - // TODO(evanlinjin): We have disabled skyproxy passcode by default for now - We should make a cli arg for this. + // TODO(evanlinjin): We have disabled skysocks passcode by default for now - We should make a cli arg for this. //passcode := base64.StdEncoding.Strict().EncodeToString(cipher.RandByte(8)) conf.Apps = []visor.AppConfig{ defaultSkychatConfig(), - defaultSkyproxyConfig(""), - defaultSkyproxyClientConfig(), + defaultSkysocksConfig(""), + defaultSkysocksClientConfig(), } conf.TrustedNodes = []cipher.PubKey{} @@ -162,25 +162,25 @@ func defaultSkychatConfig() visor.AppConfig { } } -func defaultSkyproxyConfig(passcode string) visor.AppConfig { +func defaultSkysocksConfig(passcode string) visor.AppConfig { var args []string if passcode != "" { args = []string{"-passcode", passcode} } return visor.AppConfig{ - App: skyenv.SkyproxyName, - Version: skyenv.SkyproxyVersion, + App: skyenv.SkysocksName, + Version: skyenv.SkysocksVersion, AutoStart: true, - Port: routing.Port(skyenv.SkyproxyPort), + Port: routing.Port(skyenv.SkysocksPort), Args: args, } } -func defaultSkyproxyClientConfig() visor.AppConfig { +func defaultSkysocksClientConfig() visor.AppConfig { return visor.AppConfig{ - App: skyenv.SkyproxyClientName, - Version: skyenv.SkyproxyClientVersion, + App: skyenv.SkysocksClientName, + Version: skyenv.SkysocksClientVersion, AutoStart: false, - Port: routing.Port(skyenv.SkyproxyClientPort), + Port: routing.Port(skyenv.SkysocksClientPort), } } diff --git a/internal/skyenv/const.go b/internal/skyenv/const.go index 25014054e..3cf2248fd 100644 --- a/internal/skyenv/const.go +++ b/internal/skyenv/const.go @@ -41,13 +41,13 @@ const ( SkychatPort = uint16(1) SkychatAddr = ":8000" - SkyproxyName = "socksproxy" - SkyproxyVersion = "1.0" - SkyproxyPort = uint16(3) - - SkyproxyClientName = "socksproxy-client" - SkyproxyClientVersion = "1.0" - SkyproxyClientPort = uint16(13) - SkyproxyClientAddr = ":1080" + SkysocksName = "socksproxy" + SkysocksVersion = "1.0" + SkysocksPort = uint16(3) + + SkysocksClientName = "socksproxy-client" + SkysocksClientVersion = "1.0" + SkysocksClientPort = uint16(13) + SkysocksClientAddr = ":1080" // TODO(evanlinjin): skyproxy-client requires ) From 3e434042bead8827c58c36dd0c4768745016ba40 Mon Sep 17 00:00:00 2001 From: kifen Date: Fri, 3 Jan 2020 08:49:13 +0100 Subject: [PATCH 26/33] remove therealproxy in README.md --- go.mod | 1 - 1 file changed, 1 deletion(-) diff --git a/go.mod b/go.mod index edcc2796b..ce72828ff 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,6 @@ require ( github.com/gorilla/handlers v1.4.2 github.com/gorilla/securecookie v1.1.1 github.com/hashicorp/yamux v0.0.0-20190923154419-df201c70410d - github.com/mitchellh/go-homedir v1.1.0 github.com/pkg/profile v1.3.0 github.com/prometheus/client_golang v1.2.1 github.com/prometheus/common v0.7.0 From 57318ba3ebb41acacf479e3df05eac0ea9d93dcd Mon Sep 17 00:00:00 2001 From: kifen Date: Sat, 4 Jan 2020 17:40:15 +0100 Subject: [PATCH 27/33] fix git conflict in README.md --- README.md | 7 +------ ci_scripts/run-internal-tests.sh | 2 +- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ede575c60..3f59f6071 100644 --- a/README.md +++ b/README.md @@ -185,12 +185,7 @@ After `skywire-visor` is up and running with default environment, default apps a - [Chat](/cmd/apps/skychat) - [Hello World](/cmd/apps/helloworld) -<<<<<<< HEAD -- [The Real Proxy](/cmd/apps/therealproxy) ([Client](/cmd/apps/therealproxy-client)) -======= -- [The Real Proxy](/cmd/apps/skysocks) ([Client](/cmd/apps/skysocks-client)) -- [The Real SSH](/cmd/apps/therealssh) ([Client](/cmd/apps/therealssh-client)) ->>>>>>> rename therealproxy to skysocks +- [Sky Socks](/cmd/apps/skysocks) ([Client](/cmd/apps/skysocks-client)) ### Transports diff --git a/ci_scripts/run-internal-tests.sh b/ci_scripts/run-internal-tests.sh index dff03bdae..9a61a8766 100755 --- a/ci_scripts/run-internal-tests.sh +++ b/ci_scripts/run-internal-tests.sh @@ -17,4 +17,4 @@ go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/noise -run TestReadWriterXKPattern >> ./logs/internal/TestReadWriterXKPattern.log go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/noise -run TestReadWriterConcurrentTCP >> ./logs/internal/TestReadWriterConcurrentTCP.log -go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/skysocks -run TestProxy >> ./logs/internal/TestProxy.log \ No newline at end of file +go clean -testcache &>/dev/null || go test -race -tags no_ci -cover -timeout=5m github.com/SkycoinProject/skywire-mainnet/internal/skysocks -run TestProxy >> ./logs/internal/TestProxy.log From f618455f6a5a68d2e3c04dfdf44132735fedac10 Mon Sep 17 00:00:00 2001 From: kifen Date: Sat, 4 Jan 2020 18:21:48 +0100 Subject: [PATCH 28/33] rename skyproxy to skysocks --- Makefile | 12 ++++++------ README.md | 16 ++++++++-------- cmd/apps/skysocks-client/README.md | 4 ++-- cmd/apps/skysocks-client/skysocks-client.go | 2 +- cmd/apps/skysocks/README.md | 10 +++++----- cmd/apps/skysocks/skysocks.go | 2 +- docker/images/node/Dockerfile | 4 ++-- integration/InteractiveEnvironments.md | 6 +++--- integration/generic/nodeA.json | 2 +- integration/generic/nodeC.json | 2 +- integration/proxy/nodeA.json | 2 +- integration/proxy/nodeC.json | 2 +- internal/skyenv/const.go | 6 +++--- 13 files changed, 35 insertions(+), 35 deletions(-) diff --git a/Makefile b/Makefile index 101e43a73..496b2c56f 100644 --- a/Makefile +++ b/Makefile @@ -86,8 +86,8 @@ dep: ## Sorts dependencies host-apps: ## Build app ${OPTS} go build ${BUILD_OPTS} -o ./apps/skychat.v1.0 ./cmd/apps/skychat ${OPTS} go build ${BUILD_OPTS} -o ./apps/helloworld.v1.0 ./cmd/apps/helloworld - ${OPTS} go build ${BUILD_OPTS} -o ./apps/socksproxy.v1.0 ./cmd/apps/skysocks - ${OPTS} go build ${BUILD_OPTS} -o ./apps/socksproxy-client.v1.0 ./cmd/apps/skysocks-client + ${OPTS} go build ${BUILD_OPTS} -o ./apps/skysocks.v1.0 ./cmd/apps/skysocks + ${OPTS} go build ${BUILD_OPTS} -o ./apps/skysocks-client.v1.0 ./cmd/apps/skysocks-client # Bin bin: ## Build `skywire-visor`, `skywire-cli`, `hypervisor` @@ -105,8 +105,8 @@ release: ## Build `skywire-visor`, `skywire-cli`, `hypervisor` and apps without ${OPTS} go build -o ./hypervisor ./cmd/hypervisor ${OPTS} go build -o ./apps/skychat.v1.0 ./cmd/apps/skychat ${OPTS} go build -o ./apps/helloworld.v1.0 ./cmd/apps/helloworld - ${OPTS} go build -o ./apps/socksproxy.v1.0 ./cmd/apps/skysocks - ${OPTS} go build -o ./apps/socksproxy-client.v1.0 ./cmd/apps/skysocks-client + ${OPTS} go build -o ./apps/skysocks.v1.0 ./cmd/apps/skysocks + ${OPTS} go build -o ./apps/skysocks-client.v1.0 ./cmd/apps/skysocks-client # Dockerized skywire-visor docker-image: ## Build docker image `skywire-runner` @@ -122,8 +122,8 @@ docker-network: ## Create docker network ${DOCKER_NETWORK} docker-apps: ## Build apps binaries for dockerized skywire-visor. `go build` with ${DOCKER_OPTS} -${DOCKER_OPTS} go build -race -o ./node/apps/skychat.v1.0 ./cmd/apps/skychat -${DOCKER_OPTS} go build -race -o ./node/apps/helloworld.v1.0 ./cmd/apps/helloworld - -${DOCKER_OPTS} go build -race -o ./node/apps/socksproxy.v1.0 ./cmd/apps/skysocks - -${DOCKER_OPTS} go build -race -o ./node/apps/socksproxy-client.v1.0 ./cmd/apps/skysocks-client + -${DOCKER_OPTS} go build -race -o ./node/apps/skysocks.v1.0 ./cmd/apps/skysocks + -${DOCKER_OPTS} go build -race -o ./node/apps/skysocks-client.v1.0 ./cmd/apps/skysocks-client docker-bin: ## Build `skywire-visor`, `skywire-cli`, `hypervisor`. `go build` with ${DOCKER_OPTS} ${DOCKER_OPTS} go build -race -o ./node/skywire-visor ./cmd/skywire-visor diff --git a/README.md b/README.md index 3f59f6071..beb7d1a8b 100644 --- a/README.md +++ b/README.md @@ -304,11 +304,11 @@ This will: ├── apps # node `apps` compiled with DOCKER_OPTS │   ├── skychat.v1.0 # │   ├── helloworld.v1.0 # -│   ├── socksproxy-client.v1.0 # -│   └── socksproxy.v1.0 # +│   ├── skysocks-client.v1.0 # +│   └── skysocks.v1.0 # ├── local # **Created inside docker** │   ├── skychat # according to "local_path" in skywire-config.json -│   └── socksproxy # +│   └── skysocks # ├── PK # contains public key of node ├── skywire # db & logs. **Created inside docker** │   ├── routing.db # @@ -408,7 +408,7 @@ $ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/skywire-visor ./cmd/skywire # 3. compile apps $ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/skychat.v1.0 ./cmd/apps/skychat $ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/helloworld.v1.0 ./cmd/apps/helloworld -$ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/socksproxy.v1.0 ./cmd/apps/skysocks +$ GO111MODULE=on GOOS=linux go build -o /tmp/SKYNODE/apps/skysocks.v1.0 ./cmd/apps/skysocks # 4. Create skywire-config.json for node $ skywire-cli node gen-config -o /tmp/SKYNODE/skywire-config.json # 2019/03/15 16:43:49 Done! @@ -417,7 +417,7 @@ $ tree /tmp/SKYNODE # ├── apps # │   ├── skychat.v1.0 # │   ├── helloworld.v1.0 -# │   └── socksproxy.v1.0 +# │   └── skysocks.v1.0 # ├── skywire-config.json # └── skywire-visor # So far so good. We prepared docker volume. Now we can: @@ -427,15 +427,15 @@ $ docker run -it -v /tmp/SKYNODE:/sky --network=SKYNET --name=SKYNODE skywire-ru # [2019-03-15T13:55:10Z] INFO [skywire]: Connected to messaging servers # [2019-03-15T13:55:10Z] INFO [skywire]: Starting skychat.v1.0 # [2019-03-15T13:55:10Z] INFO [skywire]: Starting RPC interface on 127.0.0.1:3435 -# [2019-03-15T13:55:10Z] INFO [skywire]: Starting socksproxy.v1.0 +# [2019-03-15T13:55:10Z] INFO [skywire]: Starting skysocks.v1.0 # [2019-03-15T13:55:10Z] INFO [skywire]: Starting packet router # [2019-03-15T13:55:10Z] INFO [router]: Starting router # [2019-03-15T13:55:10Z] INFO [trmanager]: Starting transport manager # [2019-03-15T13:55:10Z] INFO [router]: Got new App request with type Init: {"app-name":"skychat",# "app-version":"1.0","protocol-version":"0.0.1"} # [2019-03-15T13:55:10Z] INFO [router]: Handshaked new connection with the app skychat.v1.0 # [2019-03-15T13:55:10Z] INFO [skychat.v1.0]: 2019/03/15 13:55:10 Serving HTTP on :8000 -# [2019-03-15T13:55:10Z] INFO [router]: Got new App request with type Init: {"app-name":"socksproxy",# "app-version":"1.0","protocol-version":"0.0.1"} -# [2019-03-15T13:55:10Z] INFO [router]: Handshaked new connection with the app socksproxy.v1.0 +# [2019-03-15T13:55:10Z] INFO [router]: Got new App request with type Init: {"app-name":"skysocks",# "app-version":"1.0","protocol-version":"0.0.1"} +# [2019-03-15T13:55:10Z] INFO [router]: Handshaked new connection with the app skysocks.v1.0 ``` Note that in this example docker is running in non-detached mode - it could be useful in some scenarios. diff --git a/cmd/apps/skysocks-client/README.md b/cmd/apps/skysocks-client/README.md index 7d8d7d995..4beef86dc 100644 --- a/cmd/apps/skysocks-client/README.md +++ b/cmd/apps/skysocks-client/README.md @@ -1,6 +1,6 @@ # Skywire SOCKS5 proxy client app -`socksproxy-client` app implements client for the SOCKS5 app. +`skysocks-client` app implements client for the SOCKS5 app. It opens persistent `skywire` connection to the configured remote node and local TCP port, all incoming TCP traffics is forwarded to the @@ -8,4 +8,4 @@ and local TCP port, all incoming TCP traffics is forwarded to the Any conventional SOCKS5 client should be able to connect to the proxy client. -Please check docs for `socksproxy` app for further instructions. +Please check docs for `skysocks` app for further instructions. diff --git a/cmd/apps/skysocks-client/skysocks-client.go b/cmd/apps/skysocks-client/skysocks-client.go index 1d1dde9d8..3c841a01e 100644 --- a/cmd/apps/skysocks-client/skysocks-client.go +++ b/cmd/apps/skysocks-client/skysocks-client.go @@ -21,7 +21,7 @@ import ( ) const ( - appName = "socksproxy-client" + appName = "skysocks-client" netType = appnet.TypeSkynet socksPort = routing.Port(3) ) diff --git a/cmd/apps/skysocks/README.md b/cmd/apps/skysocks/README.md index 3e07a56b4..7e7432982 100644 --- a/cmd/apps/skysocks/README.md +++ b/cmd/apps/skysocks/README.md @@ -1,6 +1,6 @@ # Skywire SOCKS5 proxy app -`socksproxy` app implements SOCKS5 functionality over skywire +`skysocks` app implements SOCKS5 functionality over skywire net. Any conventional SOCKS5 client should be able to connect to the proxy client. @@ -18,7 +18,7 @@ Create 2 node config files: { "apps": [ { - "app": "socksproxy", + "app": "skysocks", "version": "1.0", "auto_start": true, "port": 3, @@ -34,7 +34,7 @@ Create 2 node config files: { "apps": [ { - "app": "socksproxy-client", + "app": "skysocks-client", "version": "1.0", "auto_start": true, "port": 33, @@ -47,8 +47,8 @@ Create 2 node config files: Compile binaries and start 2 nodes: ```sh -$ go build -o apps/socksproxy.v1.0 ./cmd/apps/skysocks -$ go build -o apps/socksproxy-client.v1.0 ./cmd/apps/skysocks-client +$ go build -o apps/skysocks.v1.0 ./cmd/apps/skysocks +$ go build -o apps/skysocks-client.v1.0 ./cmd/apps/skysocks-client $ ./skywire-visor skywire1.json $ ./skywire-visor skywire2.json ``` diff --git a/cmd/apps/skysocks/skysocks.go b/cmd/apps/skysocks/skysocks.go index 305c0d089..f36df3315 100644 --- a/cmd/apps/skysocks/skysocks.go +++ b/cmd/apps/skysocks/skysocks.go @@ -16,7 +16,7 @@ import ( ) const ( - appName = "socksproxy" + appName = "skysocks" netType = appnet.TypeSkynet port = routing.Port(3) ) diff --git a/docker/images/node/Dockerfile b/docker/images/node/Dockerfile index 0886aa548..0e426d476 100644 --- a/docker/images/node/Dockerfile +++ b/docker/images/node/Dockerfile @@ -18,8 +18,8 @@ RUN go build -mod=vendor -tags netgo -ldflags="-w -s" \ go build -mod=vendor -ldflags="-w -s" -o skywire-cli ./cmd/skywire-cli &&\ go build -mod=vendor -ldflags="-w -s" -o ./apps/skychat.v1.0 ./cmd/apps/skychat &&\ go build -mod=vendor -ldflags="-w -s" -o ./apps/helloworld.v1.0 ./cmd/apps/helloworld &&\ - go build -mod=vendor -ldflags="-w -s" -o ./apps/socksproxy.v1.0 ./cmd/apps/skysocks &&\ - go build -mod=vendor -ldflags="-w -s" -o ./apps/socksproxy-client.v1.0 ./cmd/apps/skysocks-client &&\ + go build -mod=vendor -ldflags="-w -s" -o ./apps/skysocks.v1.0 ./cmd/apps/skysocks &&\ + go build -mod=vendor -ldflags="-w -s" -o ./apps/skysocks-client.v1.0 ./cmd/apps/skysocks-client ## Resulting image diff --git a/integration/InteractiveEnvironments.md b/integration/InteractiveEnvironments.md index 978d8a69e..599cec113 100644 --- a/integration/InteractiveEnvironments.md +++ b/integration/InteractiveEnvironments.md @@ -169,9 +169,9 @@ The proxy test environment will define the following: It's really tricky to make socks5 proxy work now from clean start. -Because `socksproxy-client` needs: +Because `skysocks-client` needs: - transport to NodeA -- NodeA must be running **before** start of `socksproxy-client` +- NodeA must be running **before** start of `skysocks-client` Recipe for clean start: @@ -181,7 +181,7 @@ Recipe for clean start: 4. Stop NodeA, NodeB, NodeC 5. Restart all nodes 6. Wait for message in NodeC logs about successful start of -socksproxy-client +skysocks-client 7. Check `lsof -i :9999` that it's really started 8. Check `curl -v --retry 5 --retry-connrefused 1 --connect-timeout 5 -x socks5://123456:@localhost:9999 https://www.google.com` diff --git a/integration/generic/nodeA.json b/integration/generic/nodeA.json index eaa8f4ebd..4a4de930f 100644 --- a/integration/generic/nodeA.json +++ b/integration/generic/nodeA.json @@ -30,7 +30,7 @@ "args": [] }, { - "app": "socksproxy", + "app": "skysocks", "version": "1.0", "auto_start": true, "port": 3, diff --git a/integration/generic/nodeC.json b/integration/generic/nodeC.json index 35205b3db..0cde00086 100644 --- a/integration/generic/nodeC.json +++ b/integration/generic/nodeC.json @@ -33,7 +33,7 @@ ] }, { - "app": "socksproxy-client", + "app": "skysocks-client", "version": "1.0", "auto_start": true, "port": 13, diff --git a/integration/proxy/nodeA.json b/integration/proxy/nodeA.json index 17a0b03ae..05a4816b5 100644 --- a/integration/proxy/nodeA.json +++ b/integration/proxy/nodeA.json @@ -23,7 +23,7 @@ }, "apps": [ { - "app": "socksproxy", + "app": "skysocks", "version": "1.0", "auto_start": true, "port": 3, diff --git a/integration/proxy/nodeC.json b/integration/proxy/nodeC.json index 604606494..dc4e7b0d5 100644 --- a/integration/proxy/nodeC.json +++ b/integration/proxy/nodeC.json @@ -23,7 +23,7 @@ }, "apps": [ { - "app": "socksproxy-client", + "app": "skysocks-client", "version": "1.0", "auto_start": true, "port": 13, diff --git a/internal/skyenv/const.go b/internal/skyenv/const.go index 3cf2248fd..597a593ba 100644 --- a/internal/skyenv/const.go +++ b/internal/skyenv/const.go @@ -41,13 +41,13 @@ const ( SkychatPort = uint16(1) SkychatAddr = ":8000" - SkysocksName = "socksproxy" + SkysocksName = "skysocks" SkysocksVersion = "1.0" SkysocksPort = uint16(3) - SkysocksClientName = "socksproxy-client" + SkysocksClientName = "skysocks-client" SkysocksClientVersion = "1.0" SkysocksClientPort = uint16(13) SkysocksClientAddr = ":1080" - // TODO(evanlinjin): skyproxy-client requires + // TODO(evanlinjin): skysocks-client requires ) From a327b689c782bd93a235fc937c73715f80306556 Mon Sep 17 00:00:00 2001 From: kifen Date: Mon, 6 Jan 2020 18:22:29 +0100 Subject: [PATCH 29/33] fix make check --- internal/skysocks/server_test.go | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/internal/skysocks/server_test.go b/internal/skysocks/server_test.go index 123ed6f10..094f53377 100644 --- a/internal/skysocks/server_test.go +++ b/internal/skysocks/server_test.go @@ -11,7 +11,6 @@ import ( "time" "github.com/SkycoinProject/skycoin/src/util/logging" - "github.com/hashicorp/yamux" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/net/nettest" @@ -50,13 +49,9 @@ func TestProxy(t *testing.T) { conn, err := net.Dial("tcp", l.Addr().String()) require.NoError(t, err) - session, err := yamux.Client(conn, nil) + client, err := NewClient(conn) require.NoError(t, err) - client := &Client{ - session: session, - } - errChan2 := make(chan error) go func() { errChan2 <- client.ListenAndServe(":10080") From 4ebe1d3581c0d6e4d63331915e242ff4843ce8ae Mon Sep 17 00:00:00 2001 From: kifen Date: Tue, 7 Jan 2020 13:19:48 +0100 Subject: [PATCH 30/33] update transport deregistration logic --- pkg/transport-discovery/client/client.go | 30 ++++++++++++++++++++++++ pkg/transport/discovery.go | 17 ++++++++++++++ pkg/transport/manager.go | 14 +++++++++-- 3 files changed, 59 insertions(+), 2 deletions(-) diff --git a/pkg/transport-discovery/client/client.go b/pkg/transport-discovery/client/client.go index d29ec03d0..78c09b371 100644 --- a/pkg/transport-discovery/client/client.go +++ b/pkg/transport-discovery/client/client.go @@ -73,6 +73,16 @@ func (c *apiClient) Get(ctx context.Context, path string) (*http.Response, error return c.client.Do(req.WithContext(ctx)) } +// Delete performs a new DELETE request. +func (c *apiClient) Delete(ctx context.Context, path string) (*http.Response, error) { + req, err := http.NewRequest(http.MethodDelete, c.client.Addr()+path, new(bytes.Buffer)) + if err != nil { + return nil, err + } + + return c.client.Do(req.WithContext(ctx)) +} + // RegisterTransports registers new Transports. func (c *apiClient) RegisterTransports(ctx context.Context, entries ...*transport.SignedEntry) error { if len(entries) == 0 { @@ -150,6 +160,26 @@ func (c *apiClient) GetTransportsByEdge(ctx context.Context, pk cipher.PubKey) ( return entries, nil } +// DeleteTransport deletes given transport by it's ID. A visor can only delete transports if he is one of it's edges. +func (c *apiClient) DeleteTransport(ctx context.Context, id uuid.UUID) error { + resp, err := c.Delete(ctx, fmt.Sprintf("/transports/id:%s", id.String())) + if resp != nil { + defer func() { + if err := resp.Body.Close(); err != nil { + log.WithError(err).Warn("Failed to close HTTP response body") + } + }() + } + if err != nil { + return err + } + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("status: %d, error: %v", resp.StatusCode, extractError(resp.Body)) + } + + return nil +} + // UpdateStatuses updates statuses of transports in discovery. func (c *apiClient) UpdateStatuses(ctx context.Context, statuses ...*transport.Status) ([]*transport.EntryWithStatus, error) { if len(statuses) == 0 { diff --git a/pkg/transport/discovery.go b/pkg/transport/discovery.go index 2fdee01a2..3238c3f58 100644 --- a/pkg/transport/discovery.go +++ b/pkg/transport/discovery.go @@ -5,6 +5,7 @@ import ( "errors" "sync" "time" + "fmt" "github.com/SkycoinProject/dmsg/cipher" "github.com/google/uuid" @@ -15,6 +16,7 @@ type DiscoveryClient interface { RegisterTransports(ctx context.Context, entries ...*SignedEntry) error GetTransportByID(ctx context.Context, id uuid.UUID) (*EntryWithStatus, error) GetTransportsByEdge(ctx context.Context, pk cipher.PubKey) ([]*EntryWithStatus, error) + DeleteTransport(ctx context.Context, id uuid.UUID) error UpdateStatuses(ctx context.Context, statuses ...*Status) ([]*EntryWithStatus, error) } @@ -81,6 +83,21 @@ func (td *mockDiscoveryClient) GetTransportsByEdge(ctx context.Context, pk ciphe return res, nil } +// NOTE that mock implementation doesn't checks whether the transport to be deleted is valid or not, this is, that +// it can be deleted by the visor who called DeleteTransport +func (td *mockDiscoveryClient) DeleteTransport(ctx context.Context, id uuid.UUID) error { + td.Lock() + defer td.Unlock() + + _, ok := td.entries[id] + if !ok { + return fmt.Errorf("transport with id: %s not found in transport discovery", id) + } + + delete(td.entries, id) + return nil +} + func (td *mockDiscoveryClient) UpdateStatuses(ctx context.Context, statuses ...*Status) ([]*EntryWithStatus, error) { res := make([]*EntryWithStatus, 0) diff --git a/pkg/transport/manager.go b/pkg/transport/manager.go index 0aedab6a1..e463803ef 100644 --- a/pkg/transport/manager.go +++ b/pkg/transport/manager.go @@ -6,6 +6,7 @@ import ( "io" "strings" "sync" + "time" "github.com/SkycoinProject/skywire-mainnet/internal/skyenv" "github.com/SkycoinProject/skywire-mainnet/pkg/snet/snettest" @@ -224,7 +225,7 @@ func (tm *Manager) saveTransport(remote cipher.PubKey, netName string) (*Managed return mTp, nil } -// DeleteTransport disconnects and removes the Transport of Transport ID. +// DeleteTransport deregisters the Transport of Transport ID in transport discovery and deletes it locally. func (tm *Manager) DeleteTransport(id uuid.UUID) { tm.mx.Lock() defer tm.mx.Unlock() @@ -234,8 +235,17 @@ func (tm *Manager) DeleteTransport(id uuid.UUID) { if tp, ok := tm.tps[id]; ok { tp.Close() + tm.Logger.Infof("Deregister transport %s from manager", id) + + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + err := tm.Conf.DiscoveryClient.DeleteTransport(ctx, id) + if err != nil { + tm.Logger.Errorf("Deregister transport %s from discovery failed with error: %s", id, err) + } + tm.Logger.Infof("Deregister transport %s from discovery", id) + delete(tm.tps, id) - tm.Logger.Infof("Unregistered transport %s", id) } } From fab446c1d93444c1dd5ac4d52ee35e92fc82f697 Mon Sep 17 00:00:00 2001 From: kifen Date: Tue, 7 Jan 2020 15:41:34 +0100 Subject: [PATCH 31/33] update manager_test.go --- pkg/transport/manager_test.go | 55 +++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 16 deletions(-) diff --git a/pkg/transport/manager_test.go b/pkg/transport/manager_test.go index 8ed8a4859..1a2ed69f6 100644 --- a/pkg/transport/manager_test.go +++ b/pkg/transport/manager_test.go @@ -45,12 +45,38 @@ func TestNewManager(t *testing.T) { nEnv := snettest.NewEnv(t, keys, []string{dmsg.Type}) defer nEnv.Teardown() - m0, m1, tp0, tp1, err := transport.CreateTransportPair(tpDisc, keys, nEnv, "dmsg") + // Prepare tp manager 0. + pk0, sk0 := keys[0].PK, keys[0].SK + ls0 := transport.InMemoryTransportLogStore() + m0, err := transport.NewManager(nEnv.Nets[0], &transport.ManagerConfig{ + PubKey: pk0, + SecKey: sk0, + DiscoveryClient: tpDisc, + LogStore: ls0, + }) + require.NoError(t, err) + go m0.Serve(context.TODO()) defer func() { require.NoError(t, m0.Close()) }() - defer func() { require.NoError(t, m1.Close()) }() + // Prepare tp manager 1. + pk1, sk1 := keys[1].PK, keys[1].SK + ls1 := transport.InMemoryTransportLogStore() + m2, err := transport.NewManager(nEnv.Nets[1], &transport.ManagerConfig{ + PubKey: pk1, + SecKey: sk1, + DiscoveryClient: tpDisc, + LogStore: ls1, + }) require.NoError(t, err) - require.NotNil(t, tp0) + go m2.Serve(context.TODO()) + defer func() { require.NoError(t, m2.Close()) }() + + // Create data transport between manager 1 & manager 2. + tp2, err := m2.SaveTransport(context.TODO(), pk0, "dmsg") + require.NoError(t, err) + tp1 := m0.Transport(transport.MakeTransportID(pk0, pk1, "dmsg")) + require.NotNil(t, tp1) + fmt.Println("transports created") totalSent2 := 0 @@ -63,8 +89,7 @@ func TestNewManager(t *testing.T) { totalSent2 += i rID := routing.RouteID(i) payload := cipher.RandByte(i) - packet := routing.MakeDataPacket(rID, payload) - require.NoError(t, tp1.WritePacket(context.TODO(), packet)) + require.NoError(t, tp2.WritePacket(context.TODO(), routing.MakeDataPacket(rID, payload))) recv, err := m0.ReadPacket() require.NoError(t, err) @@ -77,10 +102,9 @@ func TestNewManager(t *testing.T) { totalSent1 += i rID := routing.RouteID(i) payload := cipher.RandByte(i) - packet := routing.MakeDataPacket(rID, payload) - require.NoError(t, tp0.WritePacket(context.TODO(), packet)) + require.NoError(t, tp1.WritePacket(context.TODO(), routing.MakeDataPacket(rID, payload))) - recv, err := m1.ReadPacket() + recv, err := m2.ReadPacket() require.NoError(t, err) require.Equal(t, rID, recv.RouteID()) require.Equal(t, uint16(i), recv.Size()) @@ -94,12 +118,12 @@ func TestNewManager(t *testing.T) { // 1.5x log write interval just to be safe. time.Sleep(time.Second * 9 / 2) - entry1, err := m0.Conf.LogStore.Entry(tp0.Entry.ID) + entry1, err := ls0.Entry(tp1.Entry.ID) require.NoError(t, err) assert.Equal(t, uint64(totalSent1), entry1.SentBytes) assert.Equal(t, uint64(totalSent2), entry1.RecvBytes) - entry2, err := m1.Conf.LogStore.Entry(tp1.Entry.ID) + entry2, err := ls1.Entry(tp2.Entry.ID) require.NoError(t, err) assert.Equal(t, uint64(totalSent2), entry2.SentBytes) assert.Equal(t, uint64(totalSent1), entry2.RecvBytes) @@ -109,18 +133,17 @@ func TestNewManager(t *testing.T) { t.Run("check_delete_tp", func(t *testing.T) { // Make transport ID. - tpID := transport.MakeTransportID(m0.Conf.PubKey, m1.Conf.PubKey, "dmsg") + tpID := transport.MakeTransportID(pk0, pk1, "dmsg") // Ensure transports are registered properly in tp discovery. entry, err := tpDisc.GetTransportByID(context.TODO(), tpID) require.NoError(t, err) - assert.Equal(t, transport.SortEdges(m0.Conf.PubKey, m1.Conf.PubKey), entry.Entry.Edges) + assert.Equal(t, transport.SortEdges(pk0, pk1), entry.Entry.Edges) assert.True(t, entry.IsUp) - m1.DeleteTransport(tp1.Entry.ID) - entry, err = tpDisc.GetTransportByID(context.TODO(), tpID) - require.NoError(t, err) - assert.False(t, entry.IsUp) + m2.DeleteTransport(tp2.Entry.ID) + _, err = tpDisc.GetTransportByID(context.TODO(), tpID) + require.Contains(t, err.Error(), "not found") }) } From a0efeda82948d93ba2b8f6ea486877b2963bbc9c Mon Sep 17 00:00:00 2001 From: kifen Date: Tue, 7 Jan 2020 16:52:41 +0100 Subject: [PATCH 32/33] enable STCP by default --- cmd/skywire-cli/commands/node/gen-config.go | 25 +++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/cmd/skywire-cli/commands/node/gen-config.go b/cmd/skywire-cli/commands/node/gen-config.go index b2f2a0e12..e24dbb0d4 100644 --- a/cmd/skywire-cli/commands/node/gen-config.go +++ b/cmd/skywire-cli/commands/node/gen-config.go @@ -1,7 +1,9 @@ package node import ( + "errors" "fmt" + "net" "path/filepath" "time" @@ -84,6 +86,13 @@ func defaultConfig() *visor.Config { conf.Node.StaticPubKey = pk conf.Node.StaticSecKey = sk + lIPaddr, err := getLocalIPAddress() + if err != nil { + log.Warn(err) + } + + conf.STCP.LocalAddr = lIPaddr + if testenv { conf.Messaging.Discovery = skyenv.TestDmsgDiscAddr } else { @@ -184,3 +193,19 @@ func defaultSkysocksClientConfig() visor.AppConfig { Port: routing.Port(skyenv.SkysocksClientPort), } } + +func getLocalIPAddress() (string, error) { + addrs, err := net.InterfaceAddrs() + if err != nil { + return "", err + } + + for _, a := range addrs { + if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { + if ipnet.IP.To4() != nil { + return ipnet.IP.String() + ":7777", nil + } + } + } + return "", errors.New("could not find local IP address") +} From da69b820b4386387ac8b7e782d00259d0b08bb22 Mon Sep 17 00:00:00 2001 From: kifen Date: Wed, 8 Jan 2020 10:28:33 +0100 Subject: [PATCH 33/33] lint discovery.go --- pkg/transport/discovery.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/transport/discovery.go b/pkg/transport/discovery.go index 3238c3f58..5fbcafa25 100644 --- a/pkg/transport/discovery.go +++ b/pkg/transport/discovery.go @@ -3,9 +3,9 @@ package transport import ( "context" "errors" + "fmt" "sync" "time" - "fmt" "github.com/SkycoinProject/dmsg/cipher" "github.com/google/uuid"