forked from p4gefau1t/trojan-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
112 lines (102 loc) · 2.24 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
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
112
package router
import (
"context"
"io"
"net"
"github.com/p4gefau1t/trojan-go/common"
"github.com/p4gefau1t/trojan-go/log"
"github.com/p4gefau1t/trojan-go/tunnel"
)
type packetInfo struct {
src *tunnel.Metadata
payload []byte
}
type PacketConn struct {
proxy tunnel.PacketConn
net.PacketConn
packetChan chan *packetInfo
*Client
ctx context.Context
cancel context.CancelFunc
}
func (c *PacketConn) packetLoop() {
go func() {
for {
buf := make([]byte, MaxPacketSize)
n, addr, err := c.proxy.ReadWithMetadata(buf)
if err != nil {
select {
case <-c.ctx.Done():
return
default:
log.Error("router packetConn error", err)
continue
}
}
c.packetChan <- &packetInfo{
src: addr,
payload: buf[:n],
}
}
}()
for {
buf := make([]byte, MaxPacketSize)
n, addr, err := c.PacketConn.ReadFrom(buf)
if err != nil {
select {
case <-c.ctx.Done():
return
default:
log.Error("router packetConn error", err)
continue
}
}
address, _ := tunnel.NewAddressFromAddr("udp", addr.String())
c.packetChan <- &packetInfo{
src: &tunnel.Metadata{
Address: address,
},
payload: buf[:n],
}
}
}
func (c *PacketConn) Close() error {
c.cancel()
c.proxy.Close()
return c.PacketConn.Close()
}
func (c *PacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
panic("implement me")
}
func (c *PacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
panic("implement me")
}
func (c *PacketConn) WriteWithMetadata(p []byte, m *tunnel.Metadata) (int, error) {
policy := c.Route(m.Address)
switch policy {
case Proxy:
return c.proxy.WriteWithMetadata(p, m)
case Block:
return 0, common.NewError("router blocked address (udp): " + m.Address.String())
case Bypass:
ip, err := m.Address.ResolveIP()
if err != nil {
return 0, common.NewError("router failed to resolve udp address").Base(err)
}
return c.PacketConn.WriteTo(p, &net.UDPAddr{
IP: ip,
Port: m.Address.Port,
})
default:
panic("unknown policy")
}
}
func (c *PacketConn) ReadWithMetadata(p []byte) (int, *tunnel.Metadata, error) {
select {
case info := <-c.packetChan:
n := copy(p, info.payload)
return n, info.src, nil
case <-c.ctx.Done():
return 0, nil, io.EOF
}
}