-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn_proxy.go
49 lines (46 loc) · 1.1 KB
/
conn_proxy.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
package main
import (
"fmt"
"io"
"log"
"net"
"strings"
)
func split(addr net.Addr) (string, string, error) {
tmp := strings.Split(addr.String(), ":")
ip := net.ParseIP(tmp[0]).To4()
if ip == nil {
return "", "", fmt.Errorf("source address %s is not a tcp4 IP", tmp[0])
}
return ip.String(), tmp[1], nil
}
func forward(backendHostport string, conn net.Conn, proxyproto bool) {
backend, err := net.Dial("tcp", backendHostport)
if err != nil {
log.Printf("Dial failed: %v", err)
conn.Close()
return
}
if proxyproto {
tcpversion := "TCP4"
srcaddr, srcport, srcerr := split(conn.RemoteAddr())
dstaddr, dstport, _ := split(conn.LocalAddr())
if srcerr != nil { // source address is not tcp4
log.Print("address is not TCPv4 ", conn.RemoteAddr())
conn.Close()
return
}
proxyheader := fmt.Sprintf("PROXY %s %s %s %s %s\r\n", tcpversion, srcaddr, dstaddr, srcport, dstport)
backend.Write([]byte(proxyheader))
}
go func() {
defer backend.Close()
defer conn.Close()
io.Copy(backend, conn)
}()
go func() {
defer backend.Close()
defer conn.Close()
io.Copy(conn, backend)
}()
}