forked from dragonflyoss/Dragonfly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
389 lines (341 loc) · 9.81 KB
/
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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package proxy
import (
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"strings"
"sync"
"time"
"github.com/dragonflyoss/Dragonfly/dfdaemon/config"
"github.com/dragonflyoss/Dragonfly/dfdaemon/downloader"
"github.com/dragonflyoss/Dragonfly/dfdaemon/downloader/dfget"
"github.com/dragonflyoss/Dragonfly/dfdaemon/transport"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// Option is a functional option for configuring the proxy
type Option func(p *Proxy) error
// WithCert sets the certificate to
func WithCert(cert *tls.Certificate) Option {
return func(p *Proxy) error {
p.cert = cert
return nil
}
}
// WithHTTPSHosts sets the rules for hijacking https requests
func WithHTTPSHosts(hosts ...*config.HijackHost) Option {
return func(p *Proxy) error {
p.httpsHosts = hosts
return nil
}
}
// WithRegistryMirror sets the registry mirror for the proxy
func WithRegistryMirror(r *config.RegistryMirror) Option {
return func(p *Proxy) error {
p.registry = r
return nil
}
}
// WithCertFromFile is a convenient wrapper for WithCert, to read certificate from
// the given file
func WithCertFromFile(certFile, keyFile string) Option {
return func(p *Proxy) error {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return errors.Wrap(err, "load cert")
}
logrus.Infof("use self-signed certificate (%s, %s) for https hijacking", certFile, keyFile)
p.cert = &cert
return nil
}
}
// WithDirectHandler sets the handler for non-proxy requests
func WithDirectHandler(h *http.ServeMux) Option {
return func(p *Proxy) error {
// Make sure the root handler of the given server mux is the
// registry mirror reverse proxy
h.HandleFunc("/", p.mirrorRegistry)
p.directHandler = h
return nil
}
}
// WithRules sets the proxy rules
func WithRules(rules []*config.Proxy) Option {
return func(p *Proxy) error { return p.SetRules(rules) }
}
// WithDownloaderFactory sets the factory function to get a downloader
func WithDownloaderFactory(f downloader.Factory) Option {
return func(p *Proxy) error {
p.downloadFactory = f
return nil
}
}
// New returns a new transparent proxy with the given rules
func New(opts ...Option) (*Proxy, error) {
proxy := &Proxy{
directHandler: http.NewServeMux(),
}
for _, opt := range opts {
if err := opt(proxy); err != nil {
return nil, err
}
}
return proxy, nil
}
// NewFromConfig returns a new transparent proxy from the given properties
func NewFromConfig(c config.Properties) (*Proxy, error) {
opts := []Option{
WithRules(c.Proxies),
WithRegistryMirror(c.RegistryMirror),
WithDownloaderFactory(func() downloader.Interface {
return dfget.NewGetter(c.DFGetConfig())
}),
}
logrus.Infof("registry mirror: %s", c.RegistryMirror.Remote)
if len(c.Proxies) > 0 {
logrus.Infof("%d proxy rules loaded", len(c.Proxies))
for i, r := range c.Proxies {
method := "with dfget"
if r.Direct {
method = "directly"
}
scheme := ""
if r.UseHTTPS {
scheme = "and force https"
}
logrus.Infof("[%d] proxy %s %s %s", i+1, r.Regx, method, scheme)
}
}
if len(c.SuperNodes) > 0 {
logrus.Infof("use supernodes: %s", strings.Join(c.SuperNodes, ","))
}
logrus.Infof("rate limit set to %s", c.RateLimit)
if c.HijackHTTPS != nil {
opts = append(opts, WithHTTPSHosts(c.HijackHTTPS.Hosts...))
if c.HijackHTTPS.Cert != "" && c.HijackHTTPS.Key != "" {
opts = append(opts, WithCertFromFile(c.HijackHTTPS.Cert, c.HijackHTTPS.Key))
}
}
return New(opts...)
}
// Proxy is an http proxy handler. It proxies requests with dfget
// if any defined proxy rules is matched
type Proxy struct {
// reverse proxy upstream url for the default registry
registry *config.RegistryMirror
// proxy rules
rules []*config.Proxy
// httpsHosts is the list of hosts whose https requests will be hijacked
httpsHosts []*config.HijackHost
// cert is the certificate used to hijack https proxy requests
cert *tls.Certificate
// directHandler are used to handle non proxy requests
directHandler http.Handler
// downloadFactory returns the downloader used for p2p downloading
downloadFactory downloader.Factory
}
func (proxy *Proxy) mirrorRegistry(w http.ResponseWriter, r *http.Request) {
reverseProxy := httputil.NewSingleHostReverseProxy(proxy.registry.Remote.URL)
t, err := transport.New(
transport.WithDownloader(proxy.downloadFactory()),
transport.WithTLS(proxy.registry.TLSConfig()),
)
if err != nil {
http.Error(w, fmt.Sprintf("failed to get transport: %v", err), http.StatusInternalServerError)
}
reverseProxy.Transport = t
reverseProxy.ServeHTTP(w, r)
}
// remoteConfig returns the tls.Config used to connect to the given remote host.
// If the host should not be hijacked, nil will be returned.
func (proxy *Proxy) remoteConfig(host string) *tls.Config {
for _, h := range proxy.httpsHosts {
if h.Regx.MatchString(host) {
config := &tls.Config{InsecureSkipVerify: h.Insecure}
if h.Certs != nil {
config.RootCAs = h.Certs.CertPool
}
return config
}
}
return nil
}
// SetRules change the rule lists of the proxy to the given rules
func (proxy *Proxy) SetRules(rules []*config.Proxy) error {
proxy.rules = rules
return nil
}
// ServeHTTP implements http.Handler.ServeHTTP
func (proxy *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodConnect {
// handle https proxy requests
proxy.handleHTTPS(w, r)
} else if r.URL.Scheme == "" {
// handle direct requests
proxy.directHandler.ServeHTTP(w, r)
} else {
// handle http proxy requests
proxy.handleHTTP(w, r)
}
}
func (proxy *Proxy) handleHTTP(w http.ResponseWriter, req *http.Request) {
resp, err := proxy.roundTripper(nil).RoundTrip(req)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
defer resp.Body.Close()
copyHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
if _, err := io.Copy(w, resp.Body); err != nil {
logrus.Errorf("failed to write http body")
}
}
func (proxy *Proxy) roundTripper(tlsConfig *tls.Config) http.RoundTripper {
rt, _ := transport.New(
transport.WithDownloader(proxy.downloadFactory()),
transport.WithTLS(tlsConfig),
transport.WithCondition(proxy.shouldUseDfget),
)
return rt
}
// shouldUseDfget returns whether we should use dfget to proxy a request. It
// also change the scheme of the given request if the matched rule has
// UseHTTPS = true
func (proxy *Proxy) shouldUseDfget(req *http.Request) bool {
if req.Method != http.MethodGet {
return false
}
for _, rule := range proxy.rules {
if rule.Match(req.URL.String()) {
if rule.UseHTTPS {
req.URL.Scheme = "https"
}
return !rule.Direct
}
}
return false
}
// tunnelHTTPS handles a CONNECT request and proxy an https request through an
// http tunnel.
func tunnelHTTPS(w http.ResponseWriter, r *http.Request) {
logrus.Debugf("Tunneling https request for %s", r.Host)
dst, err := net.DialTimeout("tcp", r.Host, 10*time.Second)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
}
clientConn, _, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
go copyAndClose(dst, clientConn)
go copyAndClose(clientConn, dst)
}
func (proxy *Proxy) handleHTTPS(w http.ResponseWriter, r *http.Request) {
if proxy.cert == nil {
tunnelHTTPS(w, r)
return
}
cConfig := proxy.remoteConfig(r.Host)
if cConfig == nil {
tunnelHTTPS(w, r)
return
}
logrus.Debugln("hijack https request to", r.Host)
sConfig := new(tls.Config)
sConfig.Certificates = []tls.Certificate{*proxy.cert}
sConn, err := handshake(w, sConfig)
if err != nil {
logrus.Errorf("handshake failed for %s: %v", r.Host, err)
return
}
defer sConn.Close()
cConn, err := tls.Dial("tcp", r.Host, cConfig)
if err != nil {
logrus.Errorf("dial failed for %s: %v", r.Host, err)
return
}
defer cConn.Close()
rp := &httputil.ReverseProxy{
Director: func(r *http.Request) {
r.URL.Host = r.Host
r.URL.Scheme = "https"
},
Transport: proxy.roundTripper(cConfig),
}
// We have to wait until the connection is closed
wg := sync.WaitGroup{}
wg.Add(1)
http.Serve(&singleUseListener{&customCloseConn{sConn, wg.Done}}, rp)
wg.Wait()
}
func copyAndClose(dst io.WriteCloser, src io.ReadCloser) {
io.Copy(dst, src)
dst.Close()
src.Close()
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
var okHeader = []byte("HTTP/1.1 200 OK\r\n\r\n")
// handshake hijacks w's underlying net.Conn, responds to the CONNECT request
// and manually performs the TLS handshake.
func handshake(w http.ResponseWriter, config *tls.Config) (net.Conn, error) {
raw, _, err := w.(http.Hijacker).Hijack()
if err != nil {
http.Error(w, "no upstream", http.StatusServiceUnavailable)
return nil, err
}
if _, err = raw.Write(okHeader); err != nil {
raw.Close()
return nil, err
}
conn := tls.Server(raw, config)
if err = conn.Handshake(); err != nil {
conn.Close()
raw.Close()
return nil, err
}
return conn, nil
}
// A singleUseListener implements a net.Listener that returns the net.Conn specified
// in c for the first Accept call, and return errors for the subsequent calls.
type singleUseListener struct {
c net.Conn
}
func (l *singleUseListener) Accept() (net.Conn, error) {
if l.c == nil {
return nil, errors.New("closed")
}
c := l.c
l.c = nil
return c, nil
}
func (l *singleUseListener) Close() error { return nil }
func (l *singleUseListener) Addr() net.Addr { return l.c.LocalAddr() }
// A customCloseConn implements net.Conn and calls f before closing the underlying net.Conn
type customCloseConn struct {
net.Conn
f func()
}
func (c *customCloseConn) Close() error {
if c.f != nil {
c.f()
c.f = nil
}
return c.Conn.Close()
}