forked from p4gefau1t/trojan-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
conn.go
71 lines (60 loc) · 1.49 KB
/
conn.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
package dokodemo
import (
"context"
"net"
"github.com/faireal/trojan-go/common"
"github.com/faireal/trojan-go/tunnel"
)
const MaxPacketSize = 1024 * 8
type Conn struct {
net.Conn
src *tunnel.Address
targetMetadata *tunnel.Metadata
}
func (c *Conn) Metadata() *tunnel.Metadata {
return c.targetMetadata
}
// PacketConn receive packet info from the packet dispatcher
type PacketConn struct {
net.PacketConn
metadata *tunnel.Metadata
input chan []byte
output chan []byte
src net.Addr
ctx context.Context
cancel context.CancelFunc
}
func (c *PacketConn) Close() error {
c.cancel()
// don't close the underlying udp socket
return nil
}
func (c *PacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
return c.ReadWithMetadata(p)
}
func (c *PacketConn) WriteTo(p []byte, addr net.Addr) (int, error) {
address, err := tunnel.NewAddressFromAddr("udp", addr.String())
if err != nil {
return 0, err
}
return c.WriteWithMetadata(p, &tunnel.Metadata{
Address: address,
})
}
func (c *PacketConn) ReadWithMetadata(p []byte) (int, *tunnel.Metadata, error) {
select {
case payload := <-c.input:
n := copy(p, payload)
return n, c.metadata, nil
case <-c.ctx.Done():
return 0, nil, common.NewError("dokodemo packet conn closed")
}
}
func (c *PacketConn) WriteWithMetadata(p []byte, m *tunnel.Metadata) (int, error) {
select {
case c.output <- p:
return len(p), nil
case <-c.ctx.Done():
return 0, common.NewError("dokodemo packet conn failed to write")
}
}