├── Makefile ├── .gitignore ├── examples ├── throughput │ ├── README.md │ └── main.go └── http │ ├── README.md │ └── main.go ├── conn.go ├── util_test.go ├── .github └── workflows │ └── go.yml ├── tests ├── config.go ├── config.reverse.entry.json ├── cachepubaddr_test.go ├── pub.go ├── session_test.go ├── udp_test.go └── tcp_test.go ├── pb ├── session.proto └── session.pb.go ├── node.go ├── util.go ├── go.mod ├── config.go ├── udp.go ├── message.go ├── README.md ├── go.sum ├── LICENSE ├── udpsession.go └── client.go /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: pb 2 | pb: 3 | protoc --go_out=. pb/*.proto 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | vendor 3 | *~ 4 | .DS_Store 5 | Session.framework 6 | session.aar 7 | session.jar 8 | -------------------------------------------------------------------------------- /examples/throughput/README.md: -------------------------------------------------------------------------------- 1 | Send a fixed amount of data from dialer to listener. 2 | 3 | Basic usage: 4 | 5 | ```shell 6 | go run examples/throughput/main.go -l -d -n 4 -m 16 7 | ``` 8 | 9 | Use `--help` to see more options. 10 | -------------------------------------------------------------------------------- /conn.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "net" 5 | "sync" 6 | ) 7 | 8 | type Conn struct { 9 | net.Conn 10 | ReadLock sync.Mutex 11 | WriteLock sync.Mutex 12 | } 13 | 14 | func newConn(conn net.Conn) *Conn { 15 | return &Conn{Conn: conn} 16 | } 17 | -------------------------------------------------------------------------------- /util_test.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import "testing" 4 | 5 | // go test -v -run=TestGetFreePort 6 | func TestGetFreePort(t *testing.T) { 7 | port, err := GetFreePort(0) 8 | if err != nil { 9 | t.Error(err) 10 | } 11 | t.Log(port) 12 | } 13 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | [ push, pull_request ] 5 | 6 | jobs: 7 | 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | 13 | - name: Set up Go 14 | uses: actions/setup-go@v3 15 | with: 16 | go-version: 1.20.2 17 | 18 | - name: Build 19 | run: go build -v ./... 20 | 21 | - name: Test 22 | run: go test -v ./tests/session_test.go 23 | -------------------------------------------------------------------------------- /tests/config.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import "time" 4 | 5 | const ( 6 | bytesToSend = 10 << 10 7 | numTcpListener = 2 8 | numUdpListener = 1 9 | numUdpDialers = 4 10 | bufSize = 100 11 | writeInterval = 2 * time.Millisecond 12 | 13 | listenerId = "Bob" 14 | dialerId = "Alice" 15 | seedHex = "e68e046d13dd911594576ba0f4a196e9666790dc492071ad9ea5972c0b940435" 16 | remoteAddr = "Bob.be285ff9330122cea44487a9618f96603fde6d37d5909ae1c271616772c349fe" 17 | ) 18 | -------------------------------------------------------------------------------- /pb/session.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option go_package = "./pb"; 4 | 5 | package pb; 6 | 7 | message SessionMetadata { 8 | bytes id = 1; 9 | SessionType sessionType = 2; 10 | string dialerNknAddr = 3; 11 | } 12 | 13 | message SessionData { 14 | MsgType msgType = 1; 15 | bytes data = 3; 16 | } 17 | 18 | enum SessionType { 19 | ST_NONE = 0; 20 | TCP = 1; 21 | UDP = 2; 22 | } 23 | 24 | enum HeaderType { 25 | HT_NONE = 0; 26 | SESSION = 1; 27 | USER = 2; 28 | } 29 | 30 | enum MsgType { 31 | MT_NONE = 0; 32 | REMOTEADDR = 1; 33 | SESSIONID = 2; 34 | CLOSE = 255; 35 | } 36 | -------------------------------------------------------------------------------- /examples/http/README.md: -------------------------------------------------------------------------------- 1 | Host the files in a directory at listener side and make it accessible on dialer 2 | side. 3 | 4 | Basic usage: 5 | 6 | On listener side: 7 | 8 | ```shell 9 | go run examples/http/main.go -l -n 4 -dir . 10 | ``` 11 | 12 | and you will see the listening address at console output: 13 | 14 | ``` 15 | Serving content at 16 | ``` 17 | 18 | Then on dialer side: 19 | 20 | ```shell 21 | go run examples/http/main.go -d -a -http :8080 22 | ``` 23 | 24 | Now you can visit `http://127.0.0.1:8080` to see the content of serving 25 | directory. 26 | 27 | Use `--help` to see more options. 28 | -------------------------------------------------------------------------------- /tests/config.reverse.entry.json: -------------------------------------------------------------------------------- 1 | { 2 | "services": { 3 | "test": { 4 | "maxPrice": "0.001", 5 | "ipFilter": { 6 | "allow": [ 7 | {"countryCode": ""} 8 | ], 9 | "disallow": [ 10 | {"countryCode": ""} 11 | ] 12 | } 13 | } 14 | }, 15 | "downloadGeoDB": false, 16 | "geoDBPath": ".", 17 | "dialTimeout": 10, 18 | "udpTimeout": 0, 19 | "nanoPayFee": "", 20 | "minNanoPayFee": "0.00001", 21 | "nanoPayFeeRatio": 0.1, 22 | "reverse": true, 23 | "reverseBeneficiaryAddr": "", 24 | "reverseTCP": 30020, 25 | "reverseUDP": 30021, 26 | "reversePrice": "0.0", 27 | "reverseClaimInterval": 3600, 28 | "reverseSubscriptionDuration": 40000, 29 | "reverseSubscriptionFee": "0.0" 30 | } 31 | -------------------------------------------------------------------------------- /node.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "math" 5 | "math/rand" 6 | "sort" 7 | "time" 8 | 9 | "github.com/nknorg/tuna/types" 10 | ) 11 | 12 | func init() { 13 | rand.Seed(time.Now().UnixNano()) 14 | } 15 | 16 | type sortByWeight types.Nodes 17 | 18 | func (ns sortByWeight) Len() int { 19 | return len(ns) 20 | } 21 | 22 | func (ns sortByWeight) Swap(i, j int) { 23 | ns[i], ns[j] = ns[j], ns[i] 24 | } 25 | 26 | func (ns sortByWeight) Less(i, j int) bool { 27 | return nodeWeight(ns[i]) > nodeWeight(ns[j]) 28 | } 29 | 30 | func nodeWeight(n *types.Node) float64 { 31 | return math.Pow(float64((n.Bandwidth+1)/(n.Delay+1)), 4) 32 | } 33 | 34 | func weightedRandomChoice(nodes types.Nodes) int { 35 | if len(nodes) == 0 { 36 | return -1 37 | } 38 | 39 | cdf := make([]float64, len(nodes)) 40 | cdf[0] = nodeWeight(nodes[0]) 41 | for i := 1; i < len(nodes); i++ { 42 | cdf[i] = cdf[i-1] + nodeWeight(nodes[i]) 43 | } 44 | 45 | v := rand.Float64() * cdf[len(cdf)-1] 46 | return sort.Search(len(cdf), func(i int) bool { return cdf[i] > v }) % len(cdf) 47 | } 48 | 49 | func sortMeasuredNodes(nodes types.Nodes) { 50 | sort.Sort(sortByWeight(nodes)) 51 | choice := weightedRandomChoice(nodes) 52 | for i := choice; i > 0; i-- { 53 | nodes[i-1], nodes[i] = nodes[i], nodes[i-1] 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /util.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "encoding/hex" 5 | "errors" 6 | "fmt" 7 | "net" 8 | "strconv" 9 | "sync" 10 | "time" 11 | ) 12 | 13 | var ( 14 | zeroTime time.Time 15 | ) 16 | 17 | func sessionKey(remoteAddr string, sessionID []byte) string { 18 | return remoteAddr + ":" + hex.EncodeToString(sessionID) 19 | } 20 | 21 | func connID(i int) string { 22 | return strconv.Itoa(i) 23 | } 24 | 25 | // Get free port start from parameter `port` 26 | // If paramenter `port` is 0, return system available port 27 | // The returned port is free in both TCP and UDP 28 | var lock sync.Mutex 29 | 30 | func GetFreePort(port int) (int, error) { 31 | // to avoid race condition 32 | lock.Lock() 33 | defer lock.Unlock() 34 | 35 | for i := 0; i < 100; i++ { 36 | addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("127.0.0.1:%d", port)) 37 | if err != nil { 38 | return 0, err 39 | } 40 | 41 | l, err := net.ListenTCP("tcp", addr) 42 | if err != nil { 43 | return 0, err 44 | } 45 | defer l.Close() 46 | 47 | port = l.Addr().(*net.TCPAddr).Port 48 | u, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: port}) 49 | if err != nil { 50 | l.Close() 51 | port++ 52 | continue 53 | } 54 | u.Close() 55 | 56 | return port, nil 57 | } 58 | 59 | return 0, errors.New("failed to find free port after 100 tries") 60 | } 61 | -------------------------------------------------------------------------------- /tests/cachepubaddr_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "log" 5 | "testing" 6 | "time" 7 | 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | // go test -v -run=TestCachePubAddr 12 | func TestCachePubAddr(t *testing.T) { 13 | ch := make(chan string, 1) 14 | 15 | go func() { 16 | StartTunaTcpListener(numTcpListener, ch) 17 | }() 18 | 19 | waitfor(ch, listening) 20 | time.Sleep(10 * time.Second) // still wait for tuna exits establish connections. 21 | 22 | go func() { 23 | log.Printf("tcp dialer start now...") 24 | 25 | acc, wal, err := CreateAccountAndWallet(seedHex) 26 | require.Nil(t, err) 27 | mc, err := CreateMultiClient(acc, dialerId, 2) 28 | require.Nil(t, err) 29 | 30 | tunaSess, err := CreateTunaSession(acc, wal, mc, numTcpListener) 31 | require.Nil(t, err) 32 | 33 | diaConfig := CreateDialConfig(5000) 34 | ncpSess1, err := tunaSess.DialWithConfig(remoteAddr, diaConfig) 35 | require.Nil(t, err) 36 | ch <- dialed 37 | 38 | mc.Close() // close nkn multi-client 39 | ncpSess2, err := tunaSess.DialWithConfig(remoteAddr, diaConfig) 40 | require.Nil(t, err) 41 | ch <- dialed 42 | log.Printf("tcp dialer dialed up even nkn multi-client closed, because it uses cached pubAddrs...") 43 | 44 | tunaSess.CloseOneConn(ncpSess1, "0") // close connection 0 45 | tunaSess.CloseOneConn(ncpSess2, "0") // close conenction 0 46 | 47 | time.Sleep(time.Second) 48 | _, err = tunaSess.DialWithConfig(remoteAddr, diaConfig) // should not dial up successfully. 49 | require.NotNil(t, err) 50 | 51 | ch <- end 52 | }() 53 | 54 | waitfor(ch, end) 55 | } 56 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/nknorg/nkn-tuna-session 2 | 3 | go 1.20 4 | 5 | require ( 6 | github.com/imdario/mergo v0.3.15 7 | github.com/nknorg/ncp-go v1.0.6-0.20230228002512-f4cd1740bebd 8 | github.com/nknorg/nkn-sdk-go v1.4.6-0.20230404044330-ad192f36d07e 9 | github.com/nknorg/nkn/v2 v2.2.0 10 | github.com/nknorg/nkngomobile v0.0.0-20220615081414-671ad1afdfa9 11 | github.com/nknorg/tuna v0.0.0-20230818024750-e800a743f680 12 | github.com/patrickmn/go-cache v2.1.0+incompatible 13 | github.com/stretchr/testify v1.8.1 14 | golang.org/x/crypto v0.7.0 15 | google.golang.org/protobuf v1.29.1 16 | ) 17 | 18 | require ( 19 | github.com/davecgh/go-spew v1.1.1 // indirect 20 | github.com/golang/protobuf v1.5.3 // indirect 21 | github.com/gorilla/websocket v1.5.0 // indirect 22 | github.com/hashicorp/errwrap v1.1.0 // indirect 23 | github.com/hashicorp/go-multierror v1.1.1 // indirect 24 | github.com/itchyny/base58-go v0.2.1 // indirect 25 | github.com/jpillora/backoff v1.0.0 // indirect 26 | github.com/kr/text v0.2.0 // indirect 27 | github.com/nknorg/encrypted-stream v1.0.2-0.20230320101720-9891f770de86 // indirect 28 | github.com/oschwald/geoip2-golang v1.4.0 // indirect 29 | github.com/oschwald/maxminddb-golang v1.6.0 // indirect 30 | github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect 31 | github.com/pkg/errors v0.9.1 // indirect 32 | github.com/pmezard/go-difflib v1.0.0 // indirect 33 | github.com/rdegges/go-ipify v0.0.0-20150526035502-2d94a6a86c40 // indirect 34 | github.com/xtaci/smux v2.0.1+incompatible // indirect 35 | golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c // indirect 36 | golang.org/x/sys v0.6.0 // indirect 37 | golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df // indirect 38 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 39 | gopkg.in/yaml.v3 v3.0.1 // indirect 40 | ) 41 | -------------------------------------------------------------------------------- /tests/pub.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "encoding/hex" 5 | "log" 6 | 7 | nkn "github.com/nknorg/nkn-sdk-go" 8 | ts "github.com/nknorg/nkn-tuna-session" 9 | ) 10 | 11 | func CreateAccountAndWallet(seedHex string) (acc *nkn.Account, wal *nkn.Wallet, err error) { 12 | seed, err := hex.DecodeString(seedHex) 13 | if err != nil { 14 | log.Fatal(err) 15 | return nil, nil, err 16 | } 17 | 18 | acc, err = nkn.NewAccount(seed) 19 | if err != nil { 20 | log.Fatal(err) 21 | return 22 | } 23 | 24 | wal, err = nkn.NewWallet(acc, nil) 25 | if err != nil { 26 | log.Fatal(err) 27 | } 28 | bal, _ := wal.Balance() 29 | log.Printf("wallet address is %v, balance is %v", wal.Address(), bal) 30 | 31 | return 32 | } 33 | 34 | func CreateTunaSessionConfig(numListener int) (config *ts.Config) { 35 | config = &ts.Config{ 36 | NumTunaListeners: numListener, 37 | TunaMaxPrice: "0.01", 38 | } 39 | return config 40 | } 41 | 42 | func CreateDialConfig(timeout int32) (config *nkn.DialConfig) { 43 | config = &nkn.DialConfig{DialTimeout: timeout} 44 | return 45 | } 46 | 47 | func CreateClientConfig(retries int32) (config *nkn.ClientConfig) { 48 | config = &nkn.ClientConfig{ConnectRetries: retries} 49 | return 50 | } 51 | 52 | func CreateMultiClient(account *nkn.Account, id string, numClient int) (mc *nkn.MultiClient, err error) { 53 | clientConfig := CreateClientConfig(1) 54 | mc, err = nkn.NewMultiClient(account, id, numClient, false, clientConfig) 55 | if err != nil { 56 | log.Fatal(err) 57 | } 58 | 59 | <-mc.OnConnect.C 60 | return 61 | } 62 | 63 | func CreateTunaSession(account *nkn.Account, wallet *nkn.Wallet, mc *nkn.MultiClient, numListener int) (tunaSess *ts.TunaSessionClient, err error) { 64 | config := CreateTunaSessionConfig(numListener) 65 | tunaSess, err = ts.NewTunaSessionClient(account, mc, wallet, config) 66 | if err != nil { 67 | log.Fatal(err) 68 | } 69 | return 70 | } 71 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "github.com/imdario/mergo" 5 | ncp "github.com/nknorg/ncp-go" 6 | "github.com/nknorg/tuna" 7 | "github.com/nknorg/tuna/filter" 8 | "github.com/nknorg/tuna/geo" 9 | ) 10 | 11 | type Config struct { 12 | NumTunaListeners int 13 | TunaDialTimeout int // in millisecond 14 | TunaMaxPrice string 15 | TunaNanoPayFee string 16 | TunaMinNanoPayFee string 17 | TunaNanoPayFeeRatio float64 18 | TunaServiceName string 19 | TunaSubscriptionPrefix string 20 | TunaIPFilter *geo.IPFilter 21 | TunaNknFilter *filter.NknFilter 22 | TunaDownloadGeoDB bool 23 | TunaGeoDBPath string 24 | TunaMeasureBandwidth bool 25 | TunaMeasureStoragePath string 26 | TunaMeasurementBytesDownLink int32 27 | TunaMinBalance string 28 | SessionConfig *ncp.Config 29 | ReconnectRetries int // negative value: unlimited retries, 0: no reconnect, positive value: limit retries. 30 | ReconnectInterval int // millisecond 31 | UDPRecvBufferSize int // UDP user data receive buffer size, bytes 32 | MaxUdpDatagramBuffered int // Maximum udp datagrams can be buffered. It works with UDPRecvBufferSize together go decide if a datagram is buffered. 33 | Verbose bool 34 | } 35 | 36 | var defaultConfig = Config{ 37 | NumTunaListeners: 4, 38 | TunaDialTimeout: 10000, 39 | TunaMaxPrice: "0", 40 | TunaNanoPayFee: "", 41 | TunaMinNanoPayFee: "0", 42 | TunaNanoPayFeeRatio: 0.1, 43 | TunaServiceName: tuna.DefaultReverseServiceName, 44 | TunaSubscriptionPrefix: tuna.DefaultSubscriptionPrefix, 45 | TunaIPFilter: nil, 46 | TunaNknFilter: nil, 47 | TunaDownloadGeoDB: false, 48 | TunaGeoDBPath: "", 49 | TunaMeasureBandwidth: false, 50 | TunaMeasureStoragePath: "", 51 | TunaMeasurementBytesDownLink: 0, // use tuna default value 52 | TunaMinBalance: "0", 53 | SessionConfig: nil, 54 | ReconnectRetries: 0, 55 | ReconnectInterval: 2000, 56 | UDPRecvBufferSize: 1 << 20, // 1 mega bytes 57 | MaxUdpDatagramBuffered: 1024, 58 | Verbose: false, 59 | } 60 | 61 | func DefaultConfig() *Config { 62 | conf := defaultConfig 63 | conf.TunaIPFilter = &geo.IPFilter{} 64 | conf.TunaNknFilter = &filter.NknFilter{} 65 | conf.SessionConfig = DefaultSessionConfig() 66 | return &conf 67 | } 68 | 69 | var defaultSessionConfig = ncp.Config{ 70 | MTU: 1300, 71 | } 72 | 73 | func DefaultSessionConfig() *ncp.Config { 74 | sessionConf := defaultSessionConfig 75 | return &sessionConf 76 | } 77 | 78 | func MergedConfig(conf *Config) (*Config, error) { 79 | merged := DefaultConfig() 80 | if conf != nil { 81 | err := mergo.Merge(merged, conf, mergo.WithOverride) 82 | if err != nil { 83 | return nil, err 84 | } 85 | } 86 | return merged, nil 87 | } 88 | -------------------------------------------------------------------------------- /udp.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "errors" 5 | "net" 6 | "strconv" 7 | "time" 8 | 9 | "github.com/nknorg/nkn-sdk-go" 10 | "github.com/nknorg/tuna" 11 | ) 12 | 13 | // Start UDP server listening. 14 | // Because UDP is connectionless, we use TCP to track the connection status. 15 | // So we need to start a TCP server first, and then start a UDP server. 16 | // Meanwhile, Tuna session server hase two modes: TCP only, or TCP + UDP. 17 | func (c *TunaSessionClient) ListenUDP() (*UdpSession, error) { 18 | if len(c.listeners) == 0 { 19 | return nil, errors.New("please call Listen() to start TCP first") 20 | } 21 | 22 | if c.listenerUdpSess != nil { 23 | return c.listenerUdpSess, nil 24 | } 25 | c.listenerUdpSess = newUdpSession(c, true) 26 | 27 | err := c.startExits() 28 | if err != nil { 29 | return nil, err 30 | } 31 | 32 | host, portStr, err := net.SplitHostPort(c.listeners[0].Addr().String()) 33 | if err != nil { 34 | return nil, err 35 | } 36 | port, err := strconv.Atoi(portStr) 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | conn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP(host), Port: port}) 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | c.listenerUdpSess.udpConn = tuna.NewEncryptUDPConn(conn) 47 | 48 | go c.listenerUdpSess.recvMsg() 49 | 50 | return c.listenerUdpSess, nil 51 | } 52 | 53 | func (c *TunaSessionClient) DialUDP(remoteAddr string) (*UdpSession, error) { 54 | return c.DialUDPWithConfig(remoteAddr, nil) 55 | } 56 | 57 | func (c *TunaSessionClient) DialUDPWithConfig(remoteAddr string, config *nkn.DialConfig) (*UdpSession, error) { 58 | config, err := nkn.MergeDialConfig(c.config.SessionConfig, config) 59 | if err != nil { 60 | return nil, err 61 | } 62 | 63 | remoteAddr, err = c.multiClient.ResolveDest(remoteAddr) 64 | if err != nil { 65 | return nil, err 66 | } 67 | 68 | sessionID, err := nkn.RandomBytes(SessionIDSize) 69 | if err != nil { 70 | return nil, err 71 | } 72 | 73 | udpSess := newUdpSession(c, false) 74 | err = udpSess.DialUpSession(remoteAddr, sessionID, config) 75 | if err != nil { 76 | return nil, err 77 | } 78 | go udpSess.recvMsg() 79 | 80 | go func() { 81 | for { 82 | udpSess.handleTcpMsg(udpSess.tcpConn, sessionKey(remoteAddr, sessionID)) 83 | 84 | if c.isClosed || udpSess.udpConn.IsClosed() { 85 | break 86 | } 87 | if c.config.ReconnectRetries == 0 { 88 | return 89 | } 90 | 91 | j := 0 92 | for j = 0; c.config.ReconnectRetries < 0 || j < c.config.ReconnectRetries; j++ { 93 | var err error 94 | if err = udpSess.DialUpSession(remoteAddr, sessionID, config); err == nil { 95 | break 96 | } 97 | if err == ErrClosed { 98 | return 99 | } 100 | time.Sleep(time.Duration(c.config.ReconnectInterval) * time.Millisecond) 101 | } 102 | if j >= c.config.ReconnectRetries { 103 | break 104 | } 105 | } 106 | }() 107 | 108 | return udpSess, nil 109 | } 110 | 111 | func (c *TunaSessionClient) handleUdpListenerTcp(tcpConn *Conn, remoteAddr string, sessionID []byte) { 112 | if c.listenerUdpSess == nil { // Udp listener not started 113 | tcpConn.Close() 114 | return 115 | } 116 | sessKey := sessionKey(remoteAddr, sessionID) 117 | 118 | c.listenerUdpSess.Lock() 119 | c.listenerUdpSess.tcpConns[sessKey] = tcpConn 120 | c.listenerUdpSess.Unlock() 121 | 122 | go func() { // Udp listener starts monitoring tcp connection status 123 | c.listenerUdpSess.handleTcpMsg(tcpConn, sessKey) 124 | 125 | c.listenerUdpSess.Lock() 126 | delete(c.listenerUdpSess.tcpConns, sessKey) 127 | c.listenerUdpSess.Unlock() 128 | }() 129 | } 130 | -------------------------------------------------------------------------------- /examples/http/main.go: -------------------------------------------------------------------------------- 1 | // Basic usage: main -l -d -n 4 2 | // Use --help to see more options 3 | 4 | package main 5 | 6 | import ( 7 | "encoding/hex" 8 | "flag" 9 | "io" 10 | "log" 11 | "net" 12 | "net/http" 13 | "strings" 14 | 15 | "github.com/nknorg/ncp-go" 16 | nkn "github.com/nknorg/nkn-sdk-go" 17 | ts "github.com/nknorg/nkn-tuna-session" 18 | "github.com/nknorg/tuna/geo" 19 | ) 20 | 21 | const ( 22 | dialID = "alice" 23 | listenID = "bob" 24 | ) 25 | 26 | func main() { 27 | numTunaListeners := flag.Int("n", 1, "number of tuna listeners") 28 | numClients := flag.Int("c", 4, "number of clients") 29 | seedHex := flag.String("s", "", "secret seed") 30 | dialAddr := flag.String("a", "", "dial address") 31 | dial := flag.Bool("d", false, "dial") 32 | listen := flag.Bool("l", false, "listen") 33 | serveDir := flag.String("dir", ".", "serve directory") 34 | httpAddr := flag.String("http", ":8080", "http listen address") 35 | tunaCountry := flag.String("country", "", `tuna service node allowed country code, separated by comma, e.g. "US" or "US,CN"`) 36 | tunaServiceName := flag.String("tsn", "", "tuna reverse service name") 37 | tunaSubscriptionPrefix := flag.String("tsp", "", "tuna subscription prefix") 38 | tunaMaxPrice := flag.String("price", "0.01", "tuna reverse service max price in unit of NKN/MB") 39 | mtu := flag.Int("mtu", 0, "ncp session mtu") 40 | 41 | flag.Parse() 42 | 43 | seed, err := hex.DecodeString(*seedHex) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | 48 | countries := strings.Split(*tunaCountry, ",") 49 | locations := make([]geo.Location, len(countries)) 50 | for i := range countries { 51 | locations[i].CountryCode = strings.TrimSpace(countries[i]) 52 | } 53 | 54 | account, err := nkn.NewAccount(seed) 55 | if err != nil { 56 | log.Fatal(err) 57 | } 58 | 59 | wallet, err := nkn.NewWallet(account, nil) 60 | if err != nil { 61 | log.Fatal(err) 62 | } 63 | 64 | log.Println("Seed:", hex.EncodeToString(account.Seed())) 65 | 66 | clientConfig := &nkn.ClientConfig{ConnectRetries: 1} 67 | config := &ts.Config{ 68 | NumTunaListeners: *numTunaListeners, 69 | TunaServiceName: *tunaServiceName, 70 | TunaSubscriptionPrefix: *tunaSubscriptionPrefix, 71 | TunaMaxPrice: *tunaMaxPrice, 72 | TunaIPFilter: &geo.IPFilter{Allow: locations}, 73 | SessionConfig: &ncp.Config{MTU: int32(*mtu)}, 74 | } 75 | 76 | if *listen { 77 | m, err := nkn.NewMultiClient(account, listenID, *numClients, false, clientConfig) 78 | if err != nil { 79 | log.Fatal(err) 80 | } 81 | 82 | <-m.OnConnect.C 83 | 84 | c, err := ts.NewTunaSessionClient(account, m, wallet, config) 85 | if err != nil { 86 | log.Fatal(err) 87 | } 88 | 89 | err = c.Listen(nil) 90 | if err != nil { 91 | log.Fatal(err) 92 | } 93 | 94 | <-c.OnConnect() 95 | 96 | log.Println("Listening at", c.Addr()) 97 | 98 | go func() { 99 | log.Println("Serving content at", m.Addr().String()) 100 | fs := http.FileServer(http.Dir(*serveDir)) 101 | http.Handle("/", fs) 102 | http.Serve(c, nil) 103 | }() 104 | } 105 | 106 | if *dial { 107 | m, err := nkn.NewMultiClient(account, dialID, *numClients, false, clientConfig) 108 | if err != nil { 109 | log.Fatal(err) 110 | } 111 | 112 | <-m.OnConnect.C 113 | 114 | c, err := ts.NewTunaSessionClient(account, m, wallet, config) 115 | if err != nil { 116 | log.Fatal(err) 117 | } 118 | 119 | if len(*dialAddr) == 0 { 120 | *dialAddr = listenID + "." + strings.SplitN(m.Addr().String(), ".", 2)[1] 121 | } 122 | 123 | listener, err := net.Listen("tcp", *httpAddr) 124 | if err != nil { 125 | log.Fatal(err) 126 | } 127 | 128 | log.Println("Http server listening at", *httpAddr) 129 | 130 | go func() { 131 | for { 132 | conn, err := listener.Accept() 133 | if err != nil { 134 | log.Fatal(err) 135 | } 136 | 137 | sess, err := c.Dial(*dialAddr) 138 | if err != nil { 139 | log.Fatal(err) 140 | } 141 | 142 | go func() { 143 | io.Copy(conn, sess) 144 | }() 145 | go func() { 146 | io.Copy(sess, conn) 147 | }() 148 | } 149 | }() 150 | } 151 | 152 | select {} 153 | } 154 | -------------------------------------------------------------------------------- /message.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "crypto/rand" 5 | "encoding/binary" 6 | "encoding/hex" 7 | "errors" 8 | "fmt" 9 | "io" 10 | "regexp" 11 | "time" 12 | 13 | "github.com/nknorg/nkngomobile" 14 | 15 | "github.com/nknorg/nkn/v2/crypto/ed25519" 16 | "golang.org/x/crypto/nacl/box" 17 | ) 18 | 19 | const ( 20 | nonceSize = 24 21 | sharedKeySize = 32 22 | maxAddrSize = 512 23 | maxSessionMetadataSize = 1024 24 | maxSessionMsgOverhead = 1024 25 | 26 | ActionGetPubAddr = "getPubAddr" 27 | ) 28 | 29 | type Request struct { 30 | Action string `json:"action"` 31 | SessionID []byte `json:"sessionID"` 32 | } 33 | 34 | type PubAddr struct { 35 | IP string `json:"ip"` 36 | Port uint32 `json:"port"` 37 | InPrice string `json:"inPrice,omitempty"` 38 | OutPrice string `json:"outPrice,omitempty"` 39 | } 40 | 41 | func (pa *PubAddr) String() string { 42 | return fmt.Sprintf("%v:%v", pa.IP, pa.Port) 43 | } 44 | 45 | type PubAddrs struct { 46 | Addrs []*PubAddr `json:"addrs"` 47 | SessionClosed bool `json:"sessionClosed"` 48 | } 49 | 50 | func (c *TunaSessionClient) getOrComputeSharedKey(remotePublicKey []byte) (*[sharedKeySize]byte, error) { 51 | k := hex.EncodeToString(remotePublicKey) 52 | c.RLock() 53 | sharedKey, ok := c.sharedKeys[k] 54 | c.RUnlock() 55 | if ok && sharedKey != nil { 56 | return sharedKey, nil 57 | } 58 | 59 | if len(remotePublicKey) != ed25519.PublicKeySize { 60 | return nil, fmt.Errorf("public key length is %d, expecting %d", len(remotePublicKey), ed25519.PublicKeySize) 61 | } 62 | 63 | var pk [ed25519.PublicKeySize]byte 64 | copy(pk[:], remotePublicKey) 65 | curve25519PublicKey, ok := ed25519.PublicKeyToCurve25519PublicKey(&pk) 66 | if !ok { 67 | return nil, fmt.Errorf("converting public key %x to curve25519 public key failed", remotePublicKey) 68 | } 69 | 70 | var sk [ed25519.PrivateKeySize]byte 71 | copy(sk[:], c.clientAccount.PrivKey()) 72 | curveSecretKey := ed25519.PrivateKeyToCurve25519PrivateKey(&sk) 73 | 74 | sharedKey = new([sharedKeySize]byte) 75 | box.Precompute(sharedKey, curve25519PublicKey, curveSecretKey) 76 | 77 | c.Lock() 78 | c.sharedKeys[k] = sharedKey 79 | c.Unlock() 80 | 81 | return sharedKey, nil 82 | } 83 | 84 | func encrypt(message []byte, sharedKey *[sharedKeySize]byte) ([]byte, []byte, error) { 85 | encrypted := make([]byte, len(message)+box.Overhead) 86 | var nonce [nonceSize]byte 87 | if _, err := rand.Read(nonce[:]); err != nil { 88 | return nil, nil, err 89 | } 90 | box.SealAfterPrecomputation(encrypted[:0], message, &nonce, sharedKey) 91 | return encrypted, nonce[:], nil 92 | } 93 | 94 | func decrypt(message []byte, nonce [nonceSize]byte, sharedKey *[sharedKeySize]byte) ([]byte, error) { 95 | decrypted := make([]byte, len(message)-box.Overhead) 96 | _, ok := box.OpenAfterPrecomputation(decrypted[:0], message, &nonce, sharedKey) 97 | if !ok { 98 | return nil, errors.New("decrypt message failed") 99 | } 100 | 101 | return decrypted, nil 102 | } 103 | 104 | func writeMessage(conn *Conn, buf []byte, writeTimeout time.Duration) error { 105 | conn.WriteLock.Lock() 106 | defer conn.WriteLock.Unlock() 107 | 108 | msgSizeBuf := make([]byte, 4) 109 | binary.LittleEndian.PutUint32(msgSizeBuf, uint32(len(buf))) 110 | 111 | if writeTimeout > 0 { 112 | conn.SetWriteDeadline(time.Now().Add(writeTimeout)) 113 | } 114 | 115 | _, err := conn.Write(msgSizeBuf) 116 | if err != nil { 117 | return err 118 | } 119 | 120 | _, err = conn.Write(buf) 121 | if err != nil { 122 | return err 123 | } 124 | 125 | if writeTimeout > 0 { 126 | conn.SetWriteDeadline(zeroTime) 127 | } 128 | 129 | return nil 130 | } 131 | 132 | func readMessage(conn *Conn, maxMsgSize uint32) ([]byte, error) { 133 | conn.ReadLock.Lock() 134 | defer conn.ReadLock.Unlock() 135 | 136 | msgSizeBuf := make([]byte, 4) 137 | _, err := io.ReadFull(conn, msgSizeBuf) 138 | if err != nil { 139 | return nil, err 140 | } 141 | 142 | msgSize := binary.LittleEndian.Uint32(msgSizeBuf) 143 | if msgSize > maxMsgSize { 144 | return nil, fmt.Errorf("invalid message size %d, should be no greater than %d", msgSize, maxMsgSize) 145 | } 146 | 147 | buf := make([]byte, msgSize) 148 | _, err = io.ReadFull(conn, buf) 149 | if err != nil { 150 | return nil, err 151 | } 152 | 153 | return buf, nil 154 | } 155 | 156 | func getAcceptAddrs(addrsRe *nkngomobile.StringArray) ([]*regexp.Regexp, error) { 157 | var addrs []string 158 | if addrsRe == nil { 159 | addrs = []string{DefaultSessionAllowAddr} 160 | } else { 161 | addrs = addrsRe.Elems() 162 | } 163 | 164 | var err error 165 | acceptAddrs := make([]*regexp.Regexp, len(addrs)) 166 | for i := 0; i < len(acceptAddrs); i++ { 167 | acceptAddrs[i], err = regexp.Compile(addrs[i]) 168 | if err != nil { 169 | return nil, err 170 | } 171 | } 172 | return acceptAddrs, nil 173 | } 174 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NKN Tuna Session 2 | 3 | NKN Tuna Session is an overlay peer to peer connection based on multiple 4 | concurrent [tuna](https://github.com/nknorg/tuna) connections and 5 | [ncp](https://github.com/nknorg/ncp-go) protocol. 6 | 7 | A few feature highlights: 8 | 9 | * Performance: Use multiple parallel paths to boost overall throughput. 10 | 11 | * Network agnostic: Neither dialer nor listener needs to have public IP address 12 | or NAT traversal. They are guaranteed to be connected regardless of their 13 | network conditions. 14 | 15 | * Security: Using public key as address, which enables built-in end to end 16 | encryption while being invulnerable to man-in-the-middle attack. 17 | 18 | A simple illustration of a session between Alice and Bob: 19 | 20 | ``` 21 | X 22 | / \ 23 | Alice - Y - Bob 24 | \ / 25 | Z 26 | ``` 27 | 28 | Listener (Bob for example) will pay relayers in the middle (X, Y, Z) for 29 | relaying the traffic using NKN tokens. The payment will be based on bandwidth 30 | usage of the session. 31 | 32 | ## Usage 33 | 34 | You first need to import both `nkn-sdk-go` and `nkn-tuna-session`: 35 | 36 | ```go 37 | import ( 38 | nkn "github.com/nknorg/nkn-sdk-go" 39 | ts "github.com/nknorg/nkn-tuna-session" 40 | ) 41 | ``` 42 | 43 | Create a multi-client and wallet (see 44 | [nkn-sdk-go](https://github.com/nknorg/nkn-sdk-go) for details) or re-use your 45 | existing ones: 46 | 47 | ```go 48 | multiclient, err := nkn.NewMultiClient(...) 49 | // wallet is only needed for listener side 50 | wallet, err := nkn.NewWallet(...) 51 | ``` 52 | 53 | Then you can create a tuna session client: 54 | 55 | ```go 56 | // wallet is only needed for listener side and will be used for payment 57 | // price is in unit of NKN token per MB 58 | c, err := ts.NewTunaSessionClient(account, multiclient, wallet, &ts.Config{TunaMaxPrice: "0"}) 59 | ``` 60 | 61 | A tuna session client can start listening for incoming session where the remote 62 | address match any of the given regexp: 63 | 64 | ```go 65 | // Accepting any address, equivalent to c.Listen(nkn.NewStringArray(".*")) 66 | err = c.Listen(nil) 67 | // Only accepting pubkey 25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99 but with any identifiers 68 | err = c.Listen(nkn.NewStringArray("25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99$")) 69 | // Only accepting address alice.25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99 70 | err = c.Listen(nkn.NewStringArray("^alice\\.25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99$")) 71 | ``` 72 | 73 | Wait for tuna to connect: 74 | 75 | ```go 76 | <-c.OnConnect() 77 | ``` 78 | 79 | Then it can start accepting sessions: 80 | 81 | ```go 82 | session, err := c.Accept() 83 | ``` 84 | 85 | Tuna session client implements `net.Listener` interface, so one can use it as a 86 | drop-in replacement when `net.Listener` is needed, e.g. `http.Serve`. 87 | 88 | On the other hand, any tuna session client can dial a session to a remote NKN 89 | address: 90 | 91 | ```go 92 | session, err := c.Dial("another nkn address") 93 | ``` 94 | 95 | Session implements `net.Conn` interface, so it can be used as a drop-in 96 | replacement when `net.Conn` is needed: 97 | 98 | ```go 99 | buf := make([]byte, 1024) 100 | n, err := session.Read(buf) 101 | n, err := session.Write(buf) 102 | ``` 103 | 104 | A few more complicated examples can be found at [examples](examples) 105 | 106 | ## Usage on iOS/Android 107 | 108 | This library is designed to work with 109 | [gomobile](https://godoc.org/golang.org/x/mobile/cmd/gomobile) and run natively 110 | on iOS/Android without any modification. You can use `gomobile bind` to compile 111 | it to Objective-C framework for iOS: 112 | 113 | ```shell 114 | gomobile bind -target=ios -ldflags "-s -w" github.com/nknorg/nkn-tuna-session github.com/nknorg/nkn-sdk-go github.com/nknorg/ncp-go github.com/nknorg/tuna github.com/nknorg/nkngomobile 115 | ``` 116 | 117 | and Java AAR for Android: 118 | 119 | ```shell 120 | gomobile bind -target=android -ldflags "-s -w" github.com/nknorg/nkn-tuna-session github.com/nknorg/nkn-sdk-go github.com/nknorg/ncp-go github.com/nknorg/tuna github.com/nknorg/nkngomobile 121 | ``` 122 | 123 | ## Contributing 124 | 125 | **Can I submit a bug, suggestion or feature request?** 126 | 127 | Yes. Please open an issue for that. 128 | 129 | **Can I contribute patches?** 130 | 131 | Yes, we appreciate your help! To make contributions, please fork the repo, push 132 | your changes to the forked repo with signed-off commits, and open a pull request 133 | here. 134 | 135 | Please sign off your commit. This means adding a line "Signed-off-by: Name 136 | " at the end of each commit, indicating that you wrote the code and have 137 | the right to pass it on as an open source patch. This can be done automatically 138 | by adding -s when committing: 139 | 140 | ```shell 141 | git commit -s 142 | ``` 143 | 144 | ## Community 145 | 146 | * [Discord](https://discord.gg/c7mTynX) 147 | * [Telegram](https://t.me/nknorg) 148 | * [Reddit](https://www.reddit.com/r/nknblockchain/) 149 | * [Twitter](https://twitter.com/NKN_ORG) 150 | -------------------------------------------------------------------------------- /tests/session_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "encoding/hex" 7 | "errors" 8 | "io" 9 | "net" 10 | "os" 11 | "strconv" 12 | "strings" 13 | "sync" 14 | "testing" 15 | "time" 16 | 17 | "github.com/nknorg/ncp-go" 18 | "github.com/nknorg/nkn-sdk-go" 19 | ts "github.com/nknorg/nkn-tuna-session" 20 | "github.com/nknorg/nkn/v2/crypto" 21 | "github.com/nknorg/nkn/v2/vault" 22 | "github.com/nknorg/tuna" 23 | "github.com/nknorg/tuna/pb" 24 | _ "github.com/nknorg/tuna/tests" 25 | "github.com/nknorg/tuna/types" 26 | "github.com/nknorg/tuna/util" 27 | ) 28 | 29 | const ( 30 | dialID = "alice" 31 | listenID = "bob" 32 | ) 33 | 34 | func TestMain(m *testing.M) { 35 | os.Exit(m.Run()) 36 | } 37 | 38 | func TestTunaSession(t *testing.T) { 39 | _, privKey, _ := crypto.GenKeyPair() 40 | seed := crypto.GetSeedFromPrivateKey(privKey) 41 | _, privKey2, _ := crypto.GenKeyPair() 42 | seed2 := crypto.GetSeedFromPrivateKey(privKey2) 43 | 44 | // Set up tuna 45 | tunaPubKey, tunaPrivKey, _ := crypto.GenKeyPair() 46 | tunaSeed := crypto.GetSeedFromPrivateKey(tunaPrivKey) 47 | go runReverseEntry(tunaSeed) 48 | time.Sleep(15 * time.Second) 49 | 50 | account, err := nkn.NewAccount(seed) 51 | if err != nil { 52 | t.Fatal(err) 53 | } 54 | account2, err := nkn.NewAccount(seed2) 55 | if err != nil { 56 | t.Fatal(err) 57 | } 58 | seedRPCServerAddr := nkn.NewStringArray(nkn.DefaultSeedRPCServerAddr...) 59 | walletConfig := &nkn.WalletConfig{ 60 | SeedRPCServerAddr: seedRPCServerAddr, 61 | } 62 | 63 | wallet, err := nkn.NewWallet(account, walletConfig) 64 | if err != nil { 65 | t.Fatal(err) 66 | } 67 | wallet2, err := nkn.NewWallet(account2, walletConfig) 68 | if err != nil { 69 | t.Fatal(err) 70 | } 71 | clientConfig := &nkn.ClientConfig{ConnectRetries: 1} 72 | dialConfig := &nkn.DialConfig{DialTimeout: 5000} 73 | config := &ts.Config{ 74 | NumTunaListeners: 1, 75 | TunaMeasureBandwidth: false, 76 | TunaMaxPrice: "0.0", 77 | SessionConfig: &ncp.Config{MTU: int32(0)}, 78 | } 79 | 80 | m, err := nkn.NewMultiClient(account, listenID, 4, false, clientConfig) 81 | if err != nil { 82 | t.Fatal(err) 83 | } 84 | 85 | <-m.OnConnect.C 86 | 87 | c, err := ts.NewTunaSessionClient(account, m, wallet, config) 88 | if err != nil { 89 | t.Fatal(err) 90 | } 91 | 92 | n := &types.Node{ 93 | Delay: 0, 94 | Bandwidth: 0, 95 | Metadata: &pb.ServiceMetadata{ 96 | Ip: "127.0.0.1", 97 | TcpPort: 30020, 98 | UdpPort: 30021, 99 | ServiceId: 0, 100 | Price: "0.0", 101 | BeneficiaryAddr: "", 102 | }, 103 | Address: hex.EncodeToString(tunaPubKey), 104 | MetadataRaw: "CgkxMjcuMC4wLjEQxOoBGMXqAToFMC4wMDE=", 105 | } 106 | c.SetTunaNode(n) 107 | 108 | err = c.Listen(nil) 109 | if err != nil { 110 | t.Fatal(err) 111 | } 112 | 113 | uConn, err := c.ListenUDP() 114 | if err != nil { 115 | t.Fatal(err) 116 | } 117 | 118 | t.Log("Listening at", c.Addr()) 119 | 120 | go func() { 121 | for { 122 | conn, err := c.Accept() 123 | if err != nil { 124 | t.Fatal(err) 125 | } 126 | go func(conn net.Conn) { 127 | defer func() { 128 | conn.Close() 129 | }() 130 | io.Copy(conn, conn) 131 | }(conn) 132 | } 133 | }() 134 | 135 | var wg sync.WaitGroup 136 | for i := 0; i < 4; i++ { 137 | wg.Add(1) 138 | go func(i int) { 139 | defer wg.Done() 140 | id := dialID + strconv.Itoa(i) 141 | mm, err := nkn.NewMultiClient(account2, id, 4, false, clientConfig) 142 | if err != nil { 143 | t.Fatal(err) 144 | } 145 | 146 | <-mm.OnConnect.C 147 | time.Sleep(5 * time.Second) 148 | 149 | cc, err := ts.NewTunaSessionClient(account2, mm, wallet2, config) 150 | if err != nil { 151 | t.Fatal(err) 152 | } 153 | 154 | dialAddr := listenID + "." + strings.SplitN(c.Addr().String(), ".", 2)[1] 155 | 156 | t.Log("Dial to", dialAddr) 157 | 158 | s, err := cc.DialWithConfig(dialAddr, dialConfig) 159 | if err != nil { 160 | t.Fatal(err) 161 | } 162 | 163 | err = testTCP(s) 164 | if err != nil { 165 | t.Fatal(err) 166 | } 167 | 168 | udpConn, err := cc.DialUDPWithConfig(dialAddr, dialConfig) 169 | if err != nil { 170 | t.Fatal(err) 171 | } 172 | 173 | err = testUDP(udpConn, uConn) 174 | if err != nil { 175 | t.Fatal(err) 176 | } 177 | }(i) 178 | } 179 | wg.Wait() 180 | } 181 | 182 | func testTCP(conn net.Conn) error { 183 | send := make([]byte, 4096) 184 | receive := make([]byte, 4096) 185 | 186 | for i := 0; i < 1000; i++ { 187 | rand.Read(send) 188 | conn.Write(send) 189 | io.ReadFull(conn, receive) 190 | if !bytes.Equal(send, receive) { 191 | return errors.New("bytes not equal") 192 | } 193 | } 194 | return nil 195 | } 196 | 197 | func testUDP(from, to *ts.UdpSession) error { 198 | count := 1000 199 | sendList := make([]string, count) 200 | recvList := make([]string, count) 201 | sendNum := 0 202 | recvNum := 0 203 | var wg sync.WaitGroup 204 | var e error 205 | go func() { 206 | wg.Add(1) 207 | receive := make([]byte, 1024) 208 | for i := 0; i < count; i++ { 209 | _, _, err := to.ReadFrom(receive) 210 | if err != nil { 211 | e = err 212 | return 213 | } 214 | recvNum++ 215 | recvList = append(recvList, hex.EncodeToString(receive)) 216 | } 217 | wg.Done() 218 | }() 219 | 220 | go func() { 221 | time.Sleep(1 * time.Second) 222 | send := make([]byte, 1024) 223 | wg.Add(1) 224 | for i := 0; i < count; i++ { 225 | rand.Read(send) 226 | _, err := from.WriteTo(send, nil) 227 | if err != nil { 228 | e = err 229 | return 230 | } 231 | sendNum++ 232 | sendList = append(sendList, hex.EncodeToString(send)) 233 | } 234 | wg.Done() 235 | }() 236 | 237 | wg.Wait() 238 | if sendNum != recvNum { 239 | return errors.New("package lost") 240 | } 241 | 242 | for i := 0; i < sendNum; i++ { 243 | if sendList[i] != recvList[i] { 244 | return errors.New("data mismatch") 245 | } 246 | } 247 | 248 | return e 249 | } 250 | 251 | func runReverseEntry(seed []byte) error { 252 | entryAccount, err := vault.NewAccountWithSeed(seed) 253 | if err != nil { 254 | return err 255 | } 256 | seedRPCServerAddr := nkn.NewStringArray(nkn.DefaultSeedRPCServerAddr...) 257 | 258 | walletConfig := &nkn.WalletConfig{ 259 | SeedRPCServerAddr: seedRPCServerAddr, 260 | } 261 | entryWallet, err := nkn.NewWallet(&nkn.Account{Account: entryAccount}, walletConfig) 262 | if err != nil { 263 | return err 264 | } 265 | entryConfig := new(tuna.EntryConfiguration) 266 | err = util.ReadJSON("config.reverse.entry.json", entryConfig) 267 | if err != nil { 268 | return err 269 | } 270 | err = tuna.StartReverse(entryConfig, entryWallet) 271 | if err != nil { 272 | return err 273 | } 274 | select {} 275 | } 276 | -------------------------------------------------------------------------------- /tests/udp_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "errors" 5 | "log" 6 | "math" 7 | "strconv" 8 | "strings" 9 | "sync" 10 | "testing" 11 | "time" 12 | 13 | "github.com/nknorg/ncp-go" 14 | ts "github.com/nknorg/nkn-tuna-session" 15 | ) 16 | 17 | // go test -v -run=TestStartUDPListner 18 | func TestStartUDPListner(t *testing.T) { 19 | ch := make(chan string, 1) 20 | go func() { 21 | StartUDPListner(numUdpListener, ch) 22 | }() 23 | <-ch 24 | } 25 | 26 | // go test -v -run=TestStartMultiUdpDialer 27 | func TestStartMultiUdpDialer(t *testing.T) { 28 | ch := make(chan string, 1) 29 | go func() { 30 | // wait for Listener be ready 31 | time.Sleep(2 * time.Second) 32 | StartMultiUDPDialer(numUdpListener, ch) 33 | }() 34 | <-ch 35 | } 36 | 37 | func StartUDPListner(numListener int, ch chan string) (tunaSess *ts.TunaSessionClient, ncpSess *ncp.Session) { 38 | acc, wal, err := CreateAccountAndWallet(seedHex) 39 | if err != nil { 40 | log.Fatal("CreateAccountAndWallet err: ", err) 41 | } 42 | mc, err := CreateMultiClient(acc, listenerId, 2) 43 | if err != nil { 44 | log.Fatal("CreateMultiClient err: ", err) 45 | } 46 | tunaSess, err = CreateTunaSession(acc, wal, mc, numListener) 47 | if err != nil { 48 | log.Fatal("CreateTunaSession err: ", err) 49 | } 50 | 51 | err = tunaSess.Listen(nil) 52 | if err != nil { 53 | log.Fatal("tunaSess.Listen ", err) 54 | } 55 | go func() { // TCP 56 | sess, err := tunaSess.Accept() 57 | if err != nil { 58 | log.Fatal("tunaSess.Accept tcp ", err) 59 | } 60 | ncpSess = sess.(*ncp.Session) 61 | 62 | go func() { 63 | err = readTcp(ncpSess) 64 | if err != nil { 65 | log.Printf("StartTunaUDPListner TCP read err:%v\n", err) 66 | } else { 67 | log.Printf("Finished TCP reading, close ncp.session now\n") 68 | } 69 | ncpSess.Close() 70 | }() 71 | }() 72 | 73 | udpSess, err := tunaSess.ListenUDP() 74 | if err != nil { 75 | log.Println("ListenUDP err ", err) 76 | } 77 | go func() { 78 | err = readUdp(udpSess) 79 | if err != nil { 80 | log.Printf("StartTunaUDPListner UDP read err:%v\n", err) 81 | } else { 82 | log.Printf("StartTunaUDPListner finished UDP reading, close udpSess now\n") 83 | } 84 | udpSess.Close() 85 | close(ch) 86 | }() 87 | 88 | return 89 | } 90 | 91 | func StartMultiUDPDialer(numListener int, ch chan string) { 92 | acc, wal, err := CreateAccountAndWallet(seedHex) 93 | if err != nil { 94 | log.Fatal("CreateAccountAndWallet err: ", err) 95 | } 96 | mc, err := CreateMultiClient(acc, dialerId, 2) 97 | if err != nil { 98 | log.Fatal("CreateMultiClient err: ", err) 99 | } 100 | 101 | tunaSess, err := CreateTunaSession(acc, wal, mc, numListener) 102 | if err != nil { 103 | log.Fatal("CreateTunaSession err: ", err) 104 | } 105 | 106 | diaConfig := CreateDialConfig(5000) 107 | var wg sync.WaitGroup 108 | for i := 0; i < numUdpDialers; i++ { 109 | log.Printf("start dialer %v now\n", i) 110 | wg.Add(1) 111 | go func(dialerNum int) { 112 | udpSess, err := tunaSess.DialUDPWithConfig(remoteAddr, diaConfig) 113 | if err != nil { 114 | log.Fatal("StartMultiUDPDialer.DialUDPWithConfig err ", err) 115 | } 116 | log.Printf("dialer %v dial up successfully, going to write\n", dialerNum) 117 | 118 | go func() { 119 | defer wg.Done() 120 | err = writeUdp(udpSess, dialerNum) 121 | if err != nil { 122 | log.Printf("StartMultiUDPDialer Dialer %v write err:%v\n", dialerNum, err) 123 | } else { 124 | log.Printf("UDP Dialer %v Finished UDP writing", dialerNum) 125 | } 126 | 127 | time.Sleep(5 * time.Second) // wait for reader to read data. 128 | log.Printf("UDP Dialer %v close udpSess now", dialerNum) 129 | udpSess.Close() 130 | }() 131 | 132 | // test disconnect 133 | time.Sleep(time.Duration(3+dialerNum*3) * time.Second) 134 | udpSess.CloseTcp(dialerNum) 135 | }(i) 136 | 137 | time.Sleep(time.Second) 138 | } 139 | 140 | wg.Wait() 141 | close(ch) 142 | } 143 | 144 | func readUdp(udpSess *ts.UdpSession) error { 145 | timeStart := time.Now() 146 | bytesReceived := make(map[int]int) // dialerNum to received bytes. 147 | b := make([]byte, bufSize+1) // bufSize + header size 148 | nFull := 0 149 | var mu sync.RWMutex 150 | for { 151 | n, addr, err := udpSess.ReadFrom(b) 152 | if err != nil { 153 | return err 154 | } 155 | 156 | msg := string(b[:n]) 157 | arr := strings.Split(msg, ":") 158 | dialerNum, _ := strconv.Atoi(arr[0]) 159 | mu.RLock() 160 | recved := bytesReceived[dialerNum] 161 | mu.RUnlock() 162 | 163 | if strings.Compare(msg, msgs[dialerNum]) != 0 { 164 | log.Printf("\ndialer %v, received len: %v, data: %v, it is expected len: %v data: %v.\n\n", 165 | dialerNum, len(msg), msg, len(msgs[dialerNum]), msgs[dialerNum]) 166 | return errors.New("wrong message") 167 | } 168 | 169 | recved += n 170 | mu.Lock() 171 | bytesReceived[dialerNum] = recved 172 | mu.Unlock() 173 | 174 | if ((recved - n) * 10 / bytesToSend) != (recved * 10 / bytesToSend) { 175 | log.Printf("udp session %v received %v bytes %.4f MB/s", dialerNum, recved, 176 | float64(recved)/math.Pow(2, 20)/(float64(time.Since(timeStart))/float64(time.Second))) 177 | } 178 | if recved >= bytesToSend { 179 | log.Printf("udp session %v finish receiving %v bytes", dialerNum, recved) 180 | nFull++ 181 | } 182 | 183 | _, err = udpSess.WriteTo(b[:n], addr) 184 | if err != nil { 185 | log.Printf("udp session %v WriteTo err: %v", dialerNum, err) 186 | break 187 | } 188 | 189 | if nFull == numUdpDialers { 190 | break 191 | } 192 | } 193 | return nil 194 | } 195 | 196 | // Messages for differnet dialers. 197 | var msgs = []string{ 198 | "0:0000000000000", 199 | "1:111111111111111111", 200 | "2:2222222222222222222222222222", 201 | "3:33333333333333333333333333333333333333", 202 | } 203 | 204 | func writeUdp(udpSess *ts.UdpSession, dialerNum int) error { 205 | timeStart := time.Now() 206 | bytesSent := 0 207 | for bytesSent < bytesToSend { 208 | n, err := udpSess.WriteTo([]byte(msgs[dialerNum]), nil) 209 | if err != nil { 210 | log.Printf("dialer %v udpSess.WriteMsgUDP err %v\n", dialerNum, err) 211 | time.Sleep(2 * time.Second) 212 | continue 213 | } 214 | 215 | if n != len(msgs[dialerNum]) { 216 | log.Printf("\ndialer %v write len %v is not eaqul to %v\n\n", dialerNum, n, len(msgs[dialerNum])) 217 | continue 218 | } 219 | bytesSent += n 220 | 221 | if bytesSent >= bytesToSend { 222 | log.Printf("dialer %v finish UDP sending %v bytes %.4f MB/s", 223 | dialerNum, bytesSent, float64(bytesSent)/math.Pow(2, 20)/(float64(time.Since(timeStart))/float64(time.Second))) 224 | break 225 | } else { 226 | if ((bytesSent - n) * 10 / bytesToSend) != (bytesSent * 10 / bytesToSend) { 227 | log.Printf("dialer %v sent %v bytes %.4f MB/s", dialerNum, bytesSent, 228 | float64(bytesSent)/math.Pow(2, 20)/(float64(time.Since(timeStart))/float64(time.Second))) 229 | } 230 | } 231 | 232 | b := make([]byte, 1024) 233 | n, _, err = udpSess.ReadFrom(b) 234 | if err != nil { 235 | log.Printf("dialer %v ReadFrom err: %v", dialerNum, err) 236 | break 237 | } 238 | if string(b[:n]) != msgs[dialerNum] { 239 | log.Printf("dialer %v Read %v is not as same as sent %v ", dialerNum, string(b[:n]), msgs[dialerNum]) 240 | break 241 | } 242 | time.Sleep(writeInterval) 243 | } 244 | return nil 245 | } 246 | -------------------------------------------------------------------------------- /tests/tcp_test.go: -------------------------------------------------------------------------------- 1 | package tests 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "log" 7 | "math" 8 | "net" 9 | "testing" 10 | "time" 11 | 12 | "github.com/nknorg/ncp-go" 13 | ts "github.com/nknorg/nkn-tuna-session" 14 | ) 15 | 16 | // status of listener and dialer 17 | const ( 18 | listening = string("listening") 19 | accepted = string("accepted") 20 | dialed = string("dialed") 21 | end = string("end") 22 | ) 23 | 24 | // sync listener and dialer 25 | func waitfor(ch chan string, result string) { 26 | for { 27 | str := <-ch 28 | if str == result { 29 | break 30 | } 31 | } 32 | } 33 | 34 | // go test -v -run=TestNormalListener 35 | func TestNormalListener(t *testing.T) { 36 | ch := make(chan string, 1) 37 | 38 | go func() { 39 | StartTunaTcpListener(numTcpListener, ch) 40 | }() 41 | 42 | waitfor(ch, end) 43 | } 44 | 45 | // go test -v -run=TestNormalDialer 46 | func TestNormalDialer(t *testing.T) { 47 | ch := make(chan string, 1) 48 | 49 | go func() { 50 | // wait for Listener be ready 51 | time.Sleep(2 * time.Second) 52 | StartTunaTcpDialer(bytesToSend, numTcpListener, ch) 53 | }() 54 | 55 | waitfor(ch, end) 56 | } 57 | 58 | // go test -v -run=TestCloseOneConnListener 59 | func TestCloseOneConnListener(t *testing.T) { 60 | var tunaSess *ts.TunaSessionClient 61 | var ncpSess *ncp.Session 62 | ch := make(chan string, 1) 63 | 64 | go func() { 65 | tunaSess, ncpSess = StartTunaTcpListener(numTcpListener, ch) 66 | }() 67 | 68 | waitfor(ch, accepted) 69 | time.Sleep(3 * time.Second) 70 | tunaSess.CloseOneConn(ncpSess, "2") 71 | 72 | waitfor(ch, end) 73 | } 74 | 75 | // go test -v -run=TestCloseOneConnDialer 76 | func TestCloseOneConnDialer(t *testing.T) { 77 | var tunaSess *ts.TunaSessionClient 78 | var ncpSess *ncp.Session 79 | ch := make(chan string, 1) 80 | 81 | go func() { 82 | // wait for Listener be ready 83 | time.Sleep(2 * time.Second) 84 | tunaSess, ncpSess = StartTunaTcpDialer(bytesToSend, numTcpListener, ch) 85 | }() 86 | 87 | waitfor(ch, dialed) 88 | time.Sleep(2 * time.Second) 89 | tunaSess.CloseOneConn(ncpSess, "1") 90 | 91 | waitfor(ch, end) 92 | } 93 | 94 | // go test -v -run=TestCloseAllConnDialer 95 | func TestCloseAllConnDialer(t *testing.T) { 96 | var tunaSess *ts.TunaSessionClient 97 | var ncpSess *ncp.Session 98 | ch := make(chan string, 1) 99 | 100 | go func() { 101 | // wait for Listener be ready 102 | time.Sleep(2 * time.Second) 103 | tunaSess, ncpSess = StartTunaTcpDialer(bytesToSend, numTcpListener, ch) 104 | }() 105 | 106 | waitfor(ch, dialed) 107 | time.Sleep(2 * time.Second) 108 | tunaSess.CloseOneConn(ncpSess, "0") 109 | time.Sleep(2 * time.Second) 110 | tunaSess.CloseOneConn(ncpSess, "1") 111 | time.Sleep(2 * time.Second) 112 | tunaSess.CloseOneConn(ncpSess, "2") 113 | time.Sleep(2 * time.Second) 114 | tunaSess.CloseOneConn(ncpSess, "3") 115 | 116 | waitfor(ch, end) 117 | } 118 | 119 | func readTcp(sess net.Conn) error { 120 | timeStart := time.Now() 121 | 122 | b := make([]byte, 4) 123 | n := 0 124 | for { 125 | m, err := sess.Read(b[n:]) 126 | if err != nil { 127 | return err 128 | } 129 | n += m 130 | if n == 4 { 131 | break 132 | } 133 | } 134 | 135 | numBytes := int(binary.LittleEndian.Uint32(b)) 136 | 137 | b = make([]byte, 1024) 138 | bytesReceived := 0 139 | for { 140 | n, err := sess.Read(b) 141 | if err != nil { 142 | return err 143 | } 144 | for i := 0; i < n; i++ { 145 | if b[i] != byte(bytesReceived%256) { 146 | return fmt.Errorf("byte %d should be %d, got %d", bytesReceived, bytesReceived%256, b[i]) 147 | } 148 | bytesReceived++ 149 | } 150 | if ((bytesReceived - n) * 10 / numBytes) != (bytesReceived * 10 / numBytes) { 151 | log.Println("Received", bytesReceived, "bytes", float64(bytesReceived)/math.Pow(2, 20)/(float64(time.Since(timeStart))/float64(time.Second)), "MB/s") 152 | } 153 | if bytesReceived == numBytes { 154 | log.Println("Finish receiving", bytesReceived, "bytes") 155 | return nil 156 | } 157 | } 158 | } 159 | 160 | func StartTunaTcpListener(numListener int, ch chan string) (tunaSess *ts.TunaSessionClient, ncpSess *ncp.Session) { 161 | acc, wal, err := CreateAccountAndWallet(seedHex) 162 | if err != nil { 163 | log.Fatal("CreateAccountAndWallet err: ", err) 164 | } 165 | mc, err := CreateMultiClient(acc, listenerId, 2) 166 | if err != nil { 167 | log.Fatal("CreateMultiClient err: ", err) 168 | } 169 | tunaSess, err = CreateTunaSession(acc, wal, mc, numListener) 170 | if err != nil { 171 | log.Fatal("CreateTunaSession err: ", err) 172 | } 173 | 174 | err = tunaSess.Listen(nil) 175 | if err != nil { 176 | log.Fatal("tunaSess.Listen ", err) 177 | } 178 | log.Printf("tcp listener is listening...") 179 | ch <- listening 180 | 181 | go func() { 182 | for { 183 | sess, err := tunaSess.Accept() 184 | if err != nil { 185 | log.Fatal("tunaSess.Accept ", err) 186 | } 187 | ncpSess = sess.(*ncp.Session) 188 | log.Printf("tcp listener accepted a new connection...") 189 | ch <- accepted 190 | 191 | go func() { 192 | err = readTcp(ncpSess) 193 | if err != nil { 194 | log.Printf("StartTunaListner read err:%v\n", err) 195 | } else { 196 | log.Printf("Finished reading, close ncp.session now\n") 197 | } 198 | ncpSess.Close() 199 | 200 | log.Printf("tcp listener finish job, exit now...") 201 | ch <- end 202 | }() 203 | } 204 | }() 205 | 206 | return 207 | } 208 | 209 | func StartTunaTcpDialer(numBytes int, numListener int, ch chan string) (tunaSess *ts.TunaSessionClient, ncpSess *ncp.Session) { 210 | acc, wal, err := CreateAccountAndWallet(seedHex) 211 | if err != nil { 212 | log.Fatal("CreateAccountAndWallet err: ", err) 213 | } 214 | mc, err := CreateMultiClient(acc, dialerId, 2) 215 | if err != nil { 216 | log.Fatal("CreateMultiClient err: ", err) 217 | } 218 | 219 | tunaSess, err = CreateTunaSession(acc, wal, mc, numListener) 220 | if err != nil { 221 | log.Fatal("CreateTunaSession err: ", err) 222 | } 223 | 224 | diaConfig := CreateDialConfig(5000) 225 | ncpSess, err = tunaSess.DialWithConfig(remoteAddr, diaConfig) 226 | if err != nil { 227 | log.Fatal("tunaSess.DialWithConfig ", err) 228 | } 229 | ch <- dialed 230 | 231 | go func() { 232 | err = writeTcp(ncpSess, numBytes) 233 | if err != nil { 234 | log.Printf("StartTunaDialer write err:%v\n", err) 235 | } else { 236 | log.Printf("Finished writing, close ncp.session now\n") 237 | } 238 | time.Sleep(time.Second) // wait for reader to read data. 239 | ncpSess.Close() 240 | ch <- end 241 | }() 242 | 243 | return 244 | } 245 | 246 | func writeTcp(sess net.Conn, numBytes int) error { 247 | timeStart := time.Now() 248 | 249 | b := make([]byte, 4) 250 | binary.LittleEndian.PutUint32(b, uint32(numBytes)) 251 | _, err := sess.Write(b) 252 | if err != nil { 253 | return err 254 | } 255 | 256 | bytesSent := 0 257 | for i := 0; i < numBytes/1024; i++ { 258 | b := make([]byte, 1024) 259 | for j := 0; j < len(b); j++ { 260 | b[j] = byte(bytesSent % 256) 261 | bytesSent++ 262 | } 263 | n, err := sess.Write(b) 264 | if err != nil { 265 | return err 266 | } 267 | if n != len(b) { 268 | return fmt.Errorf("sent %d instead of %d bytes", n, len(b)) 269 | } 270 | 271 | if bytesSent == numBytes { 272 | log.Println("Finish sending", bytesSent, "bytes", float64(bytesSent)/math.Pow(2, 20)/(float64(time.Since(timeStart))/float64(time.Second)), "MB/s") 273 | break 274 | } else { 275 | if ((bytesSent - n) * 10 / numBytes) != (bytesSent * 10 / numBytes) { 276 | log.Println("Sent", bytesSent, "bytes", float64(bytesSent)/math.Pow(2, 20)/(float64(time.Since(timeStart))/float64(time.Second)), "MB/s") 277 | // slow down for testing disconnect and reconnect 278 | time.Sleep(2 * time.Second) 279 | } 280 | } 281 | } 282 | return nil 283 | } 284 | -------------------------------------------------------------------------------- /examples/throughput/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rand" 5 | "encoding/binary" 6 | "encoding/hex" 7 | "flag" 8 | "fmt" 9 | "log" 10 | "math" 11 | "net" 12 | "os" 13 | "strings" 14 | "time" 15 | 16 | "github.com/nknorg/ncp-go" 17 | "github.com/nknorg/nkn-sdk-go" 18 | ts "github.com/nknorg/nkn-tuna-session" 19 | "github.com/nknorg/tuna/geo" 20 | ) 21 | 22 | const ( 23 | dialID = "alice" 24 | listenID = "bob" 25 | ) 26 | 27 | var udpBytesReceived = 0 28 | var udpBytesSent = 0 29 | 30 | func read(sess net.Conn) error { 31 | timeStart := time.Now() 32 | 33 | b := make([]byte, 4) 34 | n := 0 35 | for { 36 | m, err := sess.Read(b[n:]) 37 | if err != nil { 38 | return err 39 | } 40 | n += m 41 | if n == 4 { 42 | break 43 | } 44 | } 45 | 46 | numBytes := int(binary.LittleEndian.Uint32(b)) 47 | 48 | b = make([]byte, 1024) 49 | bytesReceived := 0 50 | for { 51 | n, err := sess.Read(b) 52 | if err != nil { 53 | return err 54 | } 55 | for i := 0; i < n; i++ { 56 | if b[i] != byte(bytesReceived%256) { 57 | return fmt.Errorf("byte %d should be %d, got %d", bytesReceived, bytesReceived%256, b[i]) 58 | } 59 | bytesReceived++ 60 | } 61 | if ((bytesReceived - n) * 10 / numBytes) != (bytesReceived * 10 / numBytes) { 62 | log.Println("Received", bytesReceived, "bytes", float64(bytesReceived)/math.Pow(2, 20)/(float64(time.Since(timeStart))/float64(time.Second)), "MB/s") 63 | } 64 | if bytesReceived == numBytes { 65 | log.Println("Finished receiving", bytesReceived, "bytes") 66 | return nil 67 | } 68 | } 69 | } 70 | 71 | func write(sess net.Conn, numBytes int) error { 72 | timeStart := time.Now() 73 | 74 | b := make([]byte, 4) 75 | binary.LittleEndian.PutUint32(b, uint32(numBytes)) 76 | _, err := sess.Write(b) 77 | if err != nil { 78 | return err 79 | } 80 | 81 | bytesSent := 0 82 | for i := 0; i < numBytes/1024; i++ { 83 | b := make([]byte, 1024) 84 | for j := 0; j < len(b); j++ { 85 | b[j] = byte(bytesSent % 256) 86 | bytesSent++ 87 | } 88 | n, err := sess.Write(b) 89 | if err != nil { 90 | return err 91 | } 92 | if n != len(b) { 93 | return fmt.Errorf("sent %d instead of %d bytes", n, len(b)) 94 | } 95 | if ((bytesSent - n) * 10 / numBytes) != (bytesSent * 10 / numBytes) { 96 | log.Println("Sent", bytesSent, "bytes", float64(bytesSent)/math.Pow(2, 20)/(float64(time.Since(timeStart))/float64(time.Second)), "MB/s") 97 | } 98 | } 99 | return nil 100 | } 101 | 102 | func readUDP(conn *ts.UdpSession, numBytes int) error { 103 | defer conn.Close() 104 | buffer := make([]byte, 1024) 105 | var timeStart time.Time 106 | defer func() { 107 | if udpBytesReceived > 0 { 108 | mbTobytes := math.Pow(2, 20) 109 | sent := float64(udpBytesSent) / mbTobytes 110 | received := float64(udpBytesReceived) / mbTobytes 111 | speed := received / time.Since(timeStart).Seconds() 112 | log.Printf("UDP: Received %.2f MB bytes, speed: %.2f MB/s, package loss: %.2f%% \n", received, speed, 100*(1-received/sent)) 113 | } 114 | }() 115 | for { 116 | err := conn.SetReadDeadline(time.Now().Add(30 * time.Second)) 117 | if err != nil { 118 | return err 119 | } 120 | n, _, err := conn.ReadFrom(buffer) 121 | if udpBytesReceived == 0 { 122 | timeStart = time.Now() 123 | } 124 | if err != nil { 125 | return err 126 | } 127 | udpBytesReceived += n 128 | if ((udpBytesReceived - n) * 10 / numBytes) != (udpBytesReceived * 10 / numBytes) { 129 | mbTobytes := math.Pow(2, 20) 130 | received := float64(udpBytesReceived) / mbTobytes 131 | speed := received / time.Since(timeStart).Seconds() 132 | log.Printf("UDP: Received %.2f MB bytes, speed: %.2f MB/s\n", received, speed) 133 | } 134 | if udpBytesReceived >= numBytes { 135 | return nil 136 | } 137 | } 138 | } 139 | 140 | func writeUDP(conn *ts.UdpSession, numBytes int) error { 141 | defer conn.Close() 142 | buffer := make([]byte, 1024) 143 | timeStart := time.Now() 144 | for { 145 | rand.Read(buffer) 146 | n, err := conn.WriteTo(buffer, nil) 147 | if err != nil { 148 | return err 149 | } 150 | udpBytesSent += n 151 | if ((udpBytesSent - n) * 10 / numBytes) != (udpBytesSent * 10 / numBytes) { 152 | mbTobytes := math.Pow(2, 20) 153 | sent := float64(udpBytesSent) / mbTobytes 154 | speed := sent / time.Since(timeStart).Seconds() 155 | log.Printf("UDP: Sent %.2f MB bytes, speed: %.2f MB/s\n", sent, speed) 156 | } 157 | if udpBytesSent >= numBytes { 158 | break 159 | } 160 | time.Sleep(10 * time.Millisecond) 161 | } 162 | 163 | return nil 164 | } 165 | 166 | func main() { 167 | numTunaListeners := flag.Int("n", 1, "number of tuna listeners") 168 | numBytes := flag.Int("m", 1, "data to send (MB)") 169 | numClients := flag.Int("c", 4, "number of clients") 170 | seedHex := flag.String("s", "", "secret seed") 171 | dialAddr := flag.String("a", "", "dial address") 172 | dial := flag.Bool("d", false, "dial") 173 | listen := flag.Bool("l", false, "listen") 174 | tunaCountry := flag.String("country", "", `tuna service node allowed country code, separated by comma, e.g. "US" or "US,CN"`) 175 | tunaServiceName := flag.String("tsn", "", "tuna reverse service name") 176 | tunaSubscriptionPrefix := flag.String("tsp", "", "tuna subscription prefix") 177 | tunaMeasureBandwidth := flag.Bool("tmb", false, "tuna measure bandwidth") 178 | tunaMeasurementBytesDownLink := flag.Int("tmbd", 1, "tuna measure bandwidth downlink in bytes") 179 | tunaMaxPrice := flag.String("price", "0.01", "tuna reverse service max price in unit of NKN/MB") 180 | mtu := flag.Int("mtu", 0, "ncp session mtu") 181 | u := flag.Bool("u", false, "send data through UDP instead TCP") 182 | 183 | flag.Parse() 184 | 185 | *numBytes *= 1 << 20 186 | 187 | seed, err := hex.DecodeString(*seedHex) 188 | if err != nil { 189 | log.Fatal(err) 190 | } 191 | 192 | countries := strings.Split(*tunaCountry, ",") 193 | locations := make([]geo.Location, len(countries)) 194 | for i := range countries { 195 | locations[i].CountryCode = strings.TrimSpace(countries[i]) 196 | } 197 | 198 | account, err := nkn.NewAccount(seed) 199 | if err != nil { 200 | log.Fatal(err) 201 | } 202 | 203 | wallet, err := nkn.NewWallet(account, nil) 204 | if err != nil { 205 | log.Fatal(err) 206 | } 207 | 208 | log.Println("Seed:", hex.EncodeToString(account.Seed())) 209 | 210 | clientConfig := &nkn.ClientConfig{ConnectRetries: 1} 211 | dialConfig := &nkn.DialConfig{DialTimeout: 5000} 212 | config := &ts.Config{ 213 | NumTunaListeners: *numTunaListeners, 214 | TunaServiceName: *tunaServiceName, 215 | TunaSubscriptionPrefix: *tunaSubscriptionPrefix, 216 | TunaMeasureBandwidth: *tunaMeasureBandwidth, 217 | TunaMeasurementBytesDownLink: int32(*tunaMeasurementBytesDownLink), 218 | TunaMaxPrice: *tunaMaxPrice, 219 | TunaIPFilter: &geo.IPFilter{Allow: locations}, 220 | SessionConfig: &ncp.Config{MTU: int32(*mtu)}, 221 | } 222 | 223 | if *listen { 224 | m, err := nkn.NewMultiClient(account, listenID, *numClients, false, clientConfig) 225 | if err != nil { 226 | log.Fatal(err) 227 | } 228 | 229 | <-m.OnConnect.C 230 | 231 | c, err := ts.NewTunaSessionClient(account, m, wallet, config) 232 | if err != nil { 233 | log.Fatal(err) 234 | } 235 | 236 | err = c.Listen(nil) 237 | if err != nil { 238 | log.Fatal(err) 239 | } 240 | log.Println("Listening at", c.Addr()) 241 | 242 | if *u { 243 | uConn, err := c.ListenUDP() 244 | if err != nil { 245 | log.Fatal(err) 246 | } 247 | log.Println("Listening UDP at", c.Addr()) 248 | go func() { 249 | err = readUDP(uConn, *numBytes) 250 | if err != nil { 251 | log.Fatal(err) 252 | } 253 | os.Exit(0) 254 | }() 255 | } else { 256 | go func() { 257 | for { 258 | s, err := c.Accept() 259 | if err != nil { 260 | log.Fatal(err) 261 | } 262 | log.Println(c.Addr(), "accepted a session") 263 | 264 | go func(s net.Conn) { 265 | err := read(s) 266 | if err != nil { 267 | log.Fatal(err) 268 | } 269 | s.Close() 270 | }(s) 271 | } 272 | }() 273 | } 274 | <-c.OnConnect() 275 | } 276 | 277 | if *dial { 278 | m, err := nkn.NewMultiClient(account, dialID, *numClients, false, clientConfig) 279 | if err != nil { 280 | log.Fatal(err) 281 | } 282 | 283 | <-m.OnConnect.C 284 | time.Sleep(10 * time.Second) 285 | 286 | c, err := ts.NewTunaSessionClient(account, m, wallet, config) 287 | if err != nil { 288 | log.Fatal(err) 289 | } 290 | 291 | if len(*dialAddr) == 0 { 292 | *dialAddr = listenID + "." + strings.SplitN(c.Addr().String(), ".", 2)[1] 293 | } 294 | 295 | if *u { 296 | udpConn, err := c.DialUDPWithConfig(*dialAddr, dialConfig) 297 | if err != nil { 298 | log.Fatal(err) 299 | } 300 | log.Println(c.Addr(), "dialed a UDP session") 301 | go func() { 302 | err := writeUDP(udpConn, *numBytes) 303 | if err != nil { 304 | log.Fatal(err) 305 | } 306 | }() 307 | } else { 308 | s, err := c.DialWithConfig(*dialAddr, dialConfig) 309 | if err != nil { 310 | log.Fatal(err) 311 | } 312 | log.Println(c.Addr(), "dialed a session") 313 | 314 | go func() { 315 | err := write(s, *numBytes) 316 | if err != nil { 317 | log.Fatal(err) 318 | } 319 | for { 320 | if s.IsClosed() { 321 | os.Exit(0) 322 | } 323 | time.Sleep(time.Millisecond * 100) 324 | } 325 | }() 326 | } 327 | } 328 | 329 | select {} 330 | } 331 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= 6 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= 7 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= 8 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= 9 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= 10 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 11 | github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= 12 | github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= 13 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 14 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 15 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 16 | github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= 17 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 18 | github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= 19 | github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 20 | github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= 21 | github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= 22 | github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= 23 | github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= 24 | github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= 25 | github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= 26 | github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= 27 | github.com/imdario/mergo v0.3.15 h1:M8XP7IuFNsqUx6VPK2P9OSmsYsI/YFaGil0uD21V3dM= 28 | github.com/imdario/mergo v0.3.15/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= 29 | github.com/itchyny/base58-go v0.2.1 h1:wtnhAVdOcW3WuHEASmGHMms4juOB8yEpj/KJxlB57+k= 30 | github.com/itchyny/base58-go v0.2.1/go.mod h1:BNvrKeAtWNSca1GohNbyhfff9/v0IrZjzWCAGeAvZZE= 31 | github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA= 32 | github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= 33 | github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= 34 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 35 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 36 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 37 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 38 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 39 | github.com/nknorg/encrypted-stream v1.0.2-0.20230320101720-9891f770de86 h1:YraQ9G+P/DibBBVsLbfLatsDUngiCA0JWVkL1bzECAE= 40 | github.com/nknorg/encrypted-stream v1.0.2-0.20230320101720-9891f770de86/go.mod h1:VXJDhlUoF3uJSFLwIWnRLkiX5QPFB3E8oe2EUBwPoU0= 41 | github.com/nknorg/mockconn-go v0.0.0-20230125231524-d664e728352a/go.mod h1:/SvBORYxt9wlm8ZbaEFEri6ooOSDcU3ovU0L2eRRdS4= 42 | github.com/nknorg/ncp-go v1.0.6-0.20230228002512-f4cd1740bebd h1:ZAXKeWKjkbS9QQhrOCNYEbNIIF7tOXfDVHQijvEY6VE= 43 | github.com/nknorg/ncp-go v1.0.6-0.20230228002512-f4cd1740bebd/go.mod h1:T7ThlxmBjVIv3Ll3gJOHbQTuAFN3ZCYWvbux6JOX5wQ= 44 | github.com/nknorg/nkn-sdk-go v1.4.6-0.20230404044330-ad192f36d07e h1:lWKUEfqOJ9NImCX60Bden+Y6VgRDhlx4gc6B09S32RQ= 45 | github.com/nknorg/nkn-sdk-go v1.4.6-0.20230404044330-ad192f36d07e/go.mod h1:mnI1+17p2cI+5wv+3CWRyCjSALqUg5k1jTaWC2h0f/M= 46 | github.com/nknorg/nkn/v2 v2.2.0 h1:sXOawvVF/T3bBTuWbzBCyrGuxldA3be+f+BDjoWcOEA= 47 | github.com/nknorg/nkn/v2 v2.2.0/go.mod h1:yv3jkg0aOtN9BDHS4yerNSZJtJNBfGvlaD5K6wL6U3E= 48 | github.com/nknorg/nkngomobile v0.0.0-20220615081414-671ad1afdfa9 h1:Gr37j7Ttvcn8g7TdC5fs6Y6IJKdmfqCvj03UbsrS77o= 49 | github.com/nknorg/nkngomobile v0.0.0-20220615081414-671ad1afdfa9/go.mod h1:zNY9NCyBcJCCDrXhwOjKarkW5cngPs/Z82xVNy/wvEA= 50 | github.com/nknorg/tuna v0.0.0-20230818024750-e800a743f680 h1:+/9LBklqtjV3bo0OJ85wIcmINm0eelcR9uVk5lqE2iU= 51 | github.com/nknorg/tuna v0.0.0-20230818024750-e800a743f680/go.mod h1:Ngge8vIVM0DPmy6xCT19/zXR3y7FsgiWsyX4V+Uq848= 52 | github.com/oschwald/geoip2-golang v1.4.0 h1:5RlrjCgRyIGDz/mBmPfnAF4h8k0IAcRv9PvrpOfz+Ug= 53 | github.com/oschwald/geoip2-golang v1.4.0/go.mod h1:8QwxJvRImBH+Zl6Aa6MaIcs5YdlZSTKtzmPGzQqi9ng= 54 | github.com/oschwald/maxminddb-golang v1.6.0 h1:KAJSjdHQ8Kv45nFIbtoLGrGWqHFajOIm7skTyz/+Dls= 55 | github.com/oschwald/maxminddb-golang v1.6.0/go.mod h1:DUJFucBg2cvqx42YmDa/+xHvb0elJtOm3o4aFQ/nb/w= 56 | github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= 57 | github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= 58 | github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0= 59 | github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y= 60 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 61 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 62 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 63 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 64 | github.com/rdegges/go-ipify v0.0.0-20150526035502-2d94a6a86c40 h1:31Y7UZ1yTYBU4E79CE52I/1IRi3TqiuwquXGNtZDXWs= 65 | github.com/rdegges/go-ipify v0.0.0-20150526035502-2d94a6a86c40/go.mod h1:j4c6zEU0eMG1oiZPUy+zD4ykX0NIpjZAEOEAviTWC18= 66 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 67 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 68 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 69 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 70 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 71 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 72 | github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= 73 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 74 | github.com/xtaci/smux v2.0.1+incompatible h1:4NrCD5VzuFktMCxK08IShR0C5vKyNICJRShUzvk0U34= 75 | github.com/xtaci/smux v2.0.1+incompatible/go.mod h1:f+nYm6SpuHMy/SH0zpbvAFHT1QoMcgLOsWcFip5KfPw= 76 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 77 | golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 78 | golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= 79 | golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= 80 | golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c h1:Gk61ECugwEHL6IiyyNLXNzmu8XslmRP2dS0xjIYhbb4= 81 | golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c/go.mod h1:aAjjkJNdrh3PMckS4B10TGS2nag27cbKR1y2BpUxsiY= 82 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 83 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 84 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 85 | golang.org/x/sys v0.0.0-20191224085550-c709ea063b76/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 86 | golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= 87 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 88 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 89 | golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 90 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 91 | golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df h1:5Pf6pFKu98ODmgnpvkJ3kFUOQGGLIzLIkbzUHp47618= 92 | golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= 93 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= 94 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= 95 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= 96 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= 97 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= 98 | google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= 99 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 100 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= 101 | google.golang.org/protobuf v1.29.1 h1:7QBf+IK2gx70Ap/hDsOmam3GE0v9HicjfEdAxE62UoM= 102 | google.golang.org/protobuf v1.29.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 103 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 104 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 105 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 106 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 107 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 108 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 109 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 110 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 111 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /pb/session.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // versions: 3 | // protoc-gen-go v1.28.1 4 | // protoc v3.21.1 5 | // source: pb/session.proto 6 | 7 | package pb 8 | 9 | import ( 10 | protoreflect "google.golang.org/protobuf/reflect/protoreflect" 11 | protoimpl "google.golang.org/protobuf/runtime/protoimpl" 12 | reflect "reflect" 13 | sync "sync" 14 | ) 15 | 16 | const ( 17 | // Verify that this generated code is sufficiently up-to-date. 18 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) 19 | // Verify that runtime/protoimpl is sufficiently up-to-date. 20 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) 21 | ) 22 | 23 | type SessionType int32 24 | 25 | const ( 26 | SessionType_ST_NONE SessionType = 0 27 | SessionType_TCP SessionType = 1 28 | SessionType_UDP SessionType = 2 29 | ) 30 | 31 | // Enum value maps for SessionType. 32 | var ( 33 | SessionType_name = map[int32]string{ 34 | 0: "ST_NONE", 35 | 1: "TCP", 36 | 2: "UDP", 37 | } 38 | SessionType_value = map[string]int32{ 39 | "ST_NONE": 0, 40 | "TCP": 1, 41 | "UDP": 2, 42 | } 43 | ) 44 | 45 | func (x SessionType) Enum() *SessionType { 46 | p := new(SessionType) 47 | *p = x 48 | return p 49 | } 50 | 51 | func (x SessionType) String() string { 52 | return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) 53 | } 54 | 55 | func (SessionType) Descriptor() protoreflect.EnumDescriptor { 56 | return file_pb_session_proto_enumTypes[0].Descriptor() 57 | } 58 | 59 | func (SessionType) Type() protoreflect.EnumType { 60 | return &file_pb_session_proto_enumTypes[0] 61 | } 62 | 63 | func (x SessionType) Number() protoreflect.EnumNumber { 64 | return protoreflect.EnumNumber(x) 65 | } 66 | 67 | // Deprecated: Use SessionType.Descriptor instead. 68 | func (SessionType) EnumDescriptor() ([]byte, []int) { 69 | return file_pb_session_proto_rawDescGZIP(), []int{0} 70 | } 71 | 72 | type HeaderType int32 73 | 74 | const ( 75 | HeaderType_HT_NONE HeaderType = 0 76 | HeaderType_SESSION HeaderType = 1 77 | HeaderType_USER HeaderType = 2 78 | ) 79 | 80 | // Enum value maps for HeaderType. 81 | var ( 82 | HeaderType_name = map[int32]string{ 83 | 0: "HT_NONE", 84 | 1: "SESSION", 85 | 2: "USER", 86 | } 87 | HeaderType_value = map[string]int32{ 88 | "HT_NONE": 0, 89 | "SESSION": 1, 90 | "USER": 2, 91 | } 92 | ) 93 | 94 | func (x HeaderType) Enum() *HeaderType { 95 | p := new(HeaderType) 96 | *p = x 97 | return p 98 | } 99 | 100 | func (x HeaderType) String() string { 101 | return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) 102 | } 103 | 104 | func (HeaderType) Descriptor() protoreflect.EnumDescriptor { 105 | return file_pb_session_proto_enumTypes[1].Descriptor() 106 | } 107 | 108 | func (HeaderType) Type() protoreflect.EnumType { 109 | return &file_pb_session_proto_enumTypes[1] 110 | } 111 | 112 | func (x HeaderType) Number() protoreflect.EnumNumber { 113 | return protoreflect.EnumNumber(x) 114 | } 115 | 116 | // Deprecated: Use HeaderType.Descriptor instead. 117 | func (HeaderType) EnumDescriptor() ([]byte, []int) { 118 | return file_pb_session_proto_rawDescGZIP(), []int{1} 119 | } 120 | 121 | type MsgType int32 122 | 123 | const ( 124 | MsgType_MT_NONE MsgType = 0 125 | MsgType_REMOTEADDR MsgType = 1 126 | MsgType_SESSIONID MsgType = 2 127 | MsgType_CLOSE MsgType = 255 128 | ) 129 | 130 | // Enum value maps for MsgType. 131 | var ( 132 | MsgType_name = map[int32]string{ 133 | 0: "MT_NONE", 134 | 1: "REMOTEADDR", 135 | 2: "SESSIONID", 136 | 255: "CLOSE", 137 | } 138 | MsgType_value = map[string]int32{ 139 | "MT_NONE": 0, 140 | "REMOTEADDR": 1, 141 | "SESSIONID": 2, 142 | "CLOSE": 255, 143 | } 144 | ) 145 | 146 | func (x MsgType) Enum() *MsgType { 147 | p := new(MsgType) 148 | *p = x 149 | return p 150 | } 151 | 152 | func (x MsgType) String() string { 153 | return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) 154 | } 155 | 156 | func (MsgType) Descriptor() protoreflect.EnumDescriptor { 157 | return file_pb_session_proto_enumTypes[2].Descriptor() 158 | } 159 | 160 | func (MsgType) Type() protoreflect.EnumType { 161 | return &file_pb_session_proto_enumTypes[2] 162 | } 163 | 164 | func (x MsgType) Number() protoreflect.EnumNumber { 165 | return protoreflect.EnumNumber(x) 166 | } 167 | 168 | // Deprecated: Use MsgType.Descriptor instead. 169 | func (MsgType) EnumDescriptor() ([]byte, []int) { 170 | return file_pb_session_proto_rawDescGZIP(), []int{2} 171 | } 172 | 173 | type SessionMetadata struct { 174 | state protoimpl.MessageState 175 | sizeCache protoimpl.SizeCache 176 | unknownFields protoimpl.UnknownFields 177 | 178 | Id []byte `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` 179 | SessionType SessionType `protobuf:"varint,2,opt,name=sessionType,proto3,enum=pb.SessionType" json:"sessionType,omitempty"` 180 | DialerNknAddr string `protobuf:"bytes,3,opt,name=dialerNknAddr,proto3" json:"dialerNknAddr,omitempty"` 181 | } 182 | 183 | func (x *SessionMetadata) Reset() { 184 | *x = SessionMetadata{} 185 | if protoimpl.UnsafeEnabled { 186 | mi := &file_pb_session_proto_msgTypes[0] 187 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 188 | ms.StoreMessageInfo(mi) 189 | } 190 | } 191 | 192 | func (x *SessionMetadata) String() string { 193 | return protoimpl.X.MessageStringOf(x) 194 | } 195 | 196 | func (*SessionMetadata) ProtoMessage() {} 197 | 198 | func (x *SessionMetadata) ProtoReflect() protoreflect.Message { 199 | mi := &file_pb_session_proto_msgTypes[0] 200 | if protoimpl.UnsafeEnabled && x != nil { 201 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 202 | if ms.LoadMessageInfo() == nil { 203 | ms.StoreMessageInfo(mi) 204 | } 205 | return ms 206 | } 207 | return mi.MessageOf(x) 208 | } 209 | 210 | // Deprecated: Use SessionMetadata.ProtoReflect.Descriptor instead. 211 | func (*SessionMetadata) Descriptor() ([]byte, []int) { 212 | return file_pb_session_proto_rawDescGZIP(), []int{0} 213 | } 214 | 215 | func (x *SessionMetadata) GetId() []byte { 216 | if x != nil { 217 | return x.Id 218 | } 219 | return nil 220 | } 221 | 222 | func (x *SessionMetadata) GetSessionType() SessionType { 223 | if x != nil { 224 | return x.SessionType 225 | } 226 | return SessionType_ST_NONE 227 | } 228 | 229 | func (x *SessionMetadata) GetDialerNknAddr() string { 230 | if x != nil { 231 | return x.DialerNknAddr 232 | } 233 | return "" 234 | } 235 | 236 | type SessionData struct { 237 | state protoimpl.MessageState 238 | sizeCache protoimpl.SizeCache 239 | unknownFields protoimpl.UnknownFields 240 | 241 | MsgType MsgType `protobuf:"varint,1,opt,name=msgType,proto3,enum=pb.MsgType" json:"msgType,omitempty"` 242 | Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` 243 | } 244 | 245 | func (x *SessionData) Reset() { 246 | *x = SessionData{} 247 | if protoimpl.UnsafeEnabled { 248 | mi := &file_pb_session_proto_msgTypes[1] 249 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 250 | ms.StoreMessageInfo(mi) 251 | } 252 | } 253 | 254 | func (x *SessionData) String() string { 255 | return protoimpl.X.MessageStringOf(x) 256 | } 257 | 258 | func (*SessionData) ProtoMessage() {} 259 | 260 | func (x *SessionData) ProtoReflect() protoreflect.Message { 261 | mi := &file_pb_session_proto_msgTypes[1] 262 | if protoimpl.UnsafeEnabled && x != nil { 263 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 264 | if ms.LoadMessageInfo() == nil { 265 | ms.StoreMessageInfo(mi) 266 | } 267 | return ms 268 | } 269 | return mi.MessageOf(x) 270 | } 271 | 272 | // Deprecated: Use SessionData.ProtoReflect.Descriptor instead. 273 | func (*SessionData) Descriptor() ([]byte, []int) { 274 | return file_pb_session_proto_rawDescGZIP(), []int{1} 275 | } 276 | 277 | func (x *SessionData) GetMsgType() MsgType { 278 | if x != nil { 279 | return x.MsgType 280 | } 281 | return MsgType_MT_NONE 282 | } 283 | 284 | func (x *SessionData) GetData() []byte { 285 | if x != nil { 286 | return x.Data 287 | } 288 | return nil 289 | } 290 | 291 | var File_pb_session_proto protoreflect.FileDescriptor 292 | 293 | var file_pb_session_proto_rawDesc = []byte{ 294 | 0x0a, 0x10, 0x70, 0x62, 0x2f, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 295 | 0x74, 0x6f, 0x12, 0x02, 0x70, 0x62, 0x22, 0x7a, 0x0a, 0x0f, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 296 | 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 297 | 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x31, 0x0a, 0x0b, 0x73, 0x65, 0x73, 298 | 0x73, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x0f, 299 | 0x2e, 0x70, 0x62, 0x2e, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x52, 300 | 0x0b, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x24, 0x0a, 0x0d, 301 | 0x64, 0x69, 0x61, 0x6c, 0x65, 0x72, 0x4e, 0x6b, 0x6e, 0x41, 0x64, 0x64, 0x72, 0x18, 0x03, 0x20, 302 | 0x01, 0x28, 0x09, 0x52, 0x0d, 0x64, 0x69, 0x61, 0x6c, 0x65, 0x72, 0x4e, 0x6b, 0x6e, 0x41, 0x64, 303 | 0x64, 0x72, 0x22, 0x48, 0x0a, 0x0b, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 304 | 0x61, 0x12, 0x25, 0x0a, 0x07, 0x6d, 0x73, 0x67, 0x54, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 305 | 0x28, 0x0e, 0x32, 0x0b, 0x2e, 0x70, 0x62, 0x2e, 0x4d, 0x73, 0x67, 0x54, 0x79, 0x70, 0x65, 0x52, 306 | 0x07, 0x6d, 0x73, 0x67, 0x54, 0x79, 0x70, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 307 | 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x2a, 0x2c, 0x0a, 0x0b, 308 | 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x53, 309 | 0x54, 0x5f, 0x4e, 0x4f, 0x4e, 0x45, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x54, 0x43, 0x50, 0x10, 310 | 0x01, 0x12, 0x07, 0x0a, 0x03, 0x55, 0x44, 0x50, 0x10, 0x02, 0x2a, 0x30, 0x0a, 0x0a, 0x48, 0x65, 311 | 0x61, 0x64, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x48, 0x54, 0x5f, 0x4e, 312 | 0x4f, 0x4e, 0x45, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x45, 0x53, 0x53, 0x49, 0x4f, 0x4e, 313 | 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x55, 0x53, 0x45, 0x52, 0x10, 0x02, 0x2a, 0x41, 0x0a, 0x07, 314 | 0x4d, 0x73, 0x67, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x4d, 0x54, 0x5f, 0x4e, 0x4f, 315 | 0x4e, 0x45, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x0a, 0x52, 0x45, 0x4d, 0x4f, 0x54, 0x45, 0x41, 0x44, 316 | 0x44, 0x52, 0x10, 0x01, 0x12, 0x0d, 0x0a, 0x09, 0x53, 0x45, 0x53, 0x53, 0x49, 0x4f, 0x4e, 0x49, 317 | 0x44, 0x10, 0x02, 0x12, 0x0a, 0x0a, 0x05, 0x43, 0x4c, 0x4f, 0x53, 0x45, 0x10, 0xff, 0x01, 0x42, 318 | 0x06, 0x5a, 0x04, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, 319 | } 320 | 321 | var ( 322 | file_pb_session_proto_rawDescOnce sync.Once 323 | file_pb_session_proto_rawDescData = file_pb_session_proto_rawDesc 324 | ) 325 | 326 | func file_pb_session_proto_rawDescGZIP() []byte { 327 | file_pb_session_proto_rawDescOnce.Do(func() { 328 | file_pb_session_proto_rawDescData = protoimpl.X.CompressGZIP(file_pb_session_proto_rawDescData) 329 | }) 330 | return file_pb_session_proto_rawDescData 331 | } 332 | 333 | var file_pb_session_proto_enumTypes = make([]protoimpl.EnumInfo, 3) 334 | var file_pb_session_proto_msgTypes = make([]protoimpl.MessageInfo, 2) 335 | var file_pb_session_proto_goTypes = []interface{}{ 336 | (SessionType)(0), // 0: pb.SessionType 337 | (HeaderType)(0), // 1: pb.HeaderType 338 | (MsgType)(0), // 2: pb.MsgType 339 | (*SessionMetadata)(nil), // 3: pb.SessionMetadata 340 | (*SessionData)(nil), // 4: pb.SessionData 341 | } 342 | var file_pb_session_proto_depIdxs = []int32{ 343 | 0, // 0: pb.SessionMetadata.sessionType:type_name -> pb.SessionType 344 | 2, // 1: pb.SessionData.msgType:type_name -> pb.MsgType 345 | 2, // [2:2] is the sub-list for method output_type 346 | 2, // [2:2] is the sub-list for method input_type 347 | 2, // [2:2] is the sub-list for extension type_name 348 | 2, // [2:2] is the sub-list for extension extendee 349 | 0, // [0:2] is the sub-list for field type_name 350 | } 351 | 352 | func init() { file_pb_session_proto_init() } 353 | func file_pb_session_proto_init() { 354 | if File_pb_session_proto != nil { 355 | return 356 | } 357 | if !protoimpl.UnsafeEnabled { 358 | file_pb_session_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { 359 | switch v := v.(*SessionMetadata); i { 360 | case 0: 361 | return &v.state 362 | case 1: 363 | return &v.sizeCache 364 | case 2: 365 | return &v.unknownFields 366 | default: 367 | return nil 368 | } 369 | } 370 | file_pb_session_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { 371 | switch v := v.(*SessionData); i { 372 | case 0: 373 | return &v.state 374 | case 1: 375 | return &v.sizeCache 376 | case 2: 377 | return &v.unknownFields 378 | default: 379 | return nil 380 | } 381 | } 382 | } 383 | type x struct{} 384 | out := protoimpl.TypeBuilder{ 385 | File: protoimpl.DescBuilder{ 386 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(), 387 | RawDescriptor: file_pb_session_proto_rawDesc, 388 | NumEnums: 3, 389 | NumMessages: 2, 390 | NumExtensions: 0, 391 | NumServices: 0, 392 | }, 393 | GoTypes: file_pb_session_proto_goTypes, 394 | DependencyIndexes: file_pb_session_proto_depIdxs, 395 | EnumInfos: file_pb_session_proto_enumTypes, 396 | MessageInfos: file_pb_session_proto_msgTypes, 397 | }.Build() 398 | File_pb_session_proto = out.File 399 | file_pb_session_proto_rawDesc = nil 400 | file_pb_session_proto_goTypes = nil 401 | file_pb_session_proto_depIdxs = nil 402 | } 403 | -------------------------------------------------------------------------------- /udpsession.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "context" 5 | "log" 6 | "net" 7 | "sync" 8 | "time" 9 | 10 | "github.com/nknorg/nkn-sdk-go" 11 | "github.com/nknorg/nkn-tuna-session/pb" 12 | "github.com/nknorg/tuna" 13 | tpb "github.com/nknorg/tuna/pb" 14 | "google.golang.org/protobuf/proto" 15 | ) 16 | 17 | // Wrap of UDPAddr, including session information 18 | // implement of net.Addr interface 19 | type udpSessionAddr struct { 20 | sessionID []byte 21 | remoteNknAddr string 22 | udpAddr *net.UDPAddr // peer udp address. 23 | } 24 | 25 | func newUdpSessionAddr(sessionID []byte, remoteNknAddr string, udpAddr *net.UDPAddr) *udpSessionAddr { 26 | return &udpSessionAddr{sessionID: sessionID, remoteNknAddr: remoteNknAddr, udpAddr: udpAddr} 27 | } 28 | func (usa *udpSessionAddr) Network() string { 29 | return "tsudp" 30 | } 31 | 32 | // Return session key 33 | func (usa *udpSessionAddr) String() string { 34 | return sessionKey(usa.remoteNknAddr, usa.sessionID) 35 | } 36 | 37 | type recvData struct { 38 | data []byte 39 | usa *udpSessionAddr 40 | } 41 | 42 | // UDP session, it is a UDP listener or dialer endpoint for reading and writing udp data. 43 | // After tuna session set up UDP connection, it return UpdSession to applications. 44 | // Applications use this end point to read and write data. 45 | // If there is a node break down between UDP listener and dialer, udp session will reconenct automatically 46 | // without interrupting application usage. 47 | type UdpSession struct { 48 | isListener bool // true for listener, false for dialer 49 | udpConn *tuna.EncryptUDPConn 50 | ts *TunaSessionClient // Reference of tuna session 51 | recvChan chan *recvData // recv buffer for user application recvFrom 52 | recvSize int // size of buffer received msg used 53 | readContext context.Context 54 | readCancel context.CancelFunc 55 | 56 | sync.RWMutex 57 | 58 | // dialer only 59 | tcpConn *Conn // TCP *Conn, dialer only 60 | peer *udpSessionAddr // dialer only 61 | 62 | // listener only 63 | sessKeyToSessAddr map[string]*udpSessionAddr // listener only, session key to to *udpSessionAddr 64 | udpAddrToSessAddr map[string]*udpSessionAddr // listener only, UDPAddr.String() to *udpSessionAddr 65 | tcpConns map[string]*Conn // listen only, session key to *Conn 66 | } 67 | 68 | func newUdpSession(ts *TunaSessionClient, isListener bool) *UdpSession { 69 | us := &UdpSession{ts: ts, isListener: isListener, recvChan: make(chan *recvData, ts.config.MaxUdpDatagramBuffered)} 70 | us.SetReadDeadline(zeroTime) 71 | 72 | if isListener { 73 | us.sessKeyToSessAddr = make(map[string]*udpSessionAddr) 74 | us.udpAddrToSessAddr = make(map[string]*udpSessionAddr) 75 | us.tcpConns = make(map[string]*Conn) 76 | } 77 | 78 | return us 79 | } 80 | 81 | func (us *UdpSession) DialUpSession(listenerNknAddr string, sessionID []byte, config *nkn.DialConfig) (err error) { 82 | if us.ts.isClosed { 83 | return ErrClosed 84 | } 85 | 86 | ctx := context.Background() 87 | var cancel context.CancelFunc 88 | if config.DialTimeout > 0 { 89 | ctx, cancel = context.WithTimeout(ctx, time.Duration(config.DialTimeout)*time.Millisecond) 90 | defer cancel() 91 | } 92 | 93 | pubAddrs, err := us.ts.getPubAddrsFromRemote(ctx, listenerNknAddr, sessionID) 94 | if err != nil { 95 | return err 96 | } 97 | 98 | udpConn, pubaddr, err := us.dialUdpConn(pubAddrs) 99 | if err != nil { 100 | return err 101 | } 102 | 103 | tcpConn, err := us.ts.dialTcpConn(ctx, listenerNknAddr, sessionID, pb.SessionType_UDP, -1, pubaddr, config) 104 | if err != nil { 105 | udpConn.Close() 106 | return err 107 | } 108 | 109 | udpAddr := &net.UDPAddr{IP: net.ParseIP(pubaddr.IP), Port: int(pubaddr.Port)} 110 | usa := newUdpSessionAddr(sessionID, listenerNknAddr, udpAddr) 111 | 112 | us.Lock() 113 | us.udpConn = udpConn 114 | us.tcpConn = tcpConn 115 | us.peer = usa 116 | us.Unlock() 117 | 118 | err = us.sendMetaData(sessionID) 119 | if err != nil { 120 | us.Close() 121 | return err 122 | } 123 | 124 | err = us.addCodec(udpAddr, listenerNknAddr) 125 | if err != nil { 126 | us.Close() 127 | return err 128 | } 129 | 130 | return nil 131 | } 132 | 133 | func (us *UdpSession) dialUdpConn(pubAddrs *PubAddrs) (udpConn *tuna.EncryptUDPConn, addr *PubAddr, err error) { 134 | var conn *net.UDPConn 135 | for _, addr = range pubAddrs.Addrs { 136 | if len(addr.IP) > 0 && addr.Port > 0 { 137 | udpAddr := &net.UDPAddr{IP: net.ParseIP(addr.IP), Port: int(addr.Port)} 138 | conn, err = net.DialUDP("udp", nil, udpAddr) 139 | if err != nil { 140 | log.Printf("dial udp %v:%v err: %v", addr.IP, addr.Port, err) 141 | continue 142 | } 143 | break 144 | } 145 | } 146 | if conn == nil { 147 | return nil, nil, err 148 | } 149 | 150 | udpConn = tuna.NewEncryptUDPConn(conn) 151 | return udpConn, addr, nil 152 | } 153 | 154 | func (us *UdpSession) addCodec(udpAddr *net.UDPAddr, remoteAddr string) error { 155 | remotePublicKey, err := nkn.ClientAddrToPubKey(remoteAddr) 156 | if err != nil { 157 | return err 158 | } 159 | sharedKey, err := us.ts.getOrComputeSharedKey(remotePublicKey) 160 | if err != nil { 161 | return err 162 | } 163 | 164 | conn, err := us.GetEstablishedUDPConn() 165 | if err != nil { 166 | return err 167 | } 168 | err = conn.AddCodec(udpAddr, sharedKey, tpb.EncryptionAlgo_ENCRYPTION_XSALSA20_POLY1305, false) 169 | if err != nil { 170 | return err 171 | } 172 | 173 | return nil 174 | } 175 | 176 | // ReadFrom, implement of standard library function: net.UDPConn.ReadFrom 177 | func (us *UdpSession) ReadFrom(b []byte) (n int, addr net.Addr, err error) { 178 | if us.IsClosed() { 179 | return 0, nil, ErrClosed 180 | } 181 | 182 | var msg = &recvData{} 183 | select { 184 | case msg = <-us.recvChan: 185 | n = copy(b, msg.data) 186 | 187 | us.Lock() 188 | us.recvSize = us.recvSize - len(msg.data) 189 | us.Unlock() 190 | 191 | addr = msg.usa 192 | case <-us.readContext.Done(): 193 | err = us.readContext.Err() 194 | } 195 | 196 | return 197 | } 198 | 199 | func (us *UdpSession) GetUDPConn() *tuna.EncryptUDPConn { 200 | us.RLock() 201 | defer us.RUnlock() 202 | return us.udpConn 203 | } 204 | 205 | func (us *UdpSession) GetEstablishedUDPConn() (*tuna.EncryptUDPConn, error) { 206 | if us.ts.isClosed { 207 | return nil, ErrClosed 208 | } 209 | conn := us.GetUDPConn() 210 | if conn == nil { 211 | return nil, ErrNilConn 212 | } 213 | if conn.IsClosed() { 214 | return nil, ErrClosed 215 | } 216 | return conn, nil 217 | } 218 | 219 | // Loop receiving msg from udp. 220 | func (us *UdpSession) recvMsg() (err error) { 221 | buf := make([]byte, tuna.MaxUDPBufferSize) 222 | for { 223 | conn, err := us.GetEstablishedUDPConn() 224 | if err != nil { 225 | return err 226 | } 227 | 228 | n, udpAddr, encrypted, err := conn.ReadFromUDPEncrypted(buf) 229 | if err != nil { 230 | continue 231 | } 232 | 233 | header := buf[0] 234 | switch header { 235 | case byte(pb.HeaderType_USER): 236 | if !encrypted { // should not receive un-encryted user data 237 | continue 238 | } 239 | 240 | var usa *udpSessionAddr 241 | var ok bool 242 | if us.isListener { 243 | us.RLock() 244 | usa, ok = us.udpAddrToSessAddr[udpAddr.String()] 245 | us.RUnlock() 246 | } else { 247 | ok = udpAddr.String() == us.peer.udpAddr.String() 248 | } 249 | 250 | if ok { // only accept the data which has set up session 251 | us.Lock() 252 | if us.recvSize+n-1 < us.ts.config.UDPRecvBufferSize { 253 | b := make([]byte, n-1) 254 | copy(b, buf[1:n]) // remove header, and return to user application 255 | select { 256 | case us.recvChan <- &recvData{data: b, usa: usa}: 257 | us.recvSize += n - 1 258 | default: 259 | } 260 | } 261 | us.Unlock() 262 | } else { 263 | log.Printf("UdpSession.recvMsg addr %v is not in session, but got user data len %v", udpAddr, n) 264 | } 265 | 266 | case byte(pb.HeaderType_SESSION): 267 | err := us.handleMetaData(buf[1:n], udpAddr) 268 | if err != nil { 269 | log.Printf("UdpSession.recvMsg handleMetaData error %v", err) 270 | } 271 | 272 | default: 273 | log.Printf("UdpSession.recvMsg unknown format message") 274 | } 275 | } 276 | } 277 | 278 | func (us *UdpSession) Read(b []byte) (int, error) { 279 | n, _, err := us.ReadFrom(b) 280 | return n, err 281 | } 282 | 283 | // ReadFrom, implement of standard library net.UDPConn.WriteTo 284 | // Only for user data write 285 | func (us *UdpSession) WriteTo(b []byte, addr net.Addr) (n int, err error) { 286 | buf := make([]byte, 1+len(b)) 287 | buf[0] = byte(pb.HeaderType_USER) 288 | copy(buf[1:], b) 289 | 290 | var udpAddr *net.UDPAddr 291 | if us.isListener { // only listener need to use udpAddr 292 | udpAddr, err = us.getUdpAddr(addr) 293 | if err != nil { 294 | return 0, err 295 | } 296 | } 297 | 298 | conn, err := us.GetEstablishedUDPConn() 299 | if err != nil { 300 | return 0, err 301 | } 302 | n, _, err = conn.WriteMsgUDP(buf, nil, udpAddr) 303 | if err != nil { 304 | return 0, err 305 | } 306 | 307 | return n - 1, nil 308 | } 309 | 310 | func (us *UdpSession) Write(b []byte) (int, error) { 311 | if us.isListener { 312 | return 0, ErrOnlyDailer 313 | } 314 | return us.WriteTo(b, us.peer) 315 | } 316 | 317 | func (us *UdpSession) SetDeadline(t time.Time) error { 318 | if us.ts.isClosed { 319 | return ErrClosed 320 | } 321 | 322 | conn, err := us.GetEstablishedUDPConn() 323 | if err != nil { 324 | return err 325 | } 326 | return conn.SetDeadline(t) 327 | } 328 | 329 | func (us *UdpSession) SetReadDeadline(t time.Time) error { 330 | if t == zeroTime { 331 | us.readContext, us.readCancel = context.WithCancel(context.Background()) 332 | } else { 333 | us.readContext, us.readCancel = context.WithDeadline(context.Background(), t) 334 | } 335 | 336 | conn, err := us.GetEstablishedUDPConn() 337 | if err != nil { 338 | return err 339 | } 340 | return conn.SetReadDeadline(t) 341 | } 342 | 343 | func (us *UdpSession) SetWriteDeadline(t time.Time) error { 344 | conn, err := us.GetEstablishedUDPConn() 345 | if err != nil { 346 | return err 347 | } 348 | return conn.SetWriteDeadline(t) 349 | } 350 | 351 | func (us *UdpSession) SetWriteBuffer(size int) error { 352 | conn, err := us.GetEstablishedUDPConn() 353 | if err != nil { 354 | return err 355 | } 356 | return conn.SetWriteBuffer(size) 357 | } 358 | 359 | func (us *UdpSession) SetReadBuffer(size int) error { 360 | conn, err := us.GetEstablishedUDPConn() 361 | if err != nil { 362 | return err 363 | } 364 | return conn.SetReadBuffer(size) 365 | } 366 | 367 | func (us *UdpSession) IsClosed() bool { 368 | _, err := us.GetEstablishedUDPConn() 369 | if err != nil { 370 | return true 371 | } 372 | return false 373 | } 374 | 375 | func (us *UdpSession) LocalAddr() net.Addr { 376 | conn, err := us.GetEstablishedUDPConn() 377 | if err != nil { 378 | return nil 379 | } 380 | return conn.LocalAddr() 381 | } 382 | 383 | func (us *UdpSession) RemoteAddr() net.Addr { 384 | if us.isListener { 385 | return nil 386 | } 387 | 388 | us.RLock() 389 | defer us.RUnlock() 390 | if us.peer != nil { 391 | return us.peer.udpAddr 392 | } else { 393 | return nil 394 | } 395 | } 396 | 397 | // The endpoint close session actively. 398 | func (us *UdpSession) Close() (err error) { 399 | us.sendCloseMsg(nil) 400 | 401 | if conn, err := us.GetEstablishedUDPConn(); err == nil { 402 | conn.Close() 403 | } 404 | 405 | us.Lock() 406 | defer us.Unlock() 407 | if us.isListener { 408 | us.sessKeyToSessAddr = make(map[string]*udpSessionAddr) 409 | us.udpAddrToSessAddr = make(map[string]*udpSessionAddr) 410 | for _, conn := range us.tcpConns { 411 | if conn != nil { 412 | conn.Close() 413 | } 414 | } 415 | us.tcpConns = make(map[string]*Conn) 416 | } else { 417 | us.peer = nil 418 | if us.tcpConn != nil { 419 | return us.tcpConn.Close() 420 | } 421 | } 422 | 423 | return 424 | } 425 | 426 | func (us *UdpSession) sendCloseMsg(udpAddr *net.UDPAddr) (err error) { 427 | b, err := newSessionData(pb.MsgType_CLOSE, nil) 428 | if err != nil { 429 | return err 430 | } 431 | 432 | us.RLock() 433 | defer us.RUnlock() 434 | 435 | if !us.isListener && us.tcpConn != nil { // Dialer 436 | _, err = us.tcpConn.Write(b) 437 | return 438 | } 439 | 440 | if udpAddr != nil { // Send close message to this dialer address 441 | if usa, ok := us.udpAddrToSessAddr[udpAddr.String()]; ok { 442 | if tcpConn, ok := us.tcpConns[usa.String()]; ok { 443 | _, err = tcpConn.Write(b) 444 | } 445 | } 446 | return 447 | } 448 | 449 | for _, usa := range us.sessKeyToSessAddr { // Send close message to all dialers. 450 | if tcpConn, ok := us.tcpConns[usa.String()]; ok { 451 | _, err = tcpConn.Write(b) 452 | } 453 | } 454 | 455 | return 456 | } 457 | 458 | // Handle connection closed by peer or getting closed message from peer. 459 | func (us *UdpSession) handleConnClosed(sessKey string) { 460 | us.Lock() 461 | defer us.Unlock() 462 | if us.isListener { 463 | if usa, ok := us.sessKeyToSessAddr[sessKey]; ok { 464 | delete(us.sessKeyToSessAddr, sessKey) 465 | delete(us.udpAddrToSessAddr, usa.udpAddr.String()) 466 | if tcpConn, ok := us.tcpConns[sessKey]; ok { 467 | tcpConn.Close() 468 | delete(us.tcpConns, sessKey) 469 | } 470 | } 471 | } else { 472 | us.peer = nil 473 | us.udpConn.Close() 474 | us.tcpConn.Close() 475 | } 476 | } 477 | 478 | // Get UDPAddr by net.Addr 479 | func (us *UdpSession) getUdpAddr(addr net.Addr) (udpAddr *net.UDPAddr, err error) { 480 | us.RLock() 481 | defer us.RUnlock() 482 | 483 | if !us.isListener { 484 | udpAddr = us.peer.udpAddr 485 | return 486 | } 487 | // for listener 488 | if addr == nil { 489 | return nil, ErrWrongAddr 490 | } else { 491 | usa, ok := addr.(*udpSessionAddr) // addr should be *udpSessionAddr 492 | if !ok { 493 | return nil, ErrWrongAddr 494 | } 495 | 496 | usa, ok = us.sessKeyToSessAddr[usa.String()] 497 | if ok { 498 | udpAddr = usa.udpAddr 499 | } else { 500 | return nil, ErrWrongAddr 501 | } 502 | } 503 | 504 | return 505 | } 506 | 507 | func (us *UdpSession) sendMetaData(sessionID []byte) (err error) { 508 | metadata := &pb.SessionMetadata{ 509 | Id: sessionID, 510 | SessionType: pb.SessionType_UDP, 511 | DialerNknAddr: us.ts.Address(), 512 | } 513 | buf, err := proto.Marshal(metadata) 514 | if err != nil { 515 | return err 516 | } 517 | 518 | b, err := newSessionData(pb.MsgType_SESSIONID, buf) 519 | if err != nil { 520 | return err 521 | } 522 | 523 | conn, err := us.GetEstablishedUDPConn() 524 | if err != nil { 525 | return err 526 | } 527 | _, _, err = conn.WriteMsgUDP(b, nil, nil) 528 | 529 | return err 530 | } 531 | 532 | // Handle session meta data. 533 | func (us *UdpSession) handleMetaData(b []byte, udpAddr *net.UDPAddr) error { 534 | if !us.isListener { // dialer should not get session meta data. 535 | return nil 536 | } 537 | 538 | sessData, err := parseSessionData(b) 539 | if err != nil { 540 | return err 541 | } 542 | 543 | switch sessData.MsgType { 544 | case pb.MsgType_SESSIONID: 545 | metadata := &pb.SessionMetadata{} 546 | err = proto.Unmarshal(sessData.Data, metadata) 547 | if err != nil { 548 | return err 549 | } 550 | usa := &udpSessionAddr{sessionID: metadata.Id, remoteNknAddr: metadata.DialerNknAddr, udpAddr: udpAddr} 551 | if _, ok := us.sessKeyToSessAddr[usa.String()]; ok { // This session is exist already 552 | return nil 553 | } 554 | 555 | us.Lock() 556 | us.sessKeyToSessAddr[usa.String()] = usa 557 | us.udpAddrToSessAddr[udpAddr.String()] = usa 558 | us.Unlock() 559 | us.addCodec(udpAddr, metadata.DialerNknAddr) // listener add codec 560 | 561 | case pb.MsgType_CLOSE: 562 | if usa, ok := us.udpAddrToSessAddr[udpAddr.String()]; ok { 563 | us.handleConnClosed(usa.String()) 564 | } 565 | 566 | default: 567 | return ErrWrongMsgFormat 568 | } 569 | 570 | return nil 571 | } 572 | 573 | // New session data 574 | func newSessionData(msgType pb.MsgType, data []byte) ([]byte, error) { 575 | sessData := pb.SessionData{MsgType: msgType, Data: data} 576 | buf, err := proto.Marshal(&sessData) 577 | if err != nil { 578 | return nil, err 579 | } 580 | b := append([]byte{byte(pb.HeaderType_SESSION)}, buf...) 581 | 582 | return b, err 583 | } 584 | 585 | // Parse buffer to message type and data 586 | func parseSessionData(b []byte) (sessData *pb.SessionData, err error) { 587 | var sd pb.SessionData 588 | err = proto.Unmarshal(b, &sd) 589 | if err != nil { 590 | return nil, err 591 | } 592 | 593 | return &sd, nil 594 | } 595 | 596 | func (us *UdpSession) handleTcpMsg(conn *Conn, sessKey string) error { 597 | tcpConn := conn.Conn.(*net.TCPConn) 598 | err := tcpConn.SetKeepAlive(true) 599 | if err != nil { 600 | log.Printf("udpStatusMonitor SetKeepAlive %v", err) 601 | } 602 | 603 | b := make([]byte, 1024) 604 | for { 605 | _, err := us.GetEstablishedUDPConn() 606 | if err != nil { 607 | return err 608 | } 609 | 610 | n, err := tcpConn.Read(b) 611 | if err != nil { 612 | return err 613 | } 614 | if b[0] != byte(pb.HeaderType_SESSION) { 615 | continue 616 | } 617 | 618 | sessData, err := parseSessionData(b[1:n]) 619 | if err != nil { 620 | log.Printf("UdpSession handleTcpMsg parseSessionData err %v", err) 621 | continue 622 | } 623 | switch sessData.MsgType { 624 | case pb.MsgType_CLOSE: 625 | us.handleConnClosed(sessKey) 626 | return ErrClosed 627 | 628 | default: 629 | } 630 | } 631 | } 632 | 633 | // for test only. 634 | func (us *UdpSession) CloseTcp(i int) { 635 | us.RLock() 636 | defer us.RUnlock() 637 | log.Printf("Dialer %v is going to close TCP for testing\n", i) 638 | us.tcpConn.Close() 639 | } 640 | -------------------------------------------------------------------------------- /client.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "log" 10 | "net" 11 | "regexp" 12 | "strconv" 13 | "strings" 14 | "sync" 15 | "time" 16 | 17 | "github.com/imdario/mergo" 18 | "github.com/nknorg/ncp-go" 19 | "github.com/nknorg/nkn-sdk-go" 20 | "github.com/nknorg/nkn-tuna-session/pb" 21 | "github.com/nknorg/nkngomobile" 22 | "github.com/nknorg/tuna" 23 | "github.com/nknorg/tuna/types" 24 | gocache "github.com/patrickmn/go-cache" 25 | "google.golang.org/protobuf/proto" 26 | ) 27 | 28 | const ( 29 | DefaultSessionAllowAddr = nkn.DefaultSessionAllowAddr 30 | SessionIDSize = nkn.SessionIDSize 31 | acceptSessionBufSize = 1024 32 | closedSessionKeyExpiration = 5 * time.Minute 33 | closedSessionKeyCleanupInterval = time.Minute 34 | ) 35 | 36 | var ( 37 | ErrClosed = errors.New("tuna session is closed") 38 | ErrNoPubAddr = errors.New("no public address avalaible") 39 | ErrRemoteAddrRejected = errors.New("remote address is rejected") 40 | ErrWrongMsgFormat = errors.New("wrong message format") 41 | ErrWrongAddr = errors.New("wrong address") 42 | ErrOnlyDailer = errors.New("this function only for dialer") 43 | ErrNilConn = errors.New("conn is nil") 44 | ) 45 | 46 | type TunaSessionClient struct { 47 | config *Config 48 | clientAccount *nkn.Account 49 | multiClient *nkn.MultiClient 50 | wallet *nkn.Wallet 51 | addr net.Addr 52 | acceptSession chan *ncp.Session 53 | onConnect chan struct{} 54 | onClose chan struct{} 55 | connectedOnce sync.Once 56 | 57 | sync.RWMutex 58 | listeners []net.Listener 59 | tunaExits []*tuna.TunaExit 60 | acceptAddrs []*regexp.Regexp 61 | sessions map[string]*ncp.Session 62 | sessionConns map[string]map[string]*Conn 63 | sharedKeys map[string]*[sharedKeySize]byte 64 | connCount map[string]int 65 | closedSessionKey *gocache.Cache 66 | isClosed bool 67 | pubAddrs map[string]*PubAddrs // cached pub addrs, map key is remote address. 68 | addrConnCount map[string]map[string]int // map[remoteAddr]map[tcpAddr.String()] count 69 | 70 | tunaNode *types.Node 71 | 72 | listenerUdpSess *UdpSession // listener udp session 73 | } 74 | 75 | func NewTunaSessionClient(clientAccount *nkn.Account, m *nkn.MultiClient, wallet *nkn.Wallet, config *Config) (*TunaSessionClient, error) { 76 | config, err := MergedConfig(config) 77 | if err != nil { 78 | return nil, err 79 | } 80 | 81 | c := &TunaSessionClient{ 82 | config: config, 83 | clientAccount: clientAccount, 84 | multiClient: m, 85 | wallet: wallet, 86 | addr: m.Addr(), 87 | acceptSession: make(chan *ncp.Session, acceptSessionBufSize), 88 | onConnect: make(chan struct{}), 89 | onClose: make(chan struct{}), 90 | sessions: make(map[string]*ncp.Session), 91 | sessionConns: make(map[string]map[string]*Conn), 92 | sharedKeys: make(map[string]*[sharedKeySize]byte), 93 | connCount: make(map[string]int), 94 | closedSessionKey: gocache.New(closedSessionKeyExpiration, closedSessionKeyCleanupInterval), 95 | pubAddrs: make(map[string]*PubAddrs), 96 | addrConnCount: make(map[string]map[string]int), 97 | } 98 | 99 | go c.removeClosedSessions() 100 | 101 | return c, nil 102 | } 103 | 104 | func (c *TunaSessionClient) Address() string { 105 | return c.addr.String() 106 | } 107 | 108 | func (c *TunaSessionClient) Addr() net.Addr { 109 | return c.addr 110 | } 111 | 112 | // SetConfig will set any non-empty value in conf to tuna session config. 113 | func (c *TunaSessionClient) SetConfig(conf *Config) error { 114 | c.Lock() 115 | defer c.Unlock() 116 | err := mergo.Merge(c.config, conf, mergo.WithOverride) 117 | if err != nil { 118 | return err 119 | } 120 | if conf.TunaIPFilter != nil { 121 | c.config.TunaIPFilter = conf.TunaIPFilter 122 | } 123 | if conf.TunaNknFilter != nil { 124 | c.config.TunaNknFilter = conf.TunaNknFilter 125 | } 126 | return nil 127 | } 128 | 129 | func (c *TunaSessionClient) newTunaExit(i int) (*tuna.TunaExit, error) { 130 | if i >= len(c.listeners) { 131 | return nil, errors.New("index out of range") 132 | } 133 | 134 | _, portStr, err := net.SplitHostPort(c.listeners[i].Addr().String()) 135 | if err != nil { 136 | return nil, err 137 | } 138 | 139 | port, err := strconv.Atoi(portStr) 140 | if err != nil { 141 | return nil, err 142 | } 143 | 144 | service := tuna.Service{ 145 | Name: "session", 146 | TCP: []uint32{uint32(port)}, 147 | UDP: []uint32{uint32(port)}, 148 | } 149 | 150 | tunaConfig := &tuna.ExitConfiguration{ 151 | Reverse: true, 152 | ReverseRandomPorts: true, 153 | ReverseMaxPrice: c.config.TunaMaxPrice, 154 | ReverseNanoPayFee: c.config.TunaNanoPayFee, 155 | MinReverseNanoPayFee: c.config.TunaMinNanoPayFee, 156 | ReverseNanoPayFeeRatio: c.config.TunaNanoPayFeeRatio, 157 | ReverseServiceName: c.config.TunaServiceName, 158 | ReverseSubscriptionPrefix: c.config.TunaSubscriptionPrefix, 159 | ReverseIPFilter: *c.config.TunaIPFilter, 160 | ReverseNknFilter: *c.config.TunaNknFilter, 161 | DownloadGeoDB: c.config.TunaDownloadGeoDB, 162 | GeoDBPath: c.config.TunaGeoDBPath, 163 | MeasureBandwidth: c.config.TunaMeasureBandwidth, 164 | MeasureStoragePath: c.config.TunaMeasureStoragePath, 165 | MeasurementBytesDownLink: c.config.TunaMeasurementBytesDownLink, 166 | DialTimeout: int32(c.config.TunaDialTimeout / 1000), 167 | SortMeasuredNodes: sortMeasuredNodes, 168 | ReverseMinBalance: c.config.TunaMinBalance, 169 | } 170 | 171 | return tuna.NewTunaExit([]tuna.Service{service}, c.wallet, nil, tunaConfig) 172 | } 173 | 174 | func (c *TunaSessionClient) Listen(addrsRe *nkngomobile.StringArray) error { 175 | acceptAddrs, err := getAcceptAddrs(addrsRe) 176 | if err != nil { 177 | return err 178 | } 179 | 180 | c.Lock() 181 | defer c.Unlock() 182 | 183 | c.acceptAddrs = acceptAddrs 184 | 185 | if len(c.listeners) > 0 { 186 | return nil 187 | } 188 | 189 | if c.wallet == nil { 190 | return errors.New("wallet is empty") 191 | } 192 | 193 | return c.startExits() 194 | } 195 | 196 | // OnConnect returns a channel that will be closed when at least one tuna exit 197 | // is connected after Listen() is first called. 198 | func (c *TunaSessionClient) OnConnect() chan struct{} { 199 | return c.onConnect 200 | } 201 | 202 | // RotateOne create a new tuna exit and replace the i-th one. New connections 203 | // accepted will use new tuna exit, existing connections will not be affected. 204 | func (c *TunaSessionClient) RotateOne(i int) error { 205 | c.RLock() 206 | te, err := c.newTunaExit(i) 207 | if err != nil { 208 | c.RUnlock() 209 | return err 210 | } 211 | c.RUnlock() 212 | 213 | go te.StartReverse(true) 214 | 215 | <-te.OnConnect.C 216 | 217 | c.Lock() 218 | oldTe := c.tunaExits[i] 219 | c.tunaExits[i] = te 220 | c.Unlock() 221 | 222 | if oldTe != nil { 223 | oldTe.SetLinger(-1) 224 | go oldTe.Close() 225 | } 226 | 227 | return nil 228 | } 229 | 230 | // RotateAll create and replace all tuna exit. New connections accepted will use 231 | // new tuna exit, existing connections will not be affected. 232 | func (c *TunaSessionClient) RotateAll() error { 233 | c.RLock() 234 | n := len(c.listeners) 235 | c.RUnlock() 236 | 237 | for i := 0; i < n; i++ { 238 | err := c.RotateOne(i) 239 | if err != nil { 240 | return err 241 | } 242 | } 243 | return nil 244 | } 245 | 246 | func (c *TunaSessionClient) shouldAcceptAddr(addr string) bool { 247 | for _, allowAddr := range c.acceptAddrs { 248 | if allowAddr.MatchString(addr) { 249 | return true 250 | } 251 | } 252 | return false 253 | } 254 | 255 | func (c *TunaSessionClient) getPubAddrsFromRemote(ctx context.Context, remoteAddr string, sessionID []byte) (*PubAddrs, error) { 256 | if pubAddrs := c.getCachedPubAddrs(remoteAddr); pubAddrs != nil { 257 | return pubAddrs, nil 258 | } 259 | 260 | buf, err := json.Marshal(&Request{Action: ActionGetPubAddr, SessionID: sessionID}) 261 | if err != nil { 262 | return nil, err 263 | } 264 | 265 | msgChan := make(chan *nkn.Message, 1) 266 | errChan := make(chan error, 1) 267 | doneCtx, doneCancel := context.WithCancel(ctx) 268 | defer doneCancel() 269 | wg := sync.WaitGroup{} 270 | for i := 0; i < 3; i++ { 271 | wg.Add(1) 272 | go func(i int) { 273 | defer wg.Done() 274 | select { 275 | case <-time.After(time.Duration(3*i) * time.Second): 276 | case <-doneCtx.Done(): 277 | return 278 | } 279 | respChan, err := c.multiClient.Send(nkn.NewStringArray(remoteAddr), buf, nil) 280 | if err != nil { 281 | select { 282 | case errChan <- err: 283 | default: 284 | } 285 | return 286 | } 287 | select { 288 | case msg := <-respChan.C: 289 | select { 290 | case msgChan <- msg: 291 | default: 292 | } 293 | doneCancel() 294 | case <-doneCtx.Done(): 295 | } 296 | }(i) 297 | } 298 | wg.Wait() 299 | close(msgChan) 300 | close(errChan) 301 | 302 | msg, ok := <-msgChan 303 | if !ok { 304 | err, ok := <-errChan 305 | if ok { 306 | return nil, err 307 | } 308 | return nil, ctx.Err() 309 | } 310 | 311 | pubAddrs := &PubAddrs{} 312 | err = json.Unmarshal(msg.Data, pubAddrs) 313 | if err != nil { 314 | return nil, err 315 | } 316 | if pubAddrs.SessionClosed { 317 | return nil, ErrClosed 318 | } 319 | 320 | for _, addr := range pubAddrs.Addrs { 321 | if len(addr.IP) > 0 && addr.Port != 0 { 322 | c.Lock() 323 | c.pubAddrs[remoteAddr] = pubAddrs 324 | c.Unlock() 325 | return pubAddrs, nil 326 | } 327 | } 328 | 329 | return nil, ErrNoPubAddr 330 | } 331 | 332 | func (c *TunaSessionClient) getPubAddrs(includePrice bool) *PubAddrs { 333 | if c.tunaExits == nil { 334 | return nil 335 | } 336 | addrs := make([]*PubAddr, 0, len(c.tunaExits)) 337 | for _, tunaExit := range c.tunaExits { 338 | ip := tunaExit.GetReverseIP().String() 339 | ports := tunaExit.GetReverseTCPPorts() 340 | addr := &PubAddr{} 341 | if len(ip) > 0 && len(ports) > 0 { 342 | addr.IP = ip 343 | addr.Port = ports[0] 344 | if includePrice { 345 | entryToExitPrice, exitToEntryPrice := tunaExit.GetPrice() 346 | addr.InPrice = entryToExitPrice.String() 347 | addr.OutPrice = exitToEntryPrice.String() 348 | } 349 | } 350 | addrs = append(addrs, addr) 351 | } 352 | 353 | return &PubAddrs{Addrs: addrs} 354 | } 355 | 356 | func (c *TunaSessionClient) GetPubAddrs() *PubAddrs { 357 | return c.getPubAddrs(true) 358 | } 359 | 360 | func (c *TunaSessionClient) listenNKN() { 361 | for { 362 | msg, ok := <-c.multiClient.OnMessage.C 363 | if !ok { 364 | return 365 | } 366 | if !c.shouldAcceptAddr(msg.Src) { 367 | continue 368 | } 369 | 370 | req := &Request{} 371 | err := json.Unmarshal(msg.Data, req) 372 | if err != nil { 373 | log.Printf("Decode request error: %v", err) 374 | continue 375 | } 376 | 377 | switch strings.ToLower(req.Action) { 378 | case strings.ToLower(ActionGetPubAddr): 379 | pubAddrs := &PubAddrs{} 380 | sessKey := sessionKey(msg.Src, req.SessionID) 381 | if c.IsSessClosed(sessKey) { 382 | pubAddrs.SessionClosed = true 383 | } else { 384 | pubAddrs = c.getPubAddrs(false) 385 | } 386 | buf, err := json.Marshal(pubAddrs) 387 | if err != nil { 388 | log.Printf("Encode reply error: %v", err) 389 | continue 390 | } 391 | 392 | err = msg.Reply(buf) 393 | if err != nil { 394 | log.Printf("Send reply error: %v", err) 395 | continue 396 | } 397 | 398 | default: 399 | log.Printf("Unknown action %v", req.Action) 400 | continue 401 | } 402 | } 403 | } 404 | 405 | func (c *TunaSessionClient) listenNet(i int) { 406 | for { 407 | netConn, err := c.listeners[i].Accept() 408 | if err != nil { 409 | if c.isClosed { 410 | return 411 | } 412 | log.Printf("Accept connection error: %v", err) 413 | time.Sleep(time.Second) 414 | continue 415 | } 416 | 417 | conn := newConn(netConn) 418 | 419 | go func(conn *Conn) { 420 | buf, err := readMessage(conn, maxAddrSize) 421 | if err != nil { 422 | log.Printf("Read message error: %v", err) 423 | conn.Close() 424 | return 425 | } 426 | 427 | remoteAddr := string(buf) 428 | 429 | if !c.shouldAcceptAddr(remoteAddr) { 430 | conn.Close() 431 | return 432 | } 433 | 434 | buf, err = readMessage(conn, maxSessionMetadataSize) 435 | if err != nil { 436 | log.Printf("Read message error: %v", err) 437 | conn.Close() 438 | return 439 | } 440 | 441 | metadataRaw, err := c.decode(buf, remoteAddr) 442 | if err != nil { 443 | log.Printf("Decode message error: %v", err) 444 | conn.Close() 445 | return 446 | } 447 | 448 | metadata := &pb.SessionMetadata{} 449 | err = proto.Unmarshal(metadataRaw, metadata) 450 | if err != nil { 451 | log.Printf("Decode session metadata error: %v", err) 452 | conn.Close() 453 | return 454 | } 455 | 456 | sessionID := metadata.Id 457 | sessionType := metadata.SessionType 458 | sessKey := sessionKey(remoteAddr, sessionID) 459 | 460 | if sessionType == pb.SessionType_UDP { // UDP session's TCP connection 461 | c.handleUdpListenerTcp(conn, remoteAddr, sessionID) 462 | return 463 | } 464 | 465 | defer conn.Close() 466 | 467 | c.Lock() 468 | sess, ok := c.sessions[sessKey] 469 | if !ok { 470 | if _, ok := c.closedSessionKey.Get(sessKey); ok { 471 | c.Unlock() 472 | return 473 | } 474 | connIDs := make([]string, c.config.NumTunaListeners) 475 | for j := 0; j < len(connIDs); j++ { 476 | connIDs[j] = connID(j) 477 | } 478 | sess, err = c.newSession(remoteAddr, sessionID, connIDs, c.config.SessionConfig) 479 | if err != nil { 480 | c.Unlock() 481 | return 482 | } 483 | c.sessions[sessKey] = sess 484 | c.sessionConns[sessKey] = make(map[string]*Conn, c.config.NumTunaListeners) 485 | } 486 | c.sessionConns[sessKey][connID(i)] = conn 487 | c.Unlock() 488 | 489 | if !ok { 490 | err := c.handleMsg(conn, sess, i) 491 | if err != nil { 492 | return 493 | } 494 | 495 | select { 496 | case c.acceptSession <- sess: 497 | default: 498 | log.Println("Accept session channel full, discard request...") 499 | } 500 | } 501 | 502 | c.handleConn(conn, remoteAddr, sessionID, i) 503 | }(conn) 504 | } 505 | } 506 | 507 | func (c *TunaSessionClient) encode(message []byte, remoteAddr string) ([]byte, error) { 508 | remotePublicKey, err := nkn.ClientAddrToPubKey(remoteAddr) 509 | if err != nil { 510 | return nil, err 511 | } 512 | 513 | sharedKey, err := c.getOrComputeSharedKey(remotePublicKey) 514 | if err != nil { 515 | return nil, err 516 | } 517 | 518 | encrypted, nonce, err := encrypt(message, sharedKey) 519 | if err != nil { 520 | return nil, err 521 | } 522 | 523 | return append(nonce, encrypted...), nil 524 | } 525 | 526 | func (c *TunaSessionClient) decode(buf []byte, remoteAddr string) ([]byte, error) { 527 | if len(buf) <= nonceSize { 528 | return nil, errors.New("message too short") 529 | } 530 | 531 | remotePublicKey, err := nkn.ClientAddrToPubKey(remoteAddr) 532 | if err != nil { 533 | return nil, err 534 | } 535 | 536 | sharedKey, err := c.getOrComputeSharedKey(remotePublicKey) 537 | if err != nil { 538 | return nil, err 539 | } 540 | 541 | var nonce [nonceSize]byte 542 | copy(nonce[:], buf[:nonceSize]) 543 | message, err := decrypt(buf[nonceSize:], nonce, sharedKey) 544 | if err != nil { 545 | return nil, err 546 | } 547 | 548 | return message, nil 549 | } 550 | 551 | func (c *TunaSessionClient) Dial(remoteAddr string) (net.Conn, error) { 552 | return c.DialSession(remoteAddr) 553 | } 554 | 555 | func (c *TunaSessionClient) DialSession(remoteAddr string) (*ncp.Session, error) { 556 | return c.DialWithConfig(remoteAddr, nil) 557 | } 558 | 559 | func (c *TunaSessionClient) DialWithConfig(remoteAddr string, config *nkn.DialConfig) (*ncp.Session, error) { 560 | config, err := nkn.MergeDialConfig(c.config.SessionConfig, config) 561 | if err != nil { 562 | return nil, err 563 | } 564 | 565 | remoteAddr, err = c.multiClient.ResolveDest(remoteAddr) 566 | if err != nil { 567 | return nil, err 568 | } 569 | 570 | ctx := context.Background() 571 | var cancel context.CancelFunc 572 | if config.DialTimeout > 0 { 573 | ctx, cancel = context.WithTimeout(ctx, time.Duration(config.DialTimeout)*time.Millisecond) 574 | defer cancel() 575 | } 576 | 577 | sessionID, err := nkn.RandomBytes(SessionIDSize) 578 | if err != nil { 579 | return nil, err 580 | } 581 | 582 | pubAddrs, err := c.getPubAddrsFromRemote(ctx, remoteAddr, sessionID) 583 | if err != nil { 584 | return nil, err 585 | } 586 | 587 | var wg sync.WaitGroup 588 | for i := range pubAddrs.Addrs { 589 | if pubAddrs.Addrs[i] == nil || pubAddrs.Addrs[i].IP == "" || pubAddrs.Addrs[i].Port == 0 { 590 | if c.config.Verbose { 591 | log.Printf("Tuna session pubAddrs %v doesn't have valid ip %v port %v", i, pubAddrs.Addrs[i].IP, pubAddrs.Addrs[i].Port) 592 | } 593 | continue 594 | } 595 | 596 | wg.Add(1) 597 | go func(i int) { 598 | defer wg.Done() 599 | 600 | _, err = c.dialTcpConn(ctx, remoteAddr, sessionID, pb.SessionType_TCP, i, pubAddrs.Addrs[i], config) 601 | if err != nil { 602 | log.Printf("Tuna session dial to ip %v port %v err: %v", pubAddrs.Addrs[i].IP, pubAddrs.Addrs[i].Port, err) 603 | return 604 | } 605 | }(i) 606 | } 607 | 608 | wg.Wait() 609 | sessKey := sessionKey(remoteAddr, sessionID) 610 | 611 | c.RLock() 612 | conns := c.sessionConns[sessKey] 613 | if len(conns) == 0 { 614 | c.RUnlock() 615 | return nil, err 616 | } 617 | connIDs := make([]string, 0, len(conns)) 618 | for i := 0; i < len(pubAddrs.Addrs); i++ { 619 | if _, ok := conns[connID(i)]; ok { 620 | connIDs = append(connIDs, connID(i)) 621 | } 622 | } 623 | c.RUnlock() 624 | 625 | sess, err := c.newSession(remoteAddr, sessionID, connIDs, config.SessionConfig) 626 | if err != nil { 627 | return nil, err 628 | } 629 | c.Lock() 630 | c.sessions[sessKey] = sess 631 | c.Unlock() 632 | 633 | for i := 0; i < len(pubAddrs.Addrs); i++ { 634 | c.RLock() 635 | conn, ok := conns[connID(i)] 636 | c.RUnlock() 637 | if ok { 638 | go func(conn *Conn, i int) { 639 | defer func() { 640 | if conn != nil { 641 | conn.Close() 642 | } 643 | }() 644 | for { 645 | c.handleConn(conn, remoteAddr, sessionID, i) 646 | 647 | if c.config.ReconnectRetries == 0 { 648 | return 649 | } 650 | for j := 0; c.config.ReconnectRetries < 0 || j < c.config.ReconnectRetries; j++ { 651 | var err error 652 | if conn, err = c.reconnect(remoteAddr, sessionID, i, pubAddrs, config); err == nil { 653 | break 654 | } 655 | if err == ErrClosed || err == ncp.ErrSessionClosed { 656 | return 657 | } 658 | time.Sleep(time.Duration(c.config.ReconnectInterval) * time.Millisecond) 659 | } 660 | if conn == nil { // fail after reconnectRetries 661 | break 662 | } 663 | } 664 | }(conn, i) 665 | } 666 | } 667 | 668 | err = sess.Dial(ctx) 669 | if err != nil { 670 | return nil, err 671 | } 672 | 673 | return sess, nil 674 | } 675 | 676 | func (c *TunaSessionClient) AcceptSession() (*ncp.Session, error) { 677 | for { 678 | select { 679 | case session := <-c.acceptSession: 680 | err := session.Accept() 681 | if err != nil { 682 | log.Println("Accept error:", err) 683 | continue 684 | } 685 | return session, nil 686 | case _, ok := <-c.onClose: 687 | if !ok { 688 | return nil, nkn.ErrClosed 689 | } 690 | } 691 | } 692 | } 693 | 694 | func (c *TunaSessionClient) Accept() (net.Conn, error) { 695 | return c.AcceptSession() 696 | } 697 | 698 | func (c *TunaSessionClient) Close() error { 699 | c.Lock() 700 | defer c.Unlock() 701 | 702 | if c.isClosed { 703 | return nil 704 | } 705 | 706 | err := c.multiClient.Close() 707 | if err != nil { 708 | log.Println("MultiClient close error:", err) 709 | } 710 | 711 | for _, listener := range c.listeners { 712 | err := listener.Close() 713 | if err != nil { 714 | log.Println("Listener close error:", err) 715 | continue 716 | } 717 | } 718 | 719 | for _, sess := range c.sessions { 720 | if !sess.IsClosed() { 721 | err := sess.Close() 722 | if err != nil { 723 | log.Println("Session close error:", err) 724 | continue 725 | } 726 | } 727 | } 728 | 729 | for _, conns := range c.sessionConns { 730 | for _, conn := range conns { 731 | if conn == nil { 732 | continue 733 | } 734 | err := conn.Close() 735 | if err != nil { 736 | log.Println("Conn close error:", err) 737 | continue 738 | } 739 | } 740 | } 741 | 742 | for _, tunaExit := range c.tunaExits { 743 | tunaExit.Close() 744 | } 745 | 746 | if c.listenerUdpSess != nil { 747 | c.listenerUdpSess.Close() 748 | } 749 | 750 | c.isClosed = true 751 | 752 | close(c.onClose) 753 | 754 | return nil 755 | } 756 | 757 | func (c *TunaSessionClient) IsClosed() bool { 758 | c.RLock() 759 | defer c.RUnlock() 760 | return c.isClosed 761 | } 762 | 763 | func (c *TunaSessionClient) newSession(remoteAddr string, sessionID []byte, connIDs []string, config *ncp.Config) (*ncp.Session, error) { 764 | sessKey := sessionKey(remoteAddr, sessionID) 765 | return ncp.NewSession(c.addr, nkn.NewClientAddr(remoteAddr), connIDs, nil, func(connID, _ string, buf []byte, writeTimeout time.Duration) error { 766 | c.RLock() 767 | conn := c.sessionConns[sessKey][connID] 768 | c.RUnlock() 769 | if conn == nil { 770 | return fmt.Errorf("conn %s is nil", connID) 771 | } 772 | buf, err := c.encode(buf, remoteAddr) 773 | if err != nil { 774 | return err 775 | } 776 | err = writeMessage(conn, buf, writeTimeout) 777 | if err != nil { 778 | log.Println("Write message error:", err) 779 | conn.Close() 780 | return err // ncp.ErrConnClosed 781 | } 782 | return nil 783 | }, config) 784 | } 785 | 786 | func (c *TunaSessionClient) handleMsg(conn *Conn, sess *ncp.Session, i int) error { 787 | buf, err := readMessage(conn, uint32(c.config.SessionConfig.MTU+maxSessionMsgOverhead)) 788 | if err != nil { 789 | return err 790 | } 791 | 792 | buf, err = c.decode(buf, sess.RemoteAddr().String()) 793 | if err != nil { 794 | return err 795 | } 796 | 797 | err = sess.ReceiveWith(connID(i), connID(i), buf) 798 | if err != nil { 799 | return err 800 | } 801 | 802 | return nil 803 | } 804 | 805 | func (c *TunaSessionClient) handleConn(conn *Conn, remoteAddr string, sessionID []byte, i int) { 806 | if conn == nil { 807 | return 808 | } 809 | 810 | sessKey := sessionKey(remoteAddr, sessionID) 811 | c.Lock() 812 | sess := c.sessions[sessKey] 813 | if sess == nil { 814 | c.Unlock() 815 | return 816 | } 817 | c.connCount[sessKey]++ 818 | 819 | connStr := conn.RemoteAddr().String() 820 | tcpCount, ok := c.addrConnCount[remoteAddr] 821 | if ok { 822 | tcpCount[connStr]++ 823 | } else { 824 | c.addrConnCount[remoteAddr] = make(map[string]int) 825 | c.addrConnCount[remoteAddr][connStr]++ 826 | } 827 | c.Unlock() 828 | 829 | defer func() { 830 | c.Lock() 831 | c.connCount[sessKey]-- 832 | delete(c.sessionConns[sessKey], connID(i)) 833 | 834 | c.addrConnCount[remoteAddr][connStr]-- 835 | if c.addrConnCount[remoteAddr][connStr] <= 0 { // When any count drops to 0 we remove c.pubAddrs[remoteAddr] from cache 836 | delete(c.addrConnCount[remoteAddr], connStr) 837 | if len(c.addrConnCount[remoteAddr]) == 0 { 838 | delete(c.addrConnCount, remoteAddr) 839 | } 840 | delete(c.pubAddrs, remoteAddr) 841 | } 842 | 843 | shouldClose := c.connCount[sessKey] == 0 844 | if shouldClose { 845 | delete(c.sessions, sessKey) 846 | delete(c.sessionConns, sessKey) 847 | delete(c.connCount, sessKey) 848 | c.closedSessionKey.Add(sessKey, nil, gocache.DefaultExpiration) 849 | } 850 | c.Unlock() 851 | 852 | if shouldClose { 853 | sess.Close() 854 | } 855 | }() 856 | 857 | for { 858 | err := c.handleMsg(conn, sess, i) 859 | if err != nil { 860 | if err == io.EOF || err == ncp.ErrSessionClosed || sess.IsClosed() { 861 | return 862 | } 863 | select { 864 | case _, ok := <-c.onClose: 865 | if !ok { 866 | return 867 | } 868 | default: 869 | } 870 | log.Printf("handle msg error: %v", err) 871 | return 872 | } 873 | } 874 | } 875 | 876 | func (c *TunaSessionClient) removeClosedSessions() { 877 | for { 878 | time.Sleep(time.Second) 879 | 880 | if c.isClosed { 881 | return 882 | } 883 | 884 | c.Lock() 885 | for sessKey, sess := range c.sessions { 886 | if sess.IsClosed() { 887 | for _, conn := range c.sessionConns[sessKey] { 888 | conn.Close() 889 | } 890 | delete(c.sessions, sessKey) 891 | delete(c.sessionConns, sessKey) 892 | delete(c.connCount, sessKey) 893 | c.closedSessionKey.Add(sessKey, nil, gocache.DefaultExpiration) 894 | } 895 | } 896 | c.Unlock() 897 | } 898 | } 899 | 900 | func (c *TunaSessionClient) startExits() error { 901 | if len(c.tunaExits) > 0 { 902 | return nil 903 | } 904 | listeners := make([]net.Listener, c.config.NumTunaListeners) 905 | var err error 906 | for i := 0; i < len(listeners); i++ { 907 | port, err := GetFreePort(0) 908 | if err != nil { 909 | return err 910 | } 911 | listeners[i], err = net.Listen("tcp", fmt.Sprintf("127.0.0.1:%v", port)) 912 | if err != nil { 913 | return err 914 | } 915 | } 916 | c.listeners = listeners 917 | 918 | exits := make([]*tuna.TunaExit, c.config.NumTunaListeners) 919 | for i := 0; i < len(listeners); i++ { 920 | exits[i], err = c.newTunaExit(i) 921 | if err != nil { 922 | return err 923 | } 924 | 925 | if c.tunaNode != nil { 926 | exits[i].SetRemoteNode(c.tunaNode) 927 | } 928 | 929 | go func(te *tuna.TunaExit) { 930 | select { 931 | case <-te.OnConnect.C: 932 | c.connectedOnce.Do(func() { 933 | close(c.onConnect) 934 | }) 935 | case <-c.onClose: 936 | return 937 | } 938 | }(exits[i]) 939 | 940 | go exits[i].StartReverse(true) 941 | } 942 | c.tunaExits = exits 943 | go func() { 944 | select { 945 | case <-c.onConnect: 946 | go c.listenNKN() 947 | for i := 0; i < len(listeners); i++ { 948 | go c.listenNet(i) 949 | } 950 | case <-c.onClose: 951 | return 952 | } 953 | }() 954 | 955 | return nil 956 | } 957 | 958 | func (c *TunaSessionClient) dialTcpConn(ctx context.Context, remoteAddr string, sessionID []byte, sessType pb.SessionType, i int, addr *PubAddr, config *nkn.DialConfig) (conn *Conn, err error) { 959 | if addr == nil || len(addr.IP) == 0 || addr.Port == 0 { 960 | return nil, fmt.Errorf("dialAConn wrong params addr") 961 | } 962 | 963 | dialer := &net.Dialer{} 964 | netConn, err := dialer.DialContext(ctx, "tcp", fmt.Sprintf("%s:%d", addr.IP, addr.Port)) 965 | if err != nil { 966 | return nil, err 967 | } 968 | conn = newConn(netConn) 969 | 970 | err = writeMessage(conn, []byte(c.addr.String()), time.Duration(config.DialTimeout)*time.Millisecond) 971 | if err != nil { 972 | conn.Close() 973 | return nil, err 974 | } 975 | 976 | metadata := &pb.SessionMetadata{ 977 | Id: sessionID, 978 | SessionType: sessType, 979 | } 980 | metadataRaw, err := proto.Marshal(metadata) 981 | if err != nil { 982 | conn.Close() 983 | return nil, err 984 | } 985 | 986 | buf, err := c.encode(metadataRaw, remoteAddr) 987 | if err != nil { 988 | conn.Close() 989 | return nil, err 990 | } 991 | 992 | err = writeMessage(conn, buf, time.Duration(config.DialTimeout)*time.Millisecond) 993 | if err != nil { 994 | conn.Close() 995 | return nil, err 996 | } 997 | 998 | sessKey := sessionKey(remoteAddr, sessionID) 999 | if sessType == pb.SessionType_TCP { 1000 | c.Lock() 1001 | conns, ok := c.sessionConns[sessKey] 1002 | if !ok { 1003 | conns = make(map[string]*Conn) 1004 | } 1005 | conns[connID(i)] = conn 1006 | c.sessionConns[sessKey] = conns 1007 | c.Unlock() 1008 | } 1009 | 1010 | return conn, nil 1011 | } 1012 | 1013 | func (c *TunaSessionClient) reconnect(remoteAddr string, sessionID []byte, i int, pubAddrs *PubAddrs, config *nkn.DialConfig) (conn *Conn, err error) { 1014 | if c.isClosed { 1015 | return nil, ErrClosed 1016 | } 1017 | sessKey := sessionKey(remoteAddr, sessionID) 1018 | c.RLock() 1019 | sess := c.sessions[sessKey] 1020 | c.RUnlock() 1021 | if sess == nil || sess.IsClosed() { 1022 | return nil, ncp.ErrSessionClosed 1023 | } 1024 | 1025 | ctx, cancel := context.WithCancel(sess.GetContext()) 1026 | if config.DialTimeout > 0 { 1027 | ctx, cancel = context.WithTimeout(ctx, time.Duration(config.DialTimeout)*time.Millisecond) 1028 | } 1029 | defer cancel() 1030 | 1031 | newPubAddrs, err := c.getPubAddrsFromRemote(ctx, remoteAddr, sessionID) 1032 | if err == ErrClosed { 1033 | sess.Close() 1034 | return nil, ErrClosed 1035 | } else if err != nil { 1036 | return nil, err 1037 | } 1038 | if len(newPubAddrs.Addrs) > i { 1039 | conn, err = c.dialTcpConn(ctx, remoteAddr, sessionID, pb.SessionType_TCP, i, newPubAddrs.Addrs[i], config) 1040 | if err == nil { 1041 | return conn, nil 1042 | } 1043 | } 1044 | return nil, err 1045 | } 1046 | 1047 | func (c *TunaSessionClient) CloseOneConn(sess *ncp.Session, connId string) { 1048 | c.RLock() 1049 | defer c.RUnlock() 1050 | for key, s := range c.sessions { 1051 | if s == sess { 1052 | conn := c.sessionConns[key][connId] 1053 | conn.Close() 1054 | break 1055 | } 1056 | } 1057 | } 1058 | 1059 | func (c *TunaSessionClient) IsSessClosed(sessKey string) bool { 1060 | c.RLock() 1061 | defer c.RUnlock() 1062 | if sess, ok := c.sessions[sessKey]; ok { 1063 | return sess.IsClosed() 1064 | } 1065 | if _, ok := c.closedSessionKey.Get(sessKey); ok { 1066 | return true 1067 | } 1068 | return false 1069 | } 1070 | 1071 | func (c *TunaSessionClient) SetTunaNode(node *types.Node) { 1072 | c.tunaNode = node 1073 | } 1074 | 1075 | func (c *TunaSessionClient) getCachedPubAddrs(remoteAddr string) *PubAddrs { 1076 | c.RLock() 1077 | defer c.RUnlock() 1078 | 1079 | cachedAddr, ok := c.pubAddrs[remoteAddr] 1080 | if !ok { 1081 | return nil 1082 | } 1083 | 1084 | for i := 0; i < len(cachedAddr.Addrs); i++ { 1085 | if cachedAddr.Addrs[i] == nil { 1086 | return nil 1087 | } 1088 | if tcpCount, ok := c.addrConnCount[remoteAddr]; ok { 1089 | if tcpCount[cachedAddr.Addrs[i].String()] <= 0 { 1090 | return nil 1091 | } 1092 | } else { 1093 | return nil 1094 | } 1095 | } 1096 | 1097 | return cachedAddr 1098 | } 1099 | --------------------------------------------------------------------------------