forked from txthinking/brook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrelay.go
99 lines (92 loc) · 1.83 KB
/
relay.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
package brook
import (
"io"
"log"
"net"
"time"
)
// Relay is a relay for two network
type Relay struct {
Address string
Server string
Timeout int
Deadline int
Listen net.Listener
}
// NewRelay returns a new Relay
func NewRelay(address, server string, timeout, deadline int) *Relay {
r := &Relay{
Address: address,
Server: server,
Timeout: timeout,
Deadline: deadline,
}
return r
}
// ListenAndServe will let relay start to listen and serve
func (r *Relay) ListenAndServe() error {
ta, err := net.ResolveTCPAddr("tcp", r.Address)
if err != nil {
return err
}
l, err := net.ListenTCP("tcp", ta)
if err != nil {
return err
}
r.Listen = l
for {
conn, err := l.AcceptTCP()
if err != nil {
return err
}
go func(conn *net.TCPConn) {
if err := r.handle(conn); err != nil {
log.Println(err)
}
}(conn)
}
}
// Shutdown used to stop the relay
func (r *Relay) Shutdown() error {
if r.Listen == nil {
return nil
}
return r.Listen.Close()
}
func (r *Relay) handle(conn *net.TCPConn) error {
defer conn.Close()
if r.Timeout != 0 {
if err := conn.SetKeepAlivePeriod(time.Duration(r.Timeout) * time.Second); err != nil {
return err
}
}
if r.Deadline != 0 {
if err := conn.SetDeadline(time.Now().Add(time.Duration(r.Deadline) * time.Second)); err != nil {
return err
}
}
ta, err := net.ResolveTCPAddr("tcp", r.Server)
if err != nil {
return err
}
rc, err := net.DialTCP("tcp", nil, ta)
if err != nil {
return err
}
defer rc.Close()
if r.Timeout != 0 {
if err := rc.SetKeepAlivePeriod(time.Duration(r.Timeout) * time.Second); err != nil {
return err
}
}
if r.Deadline != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(r.Deadline) * time.Second)); err != nil {
return err
}
}
go func() {
_, _ = io.Copy(conn, rc)
}()
_, _ = io.Copy(rc, conn)
return nil
}