/
tcp.go
70 lines (57 loc) · 1.38 KB
/
tcp.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
package tun2Pipe
import (
"fmt"
"io"
"log"
"math"
"net"
"syscall"
)
func (t2s *Tun2Pipe) simpleForward(conn net.Conn) {
leftConn := conn.(*net.TCPConn)
leftConn.SetKeepAlive(true)
port := leftConn.RemoteAddr().(*net.TCPAddr).Port
s := t2s.getSession(port)
if s == nil {
log.Println(fmt.Sprintln("Can't proxy this one:", leftConn.RemoteAddr()))
return
}
defer t2s.removeSession(port)
defer leftConn.Close()
log.Println(fmt.Sprintln("Tun New conn for tcp session:", s.ToString()))
tgtAddr := fmt.Sprintf("%s:%d", s.RemoteIP, s.RemotePort)
buff := make([]byte, math.MaxInt16)
for {
n, e := leftConn.Read(buff)
if e != nil {
if e != io.EOF {
log.Println(fmt.Sprintln("Tun Read from left conn err:", e))
}
return
}
if s.Pipe == nil {
d := &net.Dialer{
Timeout: SysDialTimeOut,
Control: func(network, address string, c syscall.RawConn) error {
return c.Control(Protector)
},
}
c, e := d.Dial("tcp", tgtAddr)
if e != nil {
log.Println(fmt.Sprintln("Dial remote err:", e))
return
}
rightConn := c.(*net.TCPConn)
rightConn.SetKeepAlive(true)
log.Println(fmt.Sprintf("TCP:Tun Pipe dial success: %s->%s:", rightConn.LocalAddr(), s.ToString()))
s.Pipe = &directPipe{
Left: leftConn,
Right: rightConn,
}
go s.Pipe.readingIn()
}
if err := s.Pipe.writeOut(buff[:n]); err != nil {
return
}
}
}