forked from st3v/go-plugins
/
transport.go
111 lines (93 loc) · 2.18 KB
/
transport.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package utp
import (
"bufio"
"context"
"crypto/tls"
"encoding/gob"
"net"
"github.com/anacrolix/utp"
"github.com/micro/go-micro/transport"
maddr "github.com/micro/util/go/lib/addr"
mnet "github.com/micro/util/go/lib/net"
mls "github.com/micro/util/go/lib/tls"
)
func (u *utpTransport) Dial(addr string, opts ...transport.DialOption) (transport.Client, error) {
dopts := transport.DialOptions{
Timeout: transport.DefaultDialTimeout,
}
for _, opt := range opts {
opt(&dopts)
}
ctx, _ := context.WithTimeout(context.Background(), dopts.Timeout)
c, err := utp.DialContext(ctx, addr)
if err != nil {
return nil, err
}
if u.opts.Secure || u.opts.TLSConfig != nil {
config := u.opts.TLSConfig
if config == nil {
config = &tls.Config{
InsecureSkipVerify: true,
}
}
c = tls.Client(c, config)
}
encBuf := bufio.NewWriter(c)
return &utpClient{
dialOpts: dopts,
conn: c,
encBuf: encBuf,
enc: gob.NewEncoder(encBuf),
dec: gob.NewDecoder(c),
timeout: u.opts.Timeout,
}, nil
}
func (u *utpTransport) Listen(addr string, opts ...transport.ListenOption) (transport.Listener, error) {
var options transport.ListenOptions
for _, o := range opts {
o(&options)
}
var l net.Listener
var err error
if u.opts.Secure || u.opts.TLSConfig != nil {
config := u.opts.TLSConfig
fn := func(addr string) (net.Listener, error) {
if config == nil {
hosts := []string{addr}
// check if its a valid host:port
if host, _, err := net.SplitHostPort(addr); err == nil {
if len(host) == 0 {
hosts = maddr.IPs()
} else {
hosts = []string{host}
}
}
// generate a certificate
cert, err := mls.Certificate(hosts...)
if err != nil {
return nil, err
}
config = &tls.Config{Certificates: []tls.Certificate{cert}}
}
l, err := utp.Listen(addr)
if err != nil {
return nil, err
}
return tls.NewListener(l, config), nil
}
l, err = mnet.Listen(addr, fn)
} else {
l, err = mnet.Listen(addr, utp.Listen)
}
if err != nil {
return nil, err
}
return &utpListener{
t: u.opts.Timeout,
l: l,
opts: options,
}, nil
}
func (u *utpTransport) String() string {
return "utp"
}