-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforward.go
58 lines (54 loc) · 1.18 KB
/
forward.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
package sniproxy
import (
"bufio"
"bytes"
"io"
"net"
"net/http"
"strconv"
"sync"
)
type Dial func(network, address string) (net.Conn, error)
func ForwardHTTP(conn net.Conn, dial Dial) {
defer conn.Close()
var peeked bytes.Buffer
request, err := http.ReadRequest(bufio.NewReader(io.TeeReader(conn, &peeked)))
if err != nil {
return
}
port := conn.LocalAddr().(*net.TCPAddr).Port
host := net.JoinHostPort(request.Host, strconv.Itoa(port))
remote, err := dial("tcp", host)
if err != nil {
return
}
_, _ = remote.Write(peeked.Bytes())
var wg sync.WaitGroup
wg.Add(2)
go copyConn(conn, remote, &wg)
go copyConn(remote, conn, &wg)
wg.Wait()
return
}
func ForwardTLS(conn net.Conn, dial Dial) {
defer conn.Close()
var peeked bytes.Buffer
serverName := readClientHello(io.TeeReader(conn, &peeked))
if serverName == "" {
return
}
port := conn.LocalAddr().(*net.TCPAddr).Port
host := net.JoinHostPort(serverName, strconv.Itoa(port))
remote, err := dial("tcp", host)
if err != nil {
err = conn.Close()
return
}
_, _ = remote.Write(peeked.Bytes())
var wg sync.WaitGroup
wg.Add(2)
go copyConn(conn, remote, &wg)
go copyConn(remote, conn, &wg)
wg.Wait()
return
}