-
Notifications
You must be signed in to change notification settings - Fork 98
/
crproxy.go
731 lines (637 loc) · 16.3 KB
/
crproxy.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
package crproxy
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/textproto"
"net/url"
"strings"
"sync"
"time"
"github.com/daocloud/crproxy/internal/maps"
"github.com/docker/distribution/registry/api/errcode"
"github.com/docker/distribution/registry/client/auth"
"github.com/docker/distribution/registry/client/auth/challenge"
"github.com/docker/distribution/registry/client/transport"
storagedriver "github.com/docker/distribution/registry/storage/driver"
"github.com/wzshiming/geario"
"github.com/wzshiming/hostmatcher"
"github.com/wzshiming/httpseek"
"github.com/wzshiming/lru"
)
var (
prefix = "/v2/"
catalog = prefix + "_catalog"
)
type Logger interface {
Println(v ...interface{})
}
type ImageInfo struct {
Host string
Name string
}
type BlockInfo struct {
IP string
Host string
Name string
}
type CRProxy struct {
baseClient *http.Client
challengeManager challenge.Manager
clientset maps.SyncMap[string, *lru.LRU[string, *http.Client]]
clientSize int
modify func(info *ImageInfo) *ImageInfo
insecureDomain map[string]struct{}
domainDisableKeepAlives map[string]struct{}
domainAlias map[string]string
userAndPass map[string]Userpass
basicCredentials *basicCredentials
mutClientset sync.Mutex
bytesPool sync.Pool
logger Logger
totalBlobsSpeedLimit *geario.Gear
speedLimitRecord maps.SyncMap[string, *geario.BPS]
blobsSpeedLimit *geario.B
blobsSpeedLimitDuration time.Duration
ipsSpeedLimit *geario.B
ipsSpeedLimitDuration time.Duration
blockFunc []func(*BlockInfo) (string, bool)
retry int
retryInterval time.Duration
storageDriver storagedriver.StorageDriver
linkExpires time.Duration
mutCache sync.Map
redirectLinks *url.URL
limitDelay bool
privilegedNoAuth bool
disableTagsList bool
simpleAuth bool
simpleAuthUserpassFunc func(r *http.Request, userinfo *url.Userinfo) bool
tokenURL string
tokenAuthForceTLS bool
matcher hostmatcher.Matcher
defaultRegistry string
overrideDefaultRegistry map[string]string
privilegedFunc func(r *http.Request, info *ImageInfo) bool
redirectToOriginBlobFunc func(r *http.Request, info *ImageInfo) bool
allowHeadMethod bool
manifestCache maps.SyncMap[string, time.Time]
manifestCacheDuration time.Duration
}
type Option func(c *CRProxy)
func WithManifestCacheDuration(d time.Duration) Option {
return func(c *CRProxy) {
c.manifestCacheDuration = d
}
}
func WithPrivilegedFunc(f func(r *http.Request, info *ImageInfo) bool) Option {
return func(c *CRProxy) {
c.privilegedFunc = f
}
}
func WithRedirectToOriginBlobFunc(f func(r *http.Request, info *ImageInfo) bool) Option {
return func(c *CRProxy) {
c.redirectToOriginBlobFunc = f
}
}
func WithSimpleAuth(b bool, tokenURL string, forceTLS bool) Option {
return func(c *CRProxy) {
c.simpleAuth = b
c.tokenURL = tokenURL
c.tokenAuthForceTLS = forceTLS
}
}
func WithSimpleAuthUserFunc(f func(r *http.Request, userinfo *url.Userinfo) bool) Option {
return func(c *CRProxy) {
c.simpleAuthUserpassFunc = f
}
}
func WithDefaultRegistry(target string) Option {
return func(c *CRProxy) {
c.defaultRegistry = target
}
}
func WithOverrideDefaultRegistry(overrideDefaultRegistry map[string]string) Option {
return func(c *CRProxy) {
c.overrideDefaultRegistry = overrideDefaultRegistry
}
}
func WithDisableTagsList(b bool) Option {
return func(c *CRProxy) {
c.disableTagsList = b
}
}
func WithPrivilegedNoAuth(b bool) Option {
return func(c *CRProxy) {
c.privilegedNoAuth = true
}
}
func WithLimitDelay(b bool) Option {
return func(c *CRProxy) {
c.limitDelay = b
}
}
func WithLinkExpires(d time.Duration) Option {
return func(c *CRProxy) {
c.linkExpires = d
}
}
func WithRedirectLinks(l *url.URL) Option {
return func(c *CRProxy) {
c.redirectLinks = l
}
}
func WithStorageDriver(storageDriver storagedriver.StorageDriver) Option {
return func(c *CRProxy) {
c.storageDriver = storageDriver
}
}
func WithBlobsSpeedLimit(limit geario.B, duration time.Duration) Option {
return func(c *CRProxy) {
c.blobsSpeedLimit = &limit
c.blobsSpeedLimitDuration = duration
}
}
func WithIPsSpeedLimit(limit geario.B, duration time.Duration) Option {
return func(c *CRProxy) {
c.ipsSpeedLimit = &limit
c.ipsSpeedLimitDuration = duration
}
}
func WithTotalBlobsSpeedLimit(limit geario.B) Option {
return func(c *CRProxy) {
c.totalBlobsSpeedLimit = geario.NewGear(time.Second, limit)
}
}
func WithBaseClient(baseClient *http.Client) Option {
return func(c *CRProxy) {
c.baseClient = baseClient
}
}
func WithLogger(logger Logger) Option {
return func(c *CRProxy) {
c.logger = logger
}
}
func WithUserAndPass(userAndPass map[string]Userpass) Option {
return func(c *CRProxy) {
c.userAndPass = userAndPass
}
}
func WithDomainAlias(domainAlias map[string]string) Option {
return func(c *CRProxy) {
c.domainAlias = domainAlias
}
}
func WithPathInfoModifyFunc(modify func(info *ImageInfo) *ImageInfo) Option {
return func(c *CRProxy) {
c.modify = modify
}
}
func WithMaxClientSizeForEachRegistry(clientSize int) Option {
return func(c *CRProxy) {
c.clientSize = clientSize
}
}
func WithDisableKeepAlives(disableKeepAlives []string) Option {
return func(c *CRProxy) {
c.domainDisableKeepAlives = map[string]struct{}{}
for _, v := range disableKeepAlives {
c.domainDisableKeepAlives[v] = struct{}{}
}
}
}
func WithBlockFunc(blockFunc func(info *BlockInfo) (string, bool)) Option {
return func(c *CRProxy) {
c.blockFunc = append(c.blockFunc, blockFunc)
}
}
func WithRetry(retry int, retryInterval time.Duration) Option {
return func(c *CRProxy) {
c.retry = retry
c.retryInterval = retryInterval
}
}
func WithAllowHeadMethod(allowHeadMethod bool) Option {
return func(c *CRProxy) {
c.allowHeadMethod = allowHeadMethod
}
}
func NewCRProxy(opts ...Option) (*CRProxy, error) {
c := &CRProxy{
challengeManager: challenge.NewSimpleManager(),
clientSize: 10240,
baseClient: http.DefaultClient,
bytesPool: sync.Pool{
New: func() interface{} {
return make([]byte, 32*1024)
},
},
}
for _, opt := range opts {
opt(c)
}
if len(c.userAndPass) != 0 {
bc, err := newBasicCredentials(c.userAndPass, c.getDomainAlias, c.getScheme)
if err != nil {
return nil, err
}
c.basicCredentials = bc
}
return c, nil
}
func (c *CRProxy) hostURL(host string) string {
return c.getScheme(host) + "://" + host
}
func (c *CRProxy) pingURL(host string) string {
return c.hostURL(host) + prefix
}
func (c *CRProxy) getScheme(host string) string {
if c.insecureDomain != nil {
_, ok := c.insecureDomain[host]
if ok {
return "http"
}
}
return "https"
}
func (c *CRProxy) getClientset(host string, image string) *http.Client {
sets, hasSets := c.clientset.Load(host)
if hasSets {
client, ok := sets.Get(image)
if ok {
return client
}
}
c.mutClientset.Lock()
defer c.mutClientset.Unlock()
if sets == nil {
sets = lru.NewLRU(c.clientSize, func(image string, client *http.Client) {
if c.logger != nil {
c.logger.Println("evicted client", host, image)
}
client.CloseIdleConnections()
})
c.clientset.Store(host, sets)
}
if c.logger != nil {
c.logger.Println("cache client", host, image)
}
var credentialStore auth.CredentialStore
if c.basicCredentials != nil {
credentialStore = c.basicCredentials
}
authHandler := auth.NewTokenHandler(nil, credentialStore, image, "pull")
tr := c.baseClient.Transport
if c.domainDisableKeepAlives != nil {
if _, ok := c.domainDisableKeepAlives[host]; ok {
tr = c.disableKeepAlives(tr)
}
}
if c.retryInterval > 0 {
if tr == nil {
tr = http.DefaultTransport
}
tr = httpseek.NewMustReaderTransport(tr, func(request *http.Request, retry int, err error) error {
if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) {
return err
}
if c.retry > 0 && retry >= c.retry {
return err
}
if c.logger != nil {
c.logger.Println("Retry", request.URL, retry, err)
}
time.Sleep(c.retryInterval)
return nil
})
}
tr = transport.NewTransport(tr, auth.NewAuthorizer(c.challengeManager, authHandler))
client := &http.Client{
Transport: tr,
CheckRedirect: c.baseClient.CheckRedirect,
Timeout: c.baseClient.Timeout,
Jar: c.baseClient.Jar,
}
sets.Put(image, client)
return client
}
func (c *CRProxy) disableKeepAlives(rt http.RoundTripper) http.RoundTripper {
if rt == nil {
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.DisableKeepAlives = true
return tr
}
if tr, ok := rt.(*http.Transport); ok {
if !tr.DisableKeepAlives {
tr = tr.Clone()
tr.DisableKeepAlives = true
}
return tr
}
if c.logger != nil {
c.logger.Println("failed to disable keep alives")
}
return rt
}
func (c *CRProxy) ping(host string) error {
if c.logger != nil {
c.logger.Println("ping", host)
}
ep := c.pingURL(host)
e, err := url.Parse(ep)
if err != nil {
return err
}
challenges, err := c.challengeManager.GetChallenges(*e)
if err == nil && len(challenges) != 0 {
return nil
}
resp, err := c.baseClient.Get(ep)
if err != nil {
return err
}
defer resp.Body.Close()
err = c.challengeManager.AddResponse(resp)
if err != nil {
return err
}
return nil
}
func apiBase(w http.ResponseWriter, r *http.Request) {
const emptyJSON = "{}"
// Provide a simple /v2/ 200 OK response with empty json response.
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", fmt.Sprint(len(emptyJSON)))
fmt.Fprint(w, emptyJSON)
}
func emptyTagsList(w http.ResponseWriter, r *http.Request) {
const emptyTagsList = `{"name":"disable-list-tags","tags":[]}`
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", fmt.Sprint(len(emptyTagsList)))
fmt.Fprint(w, emptyTagsList)
}
func (c *CRProxy) do(cli *http.Client, r *http.Request) (resp *http.Response, err error) {
if !c.allowHeadMethod && r.Method == http.MethodHead {
r.Method = http.MethodGet
defer func() {
r.Method = http.MethodHead
resp.Body.Close()
resp.Body = http.NoBody
}()
}
resp, err = cli.Do(r)
return resp, err
}
func (c *CRProxy) doWithAuth(cli *http.Client, r *http.Request, host string) (*http.Response, error) {
resp, err := c.do(cli, r)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusUnauthorized {
err = c.ping(host)
if err != nil {
if c.logger != nil {
c.logger.Println("failed to ping", host, err)
}
return resp, nil
}
resp0, err0 := c.do(cli, r)
if err0 != nil {
if c.logger != nil {
c.logger.Println("failed to redo", host, err)
}
return resp, nil
}
resp.Body.Close()
resp = resp0
}
return resp, nil
}
func getIP(str string) string {
host, _, err := net.SplitHostPort(str)
if err == nil && host != "" {
return host
}
return str
}
func (c *CRProxy) block(info *BlockInfo) (string, bool) {
for _, blockFunc := range c.blockFunc {
blockMessage, block := blockFunc(info)
if block {
return blockMessage, true
}
}
return "", false
}
func (c *CRProxy) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
errcode.ServeJSON(rw, errcode.ErrorCodeUnsupported)
return
}
r.RemoteAddr = getIP(r.RemoteAddr)
if c.simpleAuth && !c.authorization(rw, r) {
c.authenticate(rw, r)
return
}
oriPath := r.URL.Path
if oriPath == prefix {
apiBase(rw, r)
return
}
if !strings.HasPrefix(oriPath, prefix) {
c.notFoundResponse(rw, r)
return
}
if oriPath == catalog {
errcode.ServeJSON(rw, errcode.ErrorCodeUnsupported)
return
}
defaultRegistry := c.defaultRegistry
if c.overrideDefaultRegistry != nil {
r, ok := c.overrideDefaultRegistry[r.Host]
if ok {
defaultRegistry = r
}
}
info, ok := ParseOriginPathInfo(oriPath, defaultRegistry)
if !ok {
errcode.ServeJSON(rw, errcode.ErrorCodeDenied)
return
}
if c.modify != nil {
n := c.modify(&ImageInfo{
Host: info.Host,
Name: info.Image,
})
info.Host = n.Host
info.Image = n.Name
}
imageInfo := &ImageInfo{
Host: info.Host,
Name: info.Image,
}
if c.blockFunc != nil && !c.isPrivileged(r, nil) {
blockMessage, block := c.block(&BlockInfo{
IP: r.RemoteAddr,
Host: info.Host,
Name: info.Image,
})
if block {
if blockMessage != "" {
errcode.ServeJSON(rw, errcode.ErrorCodeDenied.WithMessage(blockMessage))
} else {
errcode.ServeJSON(rw, errcode.ErrorCodeDenied)
}
return
}
}
info.Host = c.getDomainAlias(info.Host)
if info.TagsList && !c.isPrivileged(r, nil) && c.disableTagsList {
emptyTagsList(rw, r)
return
}
path, err := info.Path()
if err != nil {
if c.logger != nil {
c.logger.Println("failed to get path", err)
}
errcode.ServeJSON(rw, errcode.ErrorCodeUnknown)
return
}
r.RequestURI = ""
r.Host = info.Host
r.URL.Host = info.Host
r.URL.Scheme = c.getScheme(info.Host)
r.URL.Path = path
r.URL.RawQuery = ""
r.URL.ForceQuery = false
r.Body = http.NoBody
if info.Blobs != "" && c.isRedirectToOriginBlob(r, imageInfo) {
c.redirectBlobResponse(rw, r, info)
return
}
if !c.isPrivileged(r, imageInfo) {
if !c.checkLimit(rw, r, info) {
return
}
}
if c.storageDriver != nil {
if info.Blobs != "" {
c.cacheBlobResponse(rw, r, info)
return
} else if info.Manifests != "" {
c.cacheManifestResponse(rw, r, info)
return
}
}
c.directResponse(rw, r, info)
}
func (c *CRProxy) directResponse(rw http.ResponseWriter, r *http.Request, info *PathInfo) {
cli := c.getClientset(info.Host, info.Image)
resp, err := c.doWithAuth(cli, r, info.Host)
if err != nil {
if c.logger != nil {
c.logger.Println("failed to request", info.Host, info.Image, err)
}
errcode.ServeJSON(rw, errcode.ErrorCodeUnknown)
return
}
defer func() {
resp.Body.Close()
}()
switch resp.StatusCode {
case http.StatusUnauthorized, http.StatusForbidden:
if c.logger != nil {
c.logger.Println("origin direct response 40x, but hit caches", info.Host, info.Image, err, dumpResponse(resp))
}
errcode.ServeJSON(rw, errcode.ErrorCodeDenied)
return
}
resp.Header.Del("Docker-Ratelimit-Source")
if resp.StatusCode == http.StatusOK {
oldLink := resp.Header.Get("Link")
if oldLink != "" {
resp.Header.Set("Link", addPrefixToImageForPagination(oldLink, info.Host))
}
}
header := rw.Header()
for k, v := range resp.Header {
key := textproto.CanonicalMIMEHeaderKey(k)
header[key] = v
}
rw.WriteHeader(resp.StatusCode)
if r.Method != http.MethodHead {
buf := c.bytesPool.Get().([]byte)
defer c.bytesPool.Put(buf)
var body io.Reader = resp.Body
if !c.isPrivileged(r, &ImageInfo{
Host: info.Host,
Name: info.Image,
}) {
c.accumulativeLimit(r, info, resp.ContentLength)
if c.totalBlobsSpeedLimit != nil && info.Blobs != "" {
body = c.totalBlobsSpeedLimit.Reader(body)
}
if c.blobsSpeedLimit != nil && info.Blobs != "" {
body = geario.NewGear(c.blobsSpeedLimitDuration, *c.blobsSpeedLimit).Reader(body)
}
}
io.CopyBuffer(rw, body, buf)
}
}
func (c *CRProxy) errorResponse(rw http.ResponseWriter, r *http.Request, err error) {
if err != nil {
e := err.Error()
if c.logger != nil {
c.logger.Println("error response", r.RemoteAddr, e)
}
}
if err == nil {
err = errcode.ErrorCodeUnknown
}
errcode.ServeJSON(rw, err)
}
func (c *CRProxy) notFoundResponse(rw http.ResponseWriter, r *http.Request) {
http.NotFound(rw, r)
}
func (c *CRProxy) redirect(rw http.ResponseWriter, r *http.Request, blobPath string) error {
options := map[string]interface{}{
"method": r.Method,
}
linkExpires := c.linkExpires
if linkExpires > 0 {
options["expiry"] = time.Now().Add(linkExpires)
}
u, err := c.storageDriver.URLFor(r.Context(), blobPath, options)
if err != nil {
return err
}
if c.logger != nil {
c.logger.Println("Cache hit", blobPath, u)
}
if c.redirectLinks != nil {
uri, err := url.Parse(u)
if err == nil {
uri.Scheme = c.redirectLinks.Scheme
uri.Host = c.redirectLinks.Host
u = uri.String()
}
}
http.Redirect(rw, r, u, http.StatusTemporaryRedirect)
return nil
}
func (c *CRProxy) getDomainAlias(host string) string {
if c.domainAlias == nil {
return host
}
h, ok := c.domainAlias[host]
if !ok {
return host
}
return h
}