-
-
Notifications
You must be signed in to change notification settings - Fork 625
/
conn-client.go
91 lines (82 loc) · 1.7 KB
/
conn-client.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
package udp
import (
"context"
"net"
"github.com/anacrolix/dht/v2/krpc"
"github.com/anacrolix/missinggo/v2"
)
type NewConnClientOpts struct {
Network string
Host string
Ipv6 *bool
}
type ConnClient struct {
Client Client
conn net.Conn
d Dispatcher
readErr error
ipv6 bool
}
func (cc *ConnClient) reader() {
b := make([]byte, 0x800)
for {
n, err := cc.conn.Read(b)
if err != nil {
// TODO: Do bad things to the dispatcher, and incoming calls to the client if we have a
// read error.
cc.readErr = err
break
}
_ = cc.d.Dispatch(b[:n])
// if err != nil {
// log.Printf("dispatching packet received on %v (%q): %v", cc.conn, string(b[:n]), err)
// }
}
}
func ipv6(opt *bool, network string, conn net.Conn) bool {
if opt != nil {
return *opt
}
switch network {
case "udp4":
return false
case "udp6":
return true
}
rip := missinggo.AddrIP(conn.RemoteAddr())
return rip.To16() != nil && rip.To4() == nil
}
func NewConnClient(opts NewConnClientOpts) (cc *ConnClient, err error) {
conn, err := net.Dial(opts.Network, opts.Host)
if err != nil {
return
}
cc = &ConnClient{
Client: Client{
Writer: conn,
},
conn: conn,
ipv6: ipv6(opts.Ipv6, opts.Network, conn),
}
cc.Client.Dispatcher = &cc.d
go cc.reader()
return
}
func (c *ConnClient) Close() error {
return c.conn.Close()
}
func (c *ConnClient) Announce(
ctx context.Context, req AnnounceRequest, opts Options,
) (
h AnnounceResponseHeader, nas AnnounceResponsePeers, err error,
) {
nas = func() AnnounceResponsePeers {
if c.ipv6 {
return &krpc.CompactIPv6NodeAddrs{}
} else {
return &krpc.CompactIPv4NodeAddrs{}
}
}()
h, err = c.Client.Announce(ctx, req, nas, opts)
return
}