forked from goproxy/goproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.go
590 lines (518 loc) · 12.6 KB
/
fetch.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
package goproxy
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"sort"
"strings"
"time"
"golang.org/x/mod/module"
"golang.org/x/mod/semver"
"golang.org/x/mod/sumdb"
"golang.org/x/mod/sumdb/dirhash"
"golang.org/x/mod/zip"
)
// fetch is a module fetch. All its fields are populated only by the [newFetch].
type fetch struct {
g *Goproxy
ops fetchOps
name string
tempDir string
modulePath string
moduleVersion string
modAtVer string
requiredToVerify bool
contentType string
}
// newFetch returns a new instance of the [fetch].
func newFetch(g *Goproxy, name, tempDir string) (*fetch, error) {
f := &fetch{
g: g,
name: name,
tempDir: tempDir,
}
var escapedModulePath string
if strings.HasSuffix(name, "/@latest") {
escapedModulePath = strings.TrimSuffix(name, "/@latest")
f.ops = fetchOpsResolve
f.moduleVersion = "latest"
f.contentType = "application/json; charset=utf-8"
} else if strings.HasSuffix(name, "/@v/list") {
escapedModulePath = strings.TrimSuffix(name, "/@v/list")
f.ops = fetchOpsList
f.moduleVersion = "latest"
f.contentType = "text/plain; charset=utf-8"
} else {
nameParts := strings.SplitN(name, "/@v/", 2)
if len(nameParts) != 2 {
return nil, errors.New("missing /@v/")
}
escapedModulePath = nameParts[0]
nameExt := path.Ext(nameParts[1])
escapedModuleVersion := strings.TrimSuffix(
nameParts[1],
nameExt,
)
switch nameExt {
case ".info":
f.ops = fetchOpsDownloadInfo
f.contentType = "application/json; charset=utf-8"
case ".mod":
f.ops = fetchOpsDownloadMod
f.contentType = "text/plain; charset=utf-8"
case ".zip":
f.ops = fetchOpsDownloadZip
f.contentType = "application/zip"
case "":
return nil, fmt.Errorf(
"no file extension in filename %q",
escapedModuleVersion,
)
default:
return nil, fmt.Errorf(
"unexpected extension %q",
nameExt,
)
}
var err error
f.moduleVersion, err = module.UnescapeVersion(
escapedModuleVersion,
)
if err != nil {
return nil, err
}
if f.moduleVersion == "latest" {
return nil, errors.New("invalid version")
} else if !semver.IsValid(f.moduleVersion) {
if f.ops == fetchOpsDownloadInfo {
f.ops = fetchOpsResolve
} else {
return nil, errors.New("unrecognized version")
}
}
}
var err error
f.modulePath, err = module.UnescapePath(escapedModulePath)
if err != nil {
return nil, err
}
f.modAtVer = fmt.Sprint(f.modulePath, "@", f.moduleVersion)
f.requiredToVerify = g.goBinEnvGOSUMDB != "off" &&
!globsMatchPath(g.goBinEnvGONOSUMDB, f.modulePath)
return f, nil
}
// do executes the f.
func (f *fetch) do(ctx context.Context) (*fetchResult, error) {
if globsMatchPath(f.g.goBinEnvGONOPROXY, f.modulePath) {
return f.doDirect(ctx)
}
var r *fetchResult
if err := walkGOPROXY(f.g.goBinEnvGOPROXY, func(proxy string) error {
var err error
r, err = f.doProxy(ctx, proxy)
return err
}, func() error {
var err error
r, err = f.doDirect(ctx)
return err
}, func() error {
// go/src/cmd/go/internal/modfetch.errProxyOff
return notFoundError("module lookup disabled by GOPROXY=off")
}); err != nil {
return nil, err
}
return r, nil
}
// doProxy executes the f via the proxy.
func (f *fetch) doProxy(
ctx context.Context,
proxy string,
) (*fetchResult, error) {
proxyURL, err := parseRawURL(proxy)
if err != nil {
return nil, err
}
tempFile, err := ioutil.TempFile(f.tempDir, "")
if err != nil {
return nil, err
}
if err := httpGet(
ctx,
f.g.httpClient,
appendURL(proxyURL, f.name).String(),
tempFile,
); err != nil {
return nil, err
}
if err := tempFile.Close(); err != nil {
return nil, err
}
r := &fetchResult{f: f}
switch f.ops {
case fetchOpsResolve:
b, err := ioutil.ReadFile(tempFile.Name())
if err != nil {
return nil, err
}
r.Version, r.Time, err = unmarshalInfo(string(b))
if err != nil {
return nil, notFoundError(fmt.Sprintf(
"invalid info response: %v",
err,
))
}
case fetchOpsList:
b, err := ioutil.ReadFile(tempFile.Name())
if err != nil {
return nil, err
}
lines := strings.Split(string(b), "\n")
r.Versions = make([]string, 0, len(lines))
for _, line := range lines {
// go/src/cmd/go/internal/modfetch.proxyRepo.Versions
lineParts := strings.Fields(line)
if len(lineParts) > 0 &&
semver.IsValid(lineParts[0]) &&
!module.IsPseudoVersion(lineParts[0]) {
r.Versions = append(r.Versions, lineParts[0])
}
}
sort.Slice(r.Versions, func(i, j int) bool {
return semver.Compare(r.Versions[i], r.Versions[j]) < 0
})
case fetchOpsDownloadInfo:
if err := checkAndFormatInfoFile(tempFile.Name()); err != nil {
return nil, err
}
r.Info = tempFile.Name()
case fetchOpsDownloadMod:
if err := checkModFile(tempFile.Name()); err != nil {
return nil, err
}
if f.requiredToVerify {
if err := verifyModFile(
f.g.sumdbClient,
tempFile.Name(),
f.modulePath,
f.moduleVersion,
); err != nil {
return nil, err
}
}
r.GoMod = tempFile.Name()
case fetchOpsDownloadZip:
if err := checkZipFile(
tempFile.Name(),
f.modulePath,
f.moduleVersion,
); err != nil {
return nil, err
}
if f.requiredToVerify {
if err := verifyZipFile(
f.g.sumdbClient,
tempFile.Name(),
f.modulePath,
f.moduleVersion,
); err != nil {
return nil, err
}
}
r.Zip = tempFile.Name()
}
return r, nil
}
// doDirect executes the f directly using the local go command.
func (f *fetch) doDirect(ctx context.Context) (*fetchResult, error) {
if f.g.goBinWorkerChan != nil {
f.g.goBinWorkerChan <- struct{}{}
defer func() { <-f.g.goBinWorkerChan }()
}
var args []string
switch f.ops {
case fetchOpsResolve:
args = []string{"list", "-json", "-m", f.modAtVer}
case fetchOpsList:
args = []string{"list", "-json", "-m", "-versions", f.modAtVer}
case fetchOpsDownloadInfo, fetchOpsDownloadMod, fetchOpsDownloadZip:
args = []string{"mod", "download", "-json", f.modAtVer}
}
cmd := exec.CommandContext(ctx, f.g.goBinName, args...)
cmd.Env = f.g.goBinEnv
cmd.Dir = f.tempDir
stdout, err := cmd.Output()
if err != nil {
if err := ctx.Err(); errors.Is(err, context.DeadlineExceeded) {
return nil, fmt.Errorf("command %v: %w", cmd.Args, err)
}
output := stdout
if len(output) > 0 {
var goError struct{ Error string }
if err := json.Unmarshal(output, &goError); err != nil {
return nil, err
}
if goError.Error != "" {
output = []byte(goError.Error)
}
} else if ee, ok := err.(*exec.ExitError); ok {
output = ee.Stderr
} else {
return nil, err
}
var msg string
for _, line := range strings.Split(string(output), "\n") {
if !strings.HasPrefix(line, "go: finding") {
msg = fmt.Sprint(msg, line, "\n")
}
}
msg = strings.TrimPrefix(msg, "go: ")
msg = strings.TrimPrefix(msg, "go list -m: ")
msg = strings.TrimRight(msg, "\n")
return nil, notFoundError(msg)
}
r := &fetchResult{f: f}
if err := json.Unmarshal(stdout, r); err != nil {
return nil, err
}
switch f.ops {
case fetchOpsList:
sort.Slice(r.Versions, func(i, j int) bool {
return semver.Compare(r.Versions[i], r.Versions[j]) < 0
})
case fetchOpsDownloadInfo, fetchOpsDownloadMod, fetchOpsDownloadZip:
if err := checkAndFormatInfoFile(r.Info); err != nil {
return nil, err
}
if f.requiredToVerify {
if err := verifyModFile(
f.g.sumdbClient,
r.GoMod,
f.modulePath,
f.moduleVersion,
); err != nil {
return nil, err
}
if err := verifyZipFile(
f.g.sumdbClient,
r.Zip,
f.modulePath,
f.moduleVersion,
); err != nil {
return nil, err
}
}
}
return r, nil
}
// fetchOps is the operation of the [fetch].
type fetchOps uint8
// The fetch operations.
const (
fetchOpsInvalid fetchOps = iota
fetchOpsResolve
fetchOpsList
fetchOpsDownloadInfo
fetchOpsDownloadMod
fetchOpsDownloadZip
)
// String implements the [fmt.Stringer].
func (fo fetchOps) String() string {
switch fo {
case fetchOpsResolve:
return "resolve"
case fetchOpsList:
return "list"
case fetchOpsDownloadInfo:
return "download info"
case fetchOpsDownloadMod:
return "download mod"
case fetchOpsDownloadZip:
return "download zip"
}
return "invalid"
}
// fetchResult is an unified result for the [fetch].
type fetchResult struct {
f *fetch
Version string
Time time.Time
Versions []string
Info string
GoMod string
Zip string
}
// Open opens the content of the fr.
func (fr *fetchResult) Open() (readSeekCloser, error) {
switch fr.f.ops {
case fetchOpsResolve:
content := strings.NewReader(marshalInfo(fr.Version, fr.Time))
return struct {
io.ReadCloser
io.Seeker
}{nopCloser{content}, content}, nil
case fetchOpsList:
content := strings.NewReader(strings.Join(fr.Versions, "\n"))
return struct {
io.ReadCloser
io.Seeker
}{nopCloser{content}, content}, nil
case fetchOpsDownloadInfo:
return os.Open(fr.Info)
case fetchOpsDownloadMod:
return os.Open(fr.GoMod)
case fetchOpsDownloadZip:
return os.Open(fr.Zip)
}
return nil, errors.New("invalid fetch operation")
}
// marshalInfo marshals the version and t as info.
func marshalInfo(version string, t time.Time) string {
return fmt.Sprintf(
`{"Version":%q,"Time":%q}`,
version,
t.UTC().Format(time.RFC3339Nano),
)
}
// unmarshalInfo unmarshals the s as info and returns version and time.
func unmarshalInfo(s string) (string, time.Time, error) {
var info struct {
Version string
Time time.Time
}
if err := json.Unmarshal([]byte(s), &info); err != nil {
return "", time.Time{}, err
} else if !semver.IsValid(info.Version) {
return "", time.Time{}, errors.New("empty version")
} else if info.Time.IsZero() {
return "", time.Time{}, errors.New("zero time")
}
return info.Version, info.Time, nil
}
// checkAndFormatInfoFile checks and formats the info file targeted by the name.
func checkAndFormatInfoFile(name string) error {
b, err := ioutil.ReadFile(name)
if err != nil {
return err
}
infoVersion, infoTime, err := unmarshalInfo(string(b))
if err != nil {
return notFoundError(fmt.Sprintf("invalid info file: %v", err))
}
if info := marshalInfo(infoVersion, infoTime); info != string(b) {
return ioutil.WriteFile(name, []byte(info), 0600)
}
return nil
}
// checkModFile checks the mod file targeted by the name.
func checkModFile(name string) error {
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if strings.HasPrefix(
strings.TrimSpace(scanner.Text()),
"module",
) {
return nil
}
}
if err := scanner.Err(); err != nil {
return err
}
return notFoundError("invalid mod file: missing module directive")
}
// verifyModFile uses the sumdbClient to verify the mod file targeted by the
// name with the modulePath and moduleVersion.
func verifyModFile(
sumdbClient *sumdb.Client,
name string,
modulePath string,
moduleVersion string,
) error {
gosumLines, err := sumdbClient.Lookup(
modulePath,
fmt.Sprint(moduleVersion, "/go.mod"),
)
if err != nil {
return err
}
modHash, err := dirhash.DefaultHash(
[]string{"go.mod"},
func(string) (io.ReadCloser, error) {
return os.Open(name)
},
)
if err != nil {
return err
}
if !stringSliceContains(
gosumLines,
fmt.Sprintf(
"%s %s/go.mod %s",
modulePath,
moduleVersion,
modHash,
),
) {
return notFoundError(fmt.Sprintf(
"%s@%s: invalid version: untrusted revision %s",
modulePath,
moduleVersion,
moduleVersion,
))
}
return nil
}
// checkZipFile checks the zip file targeted by the name with the modulePath and
// moduleVersion.
func checkZipFile(name, modulePath, moduleVersion string) error {
if _, err := zip.CheckZip(
module.Version{
Path: modulePath,
Version: moduleVersion,
},
name,
); err != nil {
return notFoundError(fmt.Sprintf("invalid zip file: %v", err))
}
return nil
}
// verifyZipFile uses the sumdbClient to verify the zip file targeted by the
// name with the modulePath and moduleVersion.
func verifyZipFile(
sumdbClient *sumdb.Client,
name string,
modulePath string,
moduleVersion string,
) error {
gosumLines, err := sumdbClient.Lookup(modulePath, moduleVersion)
if err != nil {
return err
}
zipHash, err := dirhash.HashZip(name, dirhash.DefaultHash)
if err != nil {
return err
}
if !stringSliceContains(
gosumLines,
fmt.Sprintf("%s %s %s", modulePath, moduleVersion, zipHash),
) {
return notFoundError(fmt.Sprintf(
"%s@%s: invalid version: untrusted revision %s",
modulePath,
moduleVersion,
moduleVersion,
))
}
return nil
}