-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
217 lines (200 loc) · 5.97 KB
/
handler.go
File metadata and controls
217 lines (200 loc) · 5.97 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package sniproxy
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"math/rand"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/pires/go-proxyproto"
"github.com/xxxsen/common/iotool"
"github.com/xxxsen/common/logutil"
"go.uber.org/zap"
)
type connHandler struct {
conn net.Conn
svr *sniproxyImpl
//中间产物
ruleData *DomainRuleItem
isTLS bool
sni string
port string
nextTarget string
//
remote net.Conn
}
func newConnHandler(conn net.Conn, svr *sniproxyImpl) *connHandler {
return &connHandler{conn: conn, svr: svr}
}
func (h *connHandler) Serve(ctx context.Context) {
defer func() {
_ = h.conn.Close()
if h.remote != nil {
_ = h.remote.Close()
}
}()
handlers := []struct {
name string
fn func(ctx context.Context) error
}{
{"resolve_sni", h.doResolveSNI},
{"select_rule", h.doSelectRule},
{"check_whitelist", h.doCheckWhiteList},
{"dns_resolve", h.doDNSResolve},
{"port_rewrite", h.doPortRewrite},
{"dial_remote", h.doDialRemote},
{"proxy_protocol", h.doProxyProtocol},
{"proxy_request", h.doProxy},
}
start := time.Now()
for _, step := range handlers {
stepStart := time.Now()
if err := step.fn(ctx); err != nil {
logutil.GetLogger(ctx).Error("process step failed", zap.Error(err), zap.String("step", step.name))
return
}
logutil.GetLogger(ctx).Debug("process step succ", zap.String("step", step.name), zap.Duration("cost", time.Since(stepStart)))
}
logutil.GetLogger(ctx).Info("processs sni proxy succ", zap.String("sni", h.sni), zap.Bool("is_tls", h.isTLS),
zap.String("next_target", h.nextTarget), zap.String("port", h.port), zap.Duration("cost", time.Since(start)))
}
func (h *connHandler) doResolveTlsTarget(ctx context.Context, r *bufio.Reader) (string, string, error) {
var hello *tls.ClientHelloInfo
err := tls.Server(iotool.NewReadOnlyConn(r), &tls.Config{
GetConfigForClient: func(argHello *tls.ClientHelloInfo) (*tls.Config, error) {
hello = new(tls.ClientHelloInfo)
*hello = *argHello
return nil, nil
},
}).Handshake()
_ = err
if hello == nil {
return "", "", fmt.Errorf("no sni found")
}
return hello.ServerName, "443", nil
}
func (h *connHandler) doResolveHTTPTarget(ctx context.Context, r *bufio.Reader) (string, string, error) {
req, err := http.ReadRequest(r)
if err != nil {
return "", "", err
}
hostport := strings.TrimSpace(req.Host)
if len(hostport) == 0 {
return "", "", fmt.Errorf("no host found")
}
host, port, err := net.SplitHostPort(hostport)
if err == nil {
return host, port, nil
}
return hostport, "80", nil
}
func (h *connHandler) doResolveSNI(ctx context.Context) error {
_ = h.conn.SetReadDeadline(time.Now().Add(h.svr.c.detectTimeout))
defer func() {
_ = h.conn.SetReadDeadline(time.Time{})
}()
peekedBytes := new(bytes.Buffer)
r := io.TeeReader(h.conn, peekedBytes)
bio := bufio.NewReader(r)
bs, err := bio.Peek(1)
if err != nil {
return fmt.Errorf("read first byte failed, err:%w", err)
}
var detecter func(ctx context.Context, r *bufio.Reader) (string, string, error)
switch bs[0] {
case 'G', 'P', 'C', 'H', 'O', 'D', 'T': //HTTP GET/PUT/CONNECT/HEAD/OPTION/DELETE/TRACE
detecter = h.doResolveHTTPTarget
default:
detecter = h.doResolveTlsTarget
h.isTLS = true
}
domain, port, err := detecter(ctx, bio)
if err != nil {
return fmt.Errorf("detect sni failed, err:%w", err)
}
r = io.MultiReader(peekedBytes, h.conn)
h.conn = iotool.WrapConn(h.conn, r, nil, nil)
h.sni = domain
h.port = port
return nil
}
func (h *connHandler) doSelectRule(ctx context.Context) error {
data, ok, err := h.svr.checker.Check(ctx, h.sni)
if err != nil {
return fmt.Errorf("check rule failed, err:%w", err)
}
if !ok {
return fmt.Errorf("sni not in white list, name:%s", h.sni)
}
h.ruleData = data.(*DomainRuleItem)
return nil
}
func (h *connHandler) doCheckWhiteList(ctx context.Context) error {
host, _, err := net.SplitHostPort(h.conn.RemoteAddr().String())
if err != nil {
return fmt.Errorf("unable to read remote host, err:%w", err)
}
ok, err := h.ruleData.WhiteList.Check(host)
if err != nil {
return fmt.Errorf("check white list failed, err:%w", err)
}
if !ok {
return fmt.Errorf("remote host not in white list, skip next, host:%s", host)
}
return nil
}
func (h *connHandler) doDNSResolve(ctx context.Context) error {
logutil.GetLogger(ctx).Debug("domain match rule", zap.String("domain", h.sni), zap.String("rewrite", h.ruleData.DomainRewrite),
zap.String("rule", h.ruleData.Rule))
domain := h.sni
if len(h.ruleData.DomainRewrite) > 0 {
domain = h.ruleData.DomainRewrite
}
ips, err := h.ruleData.Resolver.Resolve(ctx, domain)
if err != nil {
return err
}
if len(ips) == 0 {
return fmt.Errorf("no ip link with domain")
}
h.nextTarget = ips[rand.Int()%len(ips)].String()
return nil
}
func (h *connHandler) doPortRewrite(ctx context.Context) error {
if h.ruleData.TLSPortRewrite > 0 && h.isTLS {
logutil.GetLogger(ctx).Debug("rewrite tls port", zap.String("old_port", h.port), zap.Uint16("new_port", h.ruleData.TLSPortRewrite))
h.port = strconv.FormatUint(uint64(h.ruleData.TLSPortRewrite), 10)
}
if h.ruleData.HTTPPortRewrite > 0 && !h.isTLS {
logutil.GetLogger(ctx).Debug("rewrite http port", zap.String("old_port", h.port), zap.Uint16("new_port", h.ruleData.HTTPPortRewrite))
h.port = strconv.FormatUint(uint64(h.ruleData.HTTPPortRewrite), 10)
}
return nil
}
func (h *connHandler) doDialRemote(ctx context.Context) error {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(h.nextTarget, h.port), h.svr.c.dialTimeout)
if err != nil {
return err
}
h.remote = conn
return nil
}
func (h *connHandler) doProxyProtocol(ctx context.Context) error {
if !h.ruleData.ProxyProtocol {
return nil
}
hdr := proxyproto.HeaderProxyFromAddrs(0, h.conn.RemoteAddr(), h.conn.LocalAddr())
if _, err := hdr.WriteTo(h.remote); err != nil {
return fmt.Errorf("write proxy protocol failed, err:%w", err)
}
return nil
}
func (h *connHandler) doProxy(ctx context.Context) error {
return iotool.ProxyStream(ctx, h.conn, h.remote)
}