diff --git a/Makefile b/Makefile index 2a1764b94..496b2c56f 100644 --- a/Makefile +++ b/Makefile @@ -31,10 +31,10 @@ 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` - ${OPTS} go install ./cmd/skywire-visor ./cmd/skywire-cli ./cmd/setup-node ./cmd/hypervisor ./cmd/therealssh-cli ./cmd/dmsgpty +install: ## Install `skywire-visor`, `skywire-cli`, `hypervisor`, `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 @@ -89,33 +86,27 @@ 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/SSH.v1.0 ./cmd/apps/therealssh - ${OPTS} go build ${BUILD_OPTS} -o ./apps/SSH-client.v1.0 ./cmd/apps/therealssh-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`, `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 + ${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` @@ -131,12 +122,10 @@ 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/SSH.v1.0 ./cmd/apps/therealssh - -${DOCKER_OPTS} go build -race -o ./node/apps/SSH-client.v1.0 ./cmd/apps/therealssh-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`, `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 diff --git a/README.md b/README.md index 5ea3e12a8..beb7d1a8b 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. @@ -185,8 +185,7 @@ 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)) +- [Sky Socks](/cmd/apps/skysocks) ([Client](/cmd/apps/skysocks-client)) ### Transports @@ -305,14 +304,11 @@ This will: ├── apps # node `apps` compiled with DOCKER_OPTS │   ├── skychat.v1.0 # │   ├── helloworld.v1.0 # -│   ├── socksproxy-client.v1.0 # -│   ├── socksproxy.v1.0 # -│   ├── SSH-client.v1.0 # -│   └── SSH.v1.0 # +│   ├── skysocks-client.v1.0 # +│   └── skysocks.v1.0 # ├── local # **Created inside docker** │   ├── skychat # according to "local_path" in skywire-config.json -│   ├── socksproxy # -│   └── SSH # +│   └── skysocks # ├── PK # contains public key of node ├── skywire # db & logs. **Created inside docker** │   ├── routing.db # @@ -412,9 +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/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 +$ 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! @@ -423,9 +417,7 @@ $ tree /tmp/SKYNODE # ├── apps # │   ├── skychat.v1.0 # │   ├── helloworld.v1.0 -# │   ├── socksproxy.v1.0 -# │   ├── SSH-client.v1.0 -# │   └── SSH.v1.0 +# │   └── skysocks.v1.0 # ├── skywire-config.json # └── skywire-visor # So far so good. We prepared docker volume. Now we can: @@ -435,18 +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 SSH.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":"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 +# [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/ci_scripts/run-internal-tests.sh b/ci_scripts/run-internal-tests.sh index 57be9caf4..9a61a8766 100755 --- a/ci_scripts/run-internal-tests.sh +++ b/ci_scripts/run-internal-tests.sh @@ -17,18 +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/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 +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 diff --git a/cmd/apps/therealproxy-client/README.md b/cmd/apps/skysocks-client/README.md similarity index 68% rename from cmd/apps/therealproxy-client/README.md rename to cmd/apps/skysocks-client/README.md index 7d8d7d995..4beef86dc 100644 --- a/cmd/apps/therealproxy-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/therealproxy-client/therealproxy-client.go b/cmd/apps/skysocks-client/skysocks-client.go similarity index 87% rename from cmd/apps/therealproxy-client/therealproxy-client.go rename to cmd/apps/skysocks-client/skysocks-client.go index bd38b49cc..3c841a01e 100644 --- a/cmd/apps/therealproxy-client/therealproxy-client.go +++ b/cmd/apps/skysocks-client/skysocks-client.go @@ -14,14 +14,14 @@ 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" ) const ( - appName = "socksproxy-client" + appName = "skysocks-client" netType = appnet.TypeSkynet socksPort = routing.Port(3) ) @@ -30,9 +30,9 @@ 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 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() @@ -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 79% rename from cmd/apps/therealproxy/README.md rename to cmd/apps/skysocks/README.md index 360b4e187..7e7432982 100644 --- a/cmd/apps/therealproxy/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/therealproxy -$ go build -o apps/socksproxy-client.v1.0 ./cmd/apps/therealproxy-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/therealproxy/therealproxy.go b/cmd/apps/skysocks/skysocks.go similarity index 85% rename from cmd/apps/therealproxy/therealproxy.go rename to cmd/apps/skysocks/skysocks.go index 3ab67e093..f36df3315 100644 --- a/cmd/apps/therealproxy/therealproxy.go +++ b/cmd/apps/skysocks/skysocks.go @@ -9,21 +9,21 @@ 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" ) const ( - appName = "socksproxy" + appName = "skysocks" netType = appnet.TypeSkynet port = routing.Port(3) ) 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/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-cli/commands/node/gen-config.go b/cmd/skywire-cli/commands/node/gen-config.go index 8cc27ab4a..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 { @@ -94,14 +103,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(), - defaultSkysshConfig(), - defaultSkyproxyConfig(""), - defaultSkysshClientConfig(), - defaultSkyproxyClientConfig(), + defaultSkysocksConfig(""), + defaultSkysocksClientConfig(), } conf.TrustedNodes = []cipher.PubKey{} @@ -140,7 +147,7 @@ func defaultConfig() *visor.Config { conf.Interfaces.RPCAddress = "localhost:3435" - conf.AppServerSockFile = "app_server.sock" + conf.AppServerSockFile = "/tmp/visor_" + pk.Hex() + ".sock" return conf } @@ -164,43 +171,41 @@ 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 { +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 defaultSkysshClientConfig() visor.AppConfig { +func defaultSkysocksClientConfig() visor.AppConfig { return visor.AppConfig{ - App: skyenv.SkysshClientName, - Version: skyenv.SkysshVersion, - AutoStart: true, - Port: routing.Port(skyenv.SkysshClientPort), + App: skyenv.SkysocksClientName, + Version: skyenv.SkysocksClientVersion, + AutoStart: false, + Port: routing.Port(skyenv.SkysocksClientPort), } } -func defaultSkyproxyClientConfig() visor.AppConfig { - return visor.AppConfig{ - App: skyenv.SkyproxyClientName, - Version: skyenv.SkyproxyClientVersion, - AutoStart: false, - Port: routing.Port(skyenv.SkyproxyClientPort), +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") } diff --git a/cmd/skywire-visor/commands/root.go b/cmd/skywire-visor/commands/root.go index 1b49da606..ed47be729 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" ) @@ -39,6 +40,7 @@ type runCfg struct { cfgFromStdin bool profileMode string port string + startDelay string args []string profileStop func() @@ -46,6 +48,7 @@ type runCfg struct { masterLogger *logging.MasterLogger conf visor.Config node *visor.Node + restartCtx *restart.Context } var cfg *runCfg @@ -73,6 +76,9 @@ 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") + + cfg.restartCtx = restart.CaptureContext() } // Execute executes root CLI command. @@ -148,7 +154,19 @@ func (cfg *runCfg) readConfig() *runCfg { } func (cfg *runCfg) runNode() *runCfg { - node, err := visor.NewNode(&cfg.conf, cfg.masterLogger) + 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) } @@ -181,7 +199,9 @@ func (cfg *runCfg) runNode() *runCfg { if cfg.conf.ShutdownTimeout == 0 { cfg.conf.ShutdownTimeout = defaultShutdownTimeout } + cfg.node = node + return cfg } 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..0e426d476 100644 --- a/docker/images/node/Dockerfile +++ b/docker/images/node/Dockerfile @@ -18,11 +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/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/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 FROM ${base} as node-runner diff --git a/go.mod b/go.mod index eff170c4f..ce72828ff 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 @@ -12,11 +12,12 @@ 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/hashicorp/yamux v0.0.0-20190923154419-df201c70410d github.com/pkg/profile v1.3.0 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 @@ -24,4 +25,4 @@ require ( golang.org/x/net v0.0.0-20191204025024-5ee1b9f4859a ) -replace github.com/SkycoinProject/dmsg => ../dmsg +//replace github.com/SkycoinProject/dmsg => ../dmsg diff --git a/go.sum b/go.sum index afc2caf24..c3cf11d7b 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= @@ -54,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/integration/InteractiveEnvironments.md b/integration/InteractiveEnvironments.md index b7caa920e..599cec113 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,64 +155,23 @@ 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 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: @@ -229,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` @@ -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..4a4de930f 100644 --- a/integration/generic/nodeA.json +++ b/integration/generic/nodeA.json @@ -30,14 +30,7 @@ "args": [] }, { - "app": "SSH", - "version": "1.0", - "auto_start": true, - "port": 2, - "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 38d08b5d4..0cde00086 100644 --- a/integration/generic/nodeC.json +++ b/integration/generic/nodeC.json @@ -33,14 +33,7 @@ ] }, { - "app": "SSH-client", - "version": "1.0", - "auto_start": true, - "port": 12, - "args": [] - }, - { - "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/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 40593c086..597a593ba 100644 --- a/internal/skyenv/const.go +++ b/internal/skyenv/const.go @@ -41,22 +41,13 @@ const ( SkychatPort = uint16(1) SkychatAddr = ":8000" - SkysshName = "SSH" - SkysshVersion = "1.0" - SkysshPort = uint16(2) - - SkyproxyName = "socksproxy" - SkyproxyVersion = "1.0" - SkyproxyPort = uint16(3) - - SkysshClientName = "SSH-client" - SkysshClientVersion = "1.0" - SkysshClientPort = uint16(12) - SkysshClientAddr = ":2222" - - SkyproxyClientName = "socksproxy-client" - SkyproxyClientVersion = "1.0" - SkyproxyClientPort = uint16(13) - SkyproxyClientAddr = ":1080" - // TODO(evanlinjin): skyproxy-client requires + SkysocksName = "skysocks" + SkysocksVersion = "1.0" + SkysocksPort = uint16(3) + + SkysocksClientName = "skysocks-client" + SkysocksClientVersion = "1.0" + SkysocksClientPort = uint16(13) + SkysocksClientAddr = ":1080" + // TODO(evanlinjin): skysocks-client requires ) 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 98% rename from internal/therealproxy/server_test.go rename to internal/skysocks/server_test.go index 9ba3dc114..094f53377 100644 --- a/internal/therealproxy/server_test.go +++ b/internal/skysocks/server_test.go @@ -1,4 +1,4 @@ -package therealproxy +package skysocks import ( "fmt" 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/hypervisor/hypervisor.go b/pkg/hypervisor/hypervisor.go index c8134db15..30863609b 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..0c485ebb8 --- /dev/null +++ b/pkg/restart/restart.go @@ -0,0 +1,155 @@ +package restart + +import ( + "errors" + "log" + "os" + "os/exec" + "sync/atomic" + "time" + + "github.com/sirupsen/logrus" +) + +var ( + // ErrAlreadyStarting is returned on starting attempt when starting is in progress. + ErrAlreadyStarting = errors.New("already starting") +) + +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 + cmd *exec.Cmd + checkDelay time.Duration + isStarting int32 + appendDelay bool // disabled in tests +} + +// 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 { + cmd := exec.Command(os.Args[0], os.Args[1:]...) // nolint:gosec + + cmd.Stdout = os.Stdout + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr + cmd.Env = os.Environ() + + return &Context{ + cmd: cmd, + checkDelay: DefaultCheckDelay, + appendDelay: true, + } +} + +// RegisterLogger registers a logger instead of standard one. +func (c *Context) RegisterLogger(logger logrus.FieldLogger) { + if c != nil { + c.log = logger + } +} + +// SetCheckDelay sets a check delay instead of standard one. +func (c *Context) SetCheckDelay(delay time.Duration) { + if c != nil { + c.checkDelay = delay + } +} + +// Start starts a new executable using Context. +func (c *Context) Start() error { + if !atomic.CompareAndSwapInt32(&c.isStarting, 0, 1) { + return ErrAlreadyStarting + } + + defer atomic.StoreInt32(&c.isStarting, 0) + + errCh := c.startExec() + + 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 from the old one") + return nil + } +} + +func (c *Context) startExec() chan error { + errCh := make(chan error, 1) + + go func() { + defer close(errCh) + + c.adjustArgs() + + c.infoLogger()("Starting new instance of executable (args: %q)", c.cmd.Args) + + if err := c.cmd.Start(); err != nil { + errCh <- err + return + } + + if err := c.cmd.Wait(); err != nil { + errCh <- err + return + } + }() + + return errCh +} + +func (c *Context) adjustArgs() { + args := c.cmd.Args + + i := 0 + l := len(args) + + for i < l { + if args[i] == delayArgName && i < len(args)-1 { + args = append(args[:i], args[i+2:]...) + l -= 2 + } else { + i++ + } + } + + if c.appendDelay { + delay := c.checkDelay + extraWaitingTime + args = append(args, delayArgName, delay.String()) + } + + c.cmd.Args = args +} + +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/restart/restart_test.go b/pkg/restart/restart_test.go new file mode 100644 index 000000000..c29defd5f --- /dev/null +++ b/pkg/restart/restart_test.go @@ -0,0 +1,92 @@ +package restart + +import ( + "os" + "os/exec" + "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 := CaptureContext() + + require.Equal(t, DefaultCheckDelay, cc.checkDelay) + 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 := CaptureContext() + require.Nil(t, cc.log) + + logger := logging.MustGetLogger("test") + cc.RegisterLogger(logger) + require.Equal(t, logger, cc.log) +} + +func TestContext_Start(t *testing.T) { + cc := CaptureContext() + assert.NotZero(t, len(cc.cmd.Args)) + + t.Run("executable started", func(t *testing.T) { + cmd := "touch" + path := "/tmp/test_start" + cc.cmd = exec.Command(cmd, path) // nolint:gosec + cc.appendDelay = false + + assert.NoError(t, cc.Start()) + assert.NoError(t, os.Remove(path)) + }) + + t.Run("bad args", func(t *testing.T) { + cmd := "bad_command" + cc.cmd = exec.Command(cmd) // nolint:gosec + + // 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 starting", func(t *testing.T) { + cmd := "touch" + path := "/tmp/test_start" + cc.cmd = exec.Command(cmd, path) // nolint:gosec + cc.appendDelay = false + + errCh := make(chan error, 1) + go func() { + errCh <- cc.Start() + }() + + 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)) + }) +} + +func TestContext_SetCheckDelay(t *testing.T) { + cc := CaptureContext() + require.Equal(t, DefaultCheckDelay, cc.checkDelay) + + const oneSecond = 1 * time.Second + + cc.SetCheckDelay(oneSecond) + require.Equal(t, oneSecond, cc.checkDelay) +} 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/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..5fbcafa25 100644 --- a/pkg/transport/discovery.go +++ b/pkg/transport/discovery.go @@ -3,6 +3,7 @@ package transport import ( "context" "errors" + "fmt" "sync" "time" @@ -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) } } 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") }) } diff --git a/pkg/visor/config.go b/pkg/visor/config.go index 69e54d808..554c6e322 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. @@ -132,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/rpc.go b/pkg/visor/rpc.go index 4b77005df..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" @@ -29,6 +30,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 +394,27 @@ func (r *RPC) Loops(_ *struct{}, out *[]LoopInfo) error { *out = loops return nil } + +/* + <<< VISOR MANAGEMENT >>> +*/ + +const exitDelay = 100 * time.Millisecond + +// Restart restarts visor. +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.Start() +} diff --git a/pkg/visor/rpc_client.go b/pkg/visor/rpc_client.go index 219734fcd..92882bacb 100644 --- a/pkg/visor/rpc_client.go +++ b/pkg/visor/rpc_client.go @@ -9,15 +9,14 @@ import ( "sync" "time" - "github.com/SkycoinProject/skywire-mainnet/pkg/app" - "github.com/SkycoinProject/skywire-mainnet/pkg/router" - "github.com/SkycoinProject/skywire-mainnet/pkg/snet/snettest" - "github.com/SkycoinProject/dmsg/cipher" "github.com/SkycoinProject/skycoin/src/util/logging" "github.com/google/uuid" + "github.com/SkycoinProject/skywire-mainnet/pkg/app" + "github.com/SkycoinProject/skywire-mainnet/pkg/router" "github.com/SkycoinProject/skywire-mainnet/pkg/routing" + "github.com/SkycoinProject/skywire-mainnet/pkg/snet/snettest" "github.com/SkycoinProject/skywire-mainnet/pkg/transport" ) @@ -50,6 +49,8 @@ type RPCClient interface { RemoveRoutingRule(key routing.RouteID) error Loops() ([]LoopInfo, error) + + Restart() error } // RPCClient provides methods to call an RPC Server. @@ -222,6 +223,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 @@ -544,3 +550,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/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.go b/pkg/visor/visor.go index b51438fc5..114c26c92 100644 --- a/pkg/visor/visor.go +++ b/pkg/visor/visor.go @@ -26,6 +26,7 @@ import ( "github.com/SkycoinProject/skywire-mainnet/pkg/app/appnet" "github.com/SkycoinProject/skywire-mainnet/pkg/app/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" @@ -55,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 { @@ -80,9 +81,10 @@ type Node struct { appsPath string localPath string - appsConf []AppConfig + appsConf map[string]AppConfig - startedAt time.Time + startedAt time.Time + restartCtx *restart.Context pidMu sync.Mutex @@ -93,7 +95,7 @@ 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{ @@ -104,6 +106,15 @@ func NewNode(config *Config, masterLogger *logging.MasterLogger) (*Node, error) 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 @@ -476,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/pkg/visor/visor_test.go b/pkg/visor/visor_test.go index 9dc786aec..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, } @@ -248,9 +256,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{ 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/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/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 ce09179bc..831e5b965 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-20191107094546-85c27858fca6 github.com/SkycoinProject/dmsg github.com/SkycoinProject/dmsg/cipher github.com/SkycoinProject/dmsg/disc @@ -38,9 +38,11 @@ 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.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 @@ -50,8 +52,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