forked from goproxy/goproxy.cn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoproxy.go
267 lines (230 loc) · 5.98 KB
/
goproxy.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
package handler
import (
"context"
"crypto/md5"
"encoding/hex"
"io"
"io/fs"
"log"
"net"
"net/http"
"net/url"
"path"
"strings"
"time"
"github.com/aofei/air"
"github.com/goproxy/goproxy"
"github.com/goproxy/goproxy.cn/base"
"github.com/minio/minio-go/v7"
"golang.org/x/mod/module"
"golang.org/x/mod/semver"
)
var (
// goproxyViper is used to get the configuration items of the Goproxy.
goproxyViper = base.Viper.Sub("goproxy")
// hhGoproxy is an instance of the `goproxy.Goproxy`.
hhGoproxy = &goproxy.Goproxy{
GoBinName: goproxyViper.GetString("go_bin_name"),
Cacher: &goproxyCacher{},
CacherMaxCacheBytes: goproxyViper.GetInt("cacher_max_cache_bytes"),
ProxiedSUMDBs: goproxyViper.GetStringSlice("proxied_sumdbs"),
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConnsPerHost: 200,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ForceAttemptHTTP2: true,
},
ErrorLogger: log.New(base.Logger, "", 0),
}
// goproxyFetchTimeout is the maximum duration allowed for Goproxy to
// fetch a module.
goproxyFetchTimeout = goproxyViper.GetDuration("fetch_timeout")
// goproxyAutoRedirect indicates whether the automatic redirection
// feature is enabled for Goproxy.
goproxyAutoRedirect = goproxyViper.GetBool("auto_redirect")
// goproxyAutoRedirectMinSize is the minimum size of the Goproxy used to
// limit at least how big Goproxy cache can be automatically redirected.
goproxyAutoRedirectMinSize = goproxyViper.GetInt64("auto_redirect_min_size")
)
func init() {
base.Air.BATCH(getHeadMethods, "/*", hGoproxy)
}
// hGoproxy handles requests to play with Go module proxy.
func hGoproxy(req *air.Request, res *air.Response) error {
if goproxyFetchTimeout != 0 {
var cancel context.CancelFunc
req.Context, cancel = context.WithTimeout(
req.Context,
goproxyFetchTimeout,
)
defer cancel()
}
name, err := url.PathUnescape(req.ParamValue("*").String())
if err != nil || strings.HasSuffix(name, "/") {
return CacheableNotFound(req, res, 86400)
}
if !goproxyAutoRedirect || path.Ext(name) != ".zip" {
hhGoproxy.ServeHTTP(res.HTTPResponseWriter(), req.HTTPRequest())
return nil
}
if strings.Contains(name, "..") {
for _, part := range strings.Split(name, "/") {
if part == ".." {
return CacheableNotFound(req, res, 86400)
}
}
}
name = strings.TrimPrefix(path.Clean(name), "/")
if !validGoproxyCacheName(name) {
return CacheableNotFound(req, res, 86400)
}
var objectInfo minio.ObjectInfo
if err := retryQiniuKodoDo(req.Context, func(
ctx context.Context,
) (err error) {
objectInfo, err = qiniuKodoClient.StatObject(
ctx,
qiniuKodoBucketName,
name,
minio.StatObjectOptions{},
)
return err
}); err != nil {
if isNotFoundMinIOError(err) {
hhGoproxy.ServeHTTP(
res.HTTPResponseWriter(),
req.HTTPRequest(),
)
return nil
}
return err
}
if objectInfo.Size < goproxyAutoRedirectMinSize {
hhGoproxy.ServeHTTP(res.HTTPResponseWriter(), req.HTTPRequest())
return nil
}
u, err := qiniuKodoClient.Presign(
req.Context,
req.Method,
qiniuKodoBucketName,
objectInfo.Key,
7*24*time.Hour,
url.Values{
"response-cache-control": []string{
"public, max-age=604800",
},
},
)
if err != nil {
return err
}
return res.Redirect(u.String())
}
// goproxyCacher implements the `goproxy.Cacher`.
type goproxyCacher struct{}
// Cache implements the `goproxy.Cacher`.
func (gc *goproxyCacher) Get(
ctx context.Context,
name string,
) (io.ReadCloser, error) {
var (
object *minio.Object
objectInfo minio.ObjectInfo
)
if err := retryQiniuKodoDo(ctx, func(ctx context.Context) (err error) {
object, err = qiniuKodoClient.GetObject(
ctx,
qiniuKodoBucketName,
name,
minio.GetObjectOptions{},
)
if err != nil {
return err
}
objectInfo, err = object.Stat()
if err != nil {
object.Close()
}
return err
}); err != nil {
if isNotFoundMinIOError(err) {
return nil, fs.ErrNotExist
}
return nil, err
}
checksum, _ := hex.DecodeString(objectInfo.ETag)
if len(checksum) != md5.Size {
eTagChecksum := md5.Sum([]byte(objectInfo.ETag))
checksum = eTagChecksum[:]
}
return &goproxyCacheReader{
ReadSeekCloser: object,
modTime: objectInfo.LastModified,
checksum: checksum,
}, nil
}
// SetCache implements the `goproxy.Cacher`.
func (gc *goproxyCacher) Set(
ctx context.Context,
name string,
content io.ReadSeeker,
) error {
if err := retryQiniuKodoDo(ctx, func(ctx context.Context) error {
_, err := qiniuKodoClient.StatObject(
ctx,
qiniuKodoBucketName,
name,
minio.StatObjectOptions{},
)
return err
}); err == nil {
return nil
} else if !isNotFoundMinIOError(err) {
return err
}
return qiniuKodoUpload(ctx, name, content)
}
// goproxyCacheReader is the reader of the cache unit of the `goproxyCacher`.
type goproxyCacheReader struct {
io.ReadSeekCloser
modTime time.Time
checksum []byte
}
// ModTime returns the modification time of the gcr.
func (gcr *goproxyCacheReader) ModTime() time.Time {
return gcr.modTime
}
// Checksum returns the checksum of the gcr.
func (gcr *goproxyCacheReader) Checksum() []byte {
return gcr.checksum
}
// validGoproxyCacheName reports whether the name is a valid Goproxy cache name.
func validGoproxyCacheName(name string) bool {
nameParts := strings.Split(name, "/@v/")
if len(nameParts) != 2 {
return false
}
if _, err := module.UnescapePath(nameParts[0]); err != nil {
return false
}
nameBase := path.Base(name)
nameExt := path.Ext(nameBase)
switch nameExt {
case ".info", ".mod", ".zip":
default:
return false
}
escapedModuleVersion := strings.TrimSuffix(nameBase, nameExt)
moduleVersion, err := module.UnescapeVersion(escapedModuleVersion)
if err != nil {
return false
}
return semver.IsValid(moduleVersion)
}