forked from TuanKiri/socks5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.go
104 lines (83 loc) Β· 1.68 KB
/
connection.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
package socks5
import (
"bufio"
"bytes"
"io"
"net"
)
type connection struct {
net.Conn
reader *bufio.Reader
done chan struct{}
closeFn func()
}
func newConnection(conn net.Conn) *connection {
return &connection{
Conn: conn,
reader: bufio.NewReader(conn),
done: make(chan struct{}),
}
}
func (c *connection) readByte() (byte, error) {
return c.reader.ReadByte()
}
func (c *connection) read(p []byte) (int, error) {
return c.reader.Read(p)
}
func (c *connection) write(p []byte) (int, error) {
return c.Conn.Write(p)
}
func (c *connection) isActive() bool {
select {
case <-c.done:
return false
default:
return true
}
}
func (c *connection) equalAddresses(address net.Addr) bool {
currentHost, _, err := net.SplitHostPort(c.RemoteAddr().String())
if err != nil {
return false
}
incomingHost, _, err := net.SplitHostPort(address.String())
if err != nil {
return false
}
return currentHost == incomingHost
}
func (c *connection) onClose(f func()) {
c.closeFn = f
}
func (c *connection) keepAlive() {
io.Copy(io.Discard, c)
if !c.isActive() {
return
}
c.closeFn()
close(c.done)
}
type packetConn struct {
net.PacketConn
net.Addr
reader *bytes.Buffer
}
func newPacketConn(conn net.PacketConn, addr net.Addr, data []byte) *packetConn {
return &packetConn{
PacketConn: conn,
Addr: addr,
reader: bytes.NewBuffer(data),
}
}
func (c *packetConn) readByte() (byte, error) {
return c.reader.ReadByte()
}
func (c *packetConn) read(p []byte) (int, error) {
return c.reader.Read(p)
}
func (c *packetConn) write(p []byte) (int, error) {
return c.PacketConn.WriteTo(p, c.Addr)
}
func (c *packetConn) bytes() []byte {
return c.reader.Bytes()
}