-
Notifications
You must be signed in to change notification settings - Fork 0
/
relayer.go
76 lines (59 loc) · 1.34 KB
/
relayer.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
package xtcprelay
import (
"io"
"log"
"net"
)
type Relayer interface {
RelayerServerSide
RelayerClientSide
}
type RelayerServerSide interface {
io.Closer
Listen(address string) (net.Listener, error)
}
type RelayerClientSide interface {
io.Closer
Dial(address string) (net.Conn, error)
}
func copy(dst, src io.ReadWriteCloser) error {
c := make(chan error, 2)
go func() {
_, err := io.Copy(dst, src)
c <- err
}()
go func() {
_, err := io.Copy(src, dst)
c <- err
}()
defer src.Close()
defer dst.Close()
return <-c
}
func relay(l net.Listener, dialer func(address string) (net.Conn, error)) error {
for {
conn, err := l.Accept()
if err != nil {
log.Printf("failed to accept connection: %v", err)
continue
}
transit, err := dialer(conn.RemoteAddr().String())
if err != nil {
log.Printf("failed to dial relay connection: %v", err)
continue
}
go copy(conn, transit)
}
}
func RunRelayerClientSide(r RelayerClientSide, l net.Listener, addressmapper func(address string) string) error {
return relay(l, func(address string) (net.Conn, error) {
return r.Dial(addressmapper(address))
})
}
func RunRelayerServerSide(r RelayerServerSide, listenAddress string, dialer func(address string) (net.Conn, error)) error {
l, err := r.Listen(listenAddress)
if err != nil {
return err
}
return relay(l, dialer)
}