forked from boringproxy/boringproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_proxy.go
102 lines (82 loc) · 2.04 KB
/
tls_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
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
package boringproxy
import (
//"errors"
"crypto/tls"
"fmt"
"io"
"log"
"net"
"strings"
"sync"
"time"
"github.com/caddyserver/certmagic"
)
func ProxyTcp(conn net.Conn, addr string, port int, useTls bool, certConfig *certmagic.Config) error {
if useTls {
tlsConfig := &tls.Config{
GetCertificate: certConfig.GetCertificate,
}
tlsConfig.NextProtos = append([]string{"http/1.1", "h2", "acme-tls/1"}, tlsConfig.NextProtos...)
tlsConn := tls.Server(conn, tlsConfig)
tlsConn.Handshake()
if tlsConn.ConnectionState().NegotiatedProtocol == "acme-tls/1" {
tlsConn.Close()
return nil
}
go handleConnection(tlsConn, addr, port)
} else {
go handleConnection(conn, addr, port)
}
return nil
}
func handleConnection(conn net.Conn, upstreamAddr string, port int) {
useTls := false
addr := upstreamAddr
if strings.HasPrefix(upstreamAddr, "https://") {
addr = upstreamAddr[len("https://"):]
useTls = true
}
var upstreamConn net.Conn
var err error
if useTls {
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
}
upstreamConn, err = tls.Dial("tcp", fmt.Sprintf("%s:%d", addr, port), tlsConfig)
} else {
upstreamConn, err = net.Dial("tcp", fmt.Sprintf("%s:%d", addr, port))
}
if err != nil {
log.Println("Error when establishing connection:", err)
conn.Close()
return
}
deadline := time.Now().Add(3 * time.Hour)
conn.SetDeadline(deadline)
upstreamConn.SetDeadline(deadline)
var wg sync.WaitGroup
wg.Add(2)
// Copy request to upstream
go func() {
defer wg.Done()
defer upstreamConn.Close()
defer conn.Close()
_, err := io.Copy(upstreamConn, conn)
if err != nil {
log.Printf("Error when copying request to upstream (%s:%d): %s", upstreamAddr, port, err)
}
}()
// Copy response to downstream
go func() {
defer wg.Done()
defer conn.Close()
defer upstreamConn.Close()
_, err := io.Copy(conn, upstreamConn)
if err != nil {
log.Printf("Error when copying response to downstream (%s:%d): %s", upstreamAddr, port, err)
}
}()
defer upstreamConn.Close()
defer conn.Close()
wg.Wait()
}