forked from kevwan/tproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
112 lines (92 loc) · 2.58 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 main
import (
"fmt"
"io"
"net"
"sync"
"github.com/fatih/color"
"github.com/kevwan/tproxy/display"
"github.com/kevwan/tproxy/protocol"
)
const (
serverSide = "SERVER"
clientSide = "CLIENT"
useOfClosedConn = "use of closed network connection"
)
type PairedConnection struct {
id int
cliConn net.Conn
svrConn net.Conn
once sync.Once
}
func NewPairedConnection(id int, cliConn net.Conn) *PairedConnection {
return &PairedConnection{
id: id,
cliConn: cliConn,
}
}
func (c *PairedConnection) handleClientMessage() {
r, w := io.Pipe()
tee := io.MultiWriter(c.svrConn, w)
go protocol.NewDumper(r, clientSide, c.id, settings.Silent, protocol.CreateInterop(settings.Protocol)).Dump()
_, e := io.Copy(tee, c.cliConn)
if e != nil && e != io.EOF {
color.HiRed("handleClientMessage: io.Copy error: %v", e)
}
}
func (c *PairedConnection) handleServerMessage() {
r, w := io.Pipe()
tee := io.MultiWriter(c.cliConn, w)
go protocol.NewDumper(r, serverSide, c.id, settings.Silent, protocol.CreateInterop(settings.Protocol)).Dump()
_, e := io.Copy(tee, c.svrConn)
if e != nil && e != io.EOF {
netOpError, ok := e.(*net.OpError)
if ok && netOpError.Err.Error() != useOfClosedConn {
color.HiRed("handleServerMessage: io.Copy error: %v", e)
}
}
c.stop()
}
func (c *PairedConnection) process() {
conn, err := net.Dial("tcp", settings.RemoteHost)
if err != nil {
display.PrintlnWithTime(color.HiRedString("[x][%d] Couldn't connect to server: %v", c.id, err))
return
}
display.PrintlnWithTime(color.HiGreenString("[%d] Connected to server: %s", c.id, conn.RemoteAddr()))
c.svrConn = conn
go c.handleServerMessage()
c.handleClientMessage()
c.stop()
}
func (c *PairedConnection) stop() {
c.once.Do(func() {
if c.cliConn != nil {
display.PrintlnWithTime(color.HiBlueString("[%d] Client connection closed", c.id))
c.cliConn.Close()
}
if c.svrConn != nil {
display.PrintlnWithTime(color.HiBlueString("[%d] Server connection closed", c.id))
c.svrConn.Close()
}
})
}
func startListener() error {
conn, err := net.Listen("tcp", fmt.Sprint(settings.LocalHost, ":", settings.LocalPort))
if err != nil {
return fmt.Errorf("failed to start listener: %w", err)
}
display.PrintlnWithTime("Listening...")
defer conn.Close()
var connIndex int
for {
cliConn, err := conn.Accept()
if err != nil {
return fmt.Errorf("server: accept: %w", err)
}
connIndex++
display.PrintlnWithTime(color.HiGreenString("[%d] Accepted from: %s", connIndex, cliConn.RemoteAddr()))
pconn := NewPairedConnection(connIndex, cliConn)
go pconn.process()
}
}