1
2
3
4
5 package modfetch
6
7 import (
8 "archive/zip"
9 "bytes"
10 "cmd/go/internal/base"
11 "cmd/go/internal/cfg"
12 "cmd/go/internal/fsys"
13 "cmd/go/internal/gover"
14 "cmd/go/internal/lockedfile"
15 "cmd/go/internal/str"
16 "cmd/go/internal/trace"
17 "cmd/internal/par"
18 "cmd/internal/robustio"
19 "context"
20 "crypto/sha256"
21 "encoding/base64"
22 "errors"
23 "fmt"
24 "io"
25 "io/fs"
26 "os"
27 "path/filepath"
28 "sort"
29 "strings"
30 "sync"
31
32 "golang.org/x/mod/module"
33 "golang.org/x/mod/sumdb/dirhash"
34 modzip "golang.org/x/mod/zip"
35 )
36
37 var (
38 ErrToolchain = errors.New("internal error: invalid operation on toolchain module")
39 ErrFIPS140 = errors.New("golang.org/fips140 is bundled with the Go distribution and cannot be downloaded")
40 )
41
42
43
44
45 func (f *Fetcher) Download(ctx context.Context, mod module.Version) (dir string, err error) {
46 if gover.IsToolchain(mod.Path) {
47 return "", ErrToolchain
48 }
49 if mod.Path == "golang.org/fips140" {
50 return "", ErrFIPS140
51 }
52 if err := checkCacheDir(ctx); err != nil {
53 base.Fatal(err)
54 }
55
56
57 return f.downloadCache.Do(mod, func() (string, error) {
58 dir, err := f.download(ctx, mod)
59 if err != nil {
60 return "", err
61 }
62 f.checkMod(ctx, mod)
63
64
65 if data, err := os.ReadFile(filepath.Join(dir, "go.mod")); err == nil {
66 goVersion := gover.GoModLookup(data, "go")
67 if gover.Compare(goVersion, gover.Local()) > 0 {
68 return "", &gover.TooNewError{What: mod.String(), GoVersion: goVersion}
69 }
70 } else if !errors.Is(err, fs.ErrNotExist) {
71 return "", err
72 }
73
74 return dir, nil
75 })
76 }
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97 func (f *Fetcher) Unzip(ctx context.Context, mod module.Version, zipfile, ziphash string, verify func() error) (dir string, err error) {
98 if ziphash == "" {
99 return "", module.VersionError(mod, errors.New("internal error: Unzip called with empty module zip hash"))
100 }
101 if err := checkCacheDir(ctx); err != nil {
102 base.Fatal(err)
103 }
104
105 return f.downloadCache.Do(mod, func() (string, error) {
106 ctx, span := trace.StartSpan(ctx, "modfetch.Unzip "+mod.String())
107 defer span.Done()
108
109 dir, err = DownloadDir(ctx, mod)
110 if err == nil {
111
112 ok, err := haveZipHash(ctx, mod, ziphash)
113 if err != nil {
114 return "", err
115 }
116 if ok {
117 return dir, nil
118 }
119 } else if dir == "" || !errors.Is(err, fs.ErrNotExist) {
120 return "", err
121 }
122
123 return unzip(ctx, mod, zipfile, ziphash, verify)
124 })
125 }
126
127 func haveZipHash(ctx context.Context, mod module.Version, ziphash string) (bool, error) {
128 path, err := CachePath(ctx, mod, "ziphash")
129 if err != nil {
130 return false, err
131 }
132 data, err := lockedfile.Read(path)
133 if errors.Is(err, fs.ErrNotExist) {
134 return false, nil
135 }
136 if err != nil {
137 return false, err
138 }
139 return strings.TrimSpace(string(data)) == ziphash, nil
140 }
141
142 func writeZipHash(ctx context.Context, mod module.Version, ziphash string) error {
143 path, err := CachePath(ctx, mod, "ziphash")
144 if err != nil {
145 return err
146 }
147 if err := os.MkdirAll(filepath.Dir(path), 0o777); err != nil {
148 return err
149 }
150 return lockedfile.Write(path, strings.NewReader(ziphash), 0o666)
151 }
152
153 func (f *Fetcher) download(ctx context.Context, mod module.Version) (dir string, err error) {
154 ctx, span := trace.StartSpan(ctx, "modfetch.download "+mod.String())
155 defer span.Done()
156
157 dir, err = DownloadDir(ctx, mod)
158 if err == nil {
159
160 return dir, nil
161 } else if dir == "" || !errors.Is(err, fs.ErrNotExist) {
162 return "", err
163 }
164
165
166
167
168 zipfile, err := f.DownloadZip(ctx, mod)
169 if err != nil {
170 return "", err
171 }
172
173 return unzip(ctx, mod, zipfile, "", nil)
174 }
175
176
177
178
179
180
181
182 func unzip(ctx context.Context, mod module.Version, zipfile, ziphash string, verify func() error) (dir string, err error) {
183 unlock, err := lockVersion(ctx, mod)
184 if err != nil {
185 return "", err
186 }
187 defer unlock()
188
189 ctx, span := trace.StartSpan(ctx, "unzip "+zipfile)
190 defer span.Done()
191
192
193 dir, dirErr := DownloadDir(ctx, mod)
194 if dirErr == nil {
195 if ziphash == "" {
196 return dir, nil
197 }
198 ok, err := haveZipHash(ctx, mod, ziphash)
199 if err != nil {
200 return "", err
201 }
202 if ok {
203 return dir, nil
204 }
205 dirErr = &DownloadDirPartialError{dir, errors.New("ziphash file does not match")}
206 }
207 _, dirExists := dirErr.(*DownloadDirPartialError)
208
209
210
211
212 if verify != nil {
213 if err := verify(); err != nil {
214 return "", err
215 }
216 }
217
218
219
220
221
222
223 parentDir := filepath.Dir(dir)
224 tmpPrefix := filepath.Base(dir) + ".tmp-"
225 if old, err := filepath.Glob(filepath.Join(str.QuoteGlob(parentDir), str.QuoteGlob(tmpPrefix)+"*")); err == nil {
226 for _, path := range old {
227 RemoveAll(path)
228 }
229 }
230 if dirExists {
231 if err := RemoveAll(dir); err != nil {
232 return "", err
233 }
234 }
235
236
237
238
239 if ziphash != "" {
240 hashPath, err := CachePath(ctx, mod, "ziphash")
241 if err != nil {
242 return "", err
243 }
244 if err := robustio.RemoveAll(hashPath); err != nil {
245 return "", err
246 }
247 }
248
249 partialPath, err := CachePath(ctx, mod, "partial")
250 if err != nil {
251 return "", err
252 }
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268 if err := os.MkdirAll(parentDir, 0o777); err != nil {
269 return "", err
270 }
271 if err := os.WriteFile(partialPath, nil, 0o666); err != nil {
272 return "", err
273 }
274 if err := modzip.Unzip(dir, mod, zipfile); err != nil {
275 fmt.Fprintf(os.Stderr, "-> %s\n", err)
276 if rmErr := RemoveAll(dir); rmErr == nil {
277 os.Remove(partialPath)
278 }
279 return "", err
280 }
281 if err := os.Remove(partialPath); err != nil {
282 return "", err
283 }
284
285
286 if ziphash != "" {
287 if err := writeZipHash(ctx, mod, ziphash); err != nil {
288 return "", err
289 }
290 }
291
292 if !cfg.ModCacheRW {
293 makeDirsReadOnly(dir)
294 }
295 return dir, nil
296 }
297
298 var downloadZipCache par.ErrCache[module.Version, string]
299
300
301
302 func (f *Fetcher) DownloadZip(ctx context.Context, mod module.Version) (zipfile string, err error) {
303 if mod.Path == "golang.org/fips140" {
304 return "", ErrFIPS140
305 }
306
307
308 return downloadZipCache.Do(mod, func() (string, error) {
309 zipfile, err := CachePath(ctx, mod, "zip")
310 if err != nil {
311 return "", err
312 }
313 ziphashfile := zipfile + "hash"
314
315
316 if _, err := os.Stat(zipfile); err == nil {
317 if _, err := os.Stat(ziphashfile); err == nil {
318 if !HaveSum(f, mod) {
319 f.checkMod(ctx, mod)
320 }
321 return zipfile, nil
322 }
323 }
324
325
326 if cfg.CmdName != "mod download" {
327 vers := mod.Version
328 if mod.Path == "golang.org/toolchain" {
329
330 _, vers, _ = strings.Cut(vers, "-")
331 if i := strings.LastIndex(vers, "."); i >= 0 {
332 goos, goarch, _ := strings.Cut(vers[i+1:], "-")
333 vers = vers[:i] + " (" + goos + "/" + goarch + ")"
334 }
335 fmt.Fprintf(os.Stderr, "go: downloading %s\n", vers)
336 } else {
337 fmt.Fprintf(os.Stderr, "go: downloading %s %s\n", mod.Path, vers)
338 }
339 }
340 unlock, err := lockVersion(ctx, mod)
341 if err != nil {
342 return "", err
343 }
344 defer unlock()
345
346 if err := f.downloadZip(ctx, mod, zipfile); err != nil {
347 return "", err
348 }
349 return zipfile, nil
350 })
351 }
352
353 func (f *Fetcher) downloadZip(ctx context.Context, mod module.Version, zipfile string) (err error) {
354 ctx, span := trace.StartSpan(ctx, "modfetch.downloadZip "+zipfile)
355 defer span.Done()
356
357
358
359 ziphashfile := zipfile + "hash"
360 var zipExists, ziphashExists bool
361 if _, err := os.Stat(zipfile); err == nil {
362 zipExists = true
363 }
364 if _, err := os.Stat(ziphashfile); err == nil {
365 ziphashExists = true
366 }
367 if zipExists && ziphashExists {
368 return nil
369 }
370
371
372 if err := os.MkdirAll(filepath.Dir(zipfile), 0o777); err != nil {
373 return err
374 }
375
376
377
378
379 tmpPattern := filepath.Base(zipfile) + "*.tmp"
380 if old, err := filepath.Glob(filepath.Join(str.QuoteGlob(filepath.Dir(zipfile)), tmpPattern)); err == nil {
381 for _, path := range old {
382 os.Remove(path)
383 }
384 }
385
386
387
388 if zipExists {
389 return hashZip(f, mod, zipfile, ziphashfile)
390 }
391
392
393
394
395
396
397 file, err := tempFile(ctx, filepath.Dir(zipfile), filepath.Base(zipfile), 0o666)
398 if err != nil {
399 return err
400 }
401 defer func() {
402 if err != nil {
403 file.Close()
404 os.Remove(file.Name())
405 }
406 }()
407
408 var unrecoverableErr error
409 err = TryProxies(func(proxy string) error {
410 if unrecoverableErr != nil {
411 return unrecoverableErr
412 }
413 repo := f.Lookup(ctx, proxy, mod.Path)
414 err := repo.Zip(ctx, file, mod.Version)
415 if err != nil {
416
417
418
419
420 if _, err := file.Seek(0, io.SeekStart); err != nil {
421 unrecoverableErr = err
422 return err
423 }
424 if err := file.Truncate(0); err != nil {
425 unrecoverableErr = err
426 return err
427 }
428 }
429 return err
430 })
431 if err != nil {
432 return err
433 }
434
435
436
437
438 fi, err := file.Stat()
439 if err != nil {
440 return err
441 }
442 z, err := zip.NewReader(file, fi.Size())
443 if err != nil {
444 return err
445 }
446 prefix := mod.Path + "@" + mod.Version + "/"
447 for _, zf := range z.File {
448 if !strings.HasPrefix(zf.Name, prefix) {
449 return fmt.Errorf("zip for %s has unexpected file %s", prefix[:len(prefix)-1], zf.Name)
450 }
451 }
452
453 if err := file.Close(); err != nil {
454 return err
455 }
456
457
458 if err := hashZip(f, mod, file.Name(), ziphashfile); err != nil {
459 return err
460 }
461 if err := os.Rename(file.Name(), zipfile); err != nil {
462 return err
463 }
464
465
466
467 return nil
468 }
469
470
471
472
473
474
475 func hashZip(f *Fetcher, mod module.Version, zipfile, ziphashfile string) (err error) {
476 hash, err := dirhash.HashZip(zipfile, dirhash.DefaultHash)
477 if err != nil {
478 return err
479 }
480 if err := checkModSum(f, mod, hash); err != nil {
481 return err
482 }
483 hf, err := lockedfile.Create(ziphashfile)
484 if err != nil {
485 return err
486 }
487 defer func() {
488 if closeErr := hf.Close(); err == nil && closeErr != nil {
489 err = closeErr
490 }
491 }()
492 if err := hf.Truncate(int64(len(hash))); err != nil {
493 return err
494 }
495 if _, err := hf.WriteAt([]byte(hash), 0); err != nil {
496 return err
497 }
498 return nil
499 }
500
501
502
503 func makeDirsReadOnly(dir string) {
504 type pathMode struct {
505 path string
506 mode fs.FileMode
507 }
508 var dirs []pathMode
509 filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
510 if err == nil && d.IsDir() {
511 info, err := d.Info()
512 if err == nil && info.Mode()&0o222 != 0 {
513 dirs = append(dirs, pathMode{path, info.Mode()})
514 }
515 }
516 return nil
517 })
518
519
520 for i := len(dirs) - 1; i >= 0; i-- {
521 os.Chmod(dirs[i].path, dirs[i].mode&^0o222)
522 }
523 }
524
525
526
527 func RemoveAll(dir string) error {
528
529 filepath.WalkDir(dir, func(path string, info fs.DirEntry, err error) error {
530 if err != nil {
531 return nil
532 }
533 if info.IsDir() {
534 os.Chmod(path, 0o777)
535 }
536 return nil
537 })
538 return robustio.RemoveAll(dir)
539 }
540
541
542
543
544
545 type modSum struct {
546 mod module.Version
547 sum string
548 }
549
550 type sumState struct {
551 m map[module.Version][]string
552 w map[string]map[module.Version][]string
553 status map[modSum]modSumStatus
554 overwrite bool
555 enabled bool
556 }
557
558 type modSumStatus struct {
559 used, dirty bool
560 }
561
562
563 type Fetcher struct {
564
565 goSumFile string
566
567 workspaceGoSumFiles []string
568
569
570
571 lookupCache *par.Cache[lookupCacheKey, Repo]
572
573
574
575
576
577 downloadCache *par.ErrCache[module.Version, string]
578
579 mu sync.Mutex
580 sumState sumState
581 }
582
583 func NewFetcher() *Fetcher {
584 f := new(Fetcher)
585 f.lookupCache = new(par.Cache[lookupCacheKey, Repo])
586 f.downloadCache = new(par.ErrCache[module.Version, string])
587 return f
588 }
589
590 func (f *Fetcher) GoSumFile() string {
591 return f.goSumFile
592 }
593
594 func (f *Fetcher) SetGoSumFile(str string) {
595 f.goSumFile = str
596 }
597
598 func (f *Fetcher) AddWorkspaceGoSumFile(file string) {
599 f.workspaceGoSumFiles = append(f.workspaceGoSumFiles, file)
600 }
601
602
603 func (f *Fetcher) ReloadWorkspaceGoSumFiles() error {
604 f.mu.Lock()
605 defer f.mu.Unlock()
606 if _, err := f.initGoSum(); err != nil {
607 return err
608 }
609
610 w := make(map[string]map[module.Version][]string, len(f.workspaceGoSumFiles))
611 for _, file := range f.workspaceGoSumFiles {
612 w[file] = make(map[module.Version][]string)
613 if _, err := readGoSumFile(w[file], file); err != nil {
614 return err
615 }
616 }
617 f.sumState.w = w
618 return nil
619 }
620
621
622
623 func (f *Fetcher) Reset() {
624 f.SetState(NewFetcher())
625 }
626
627
628
629
630
631 func (f *Fetcher) SetState(newState *Fetcher) (oldState *Fetcher) {
632 if newState.lookupCache == nil {
633 newState.lookupCache = new(par.Cache[lookupCacheKey, Repo])
634 }
635 if newState.downloadCache == nil {
636 newState.downloadCache = new(par.ErrCache[module.Version, string])
637 }
638
639 f.mu.Lock()
640 defer f.mu.Unlock()
641
642 oldState = &Fetcher{
643 goSumFile: f.goSumFile,
644 workspaceGoSumFiles: f.workspaceGoSumFiles,
645 lookupCache: f.lookupCache,
646 downloadCache: f.downloadCache,
647 sumState: f.sumState,
648 }
649
650 f.SetGoSumFile(newState.goSumFile)
651 f.workspaceGoSumFiles = newState.workspaceGoSumFiles
652
653
654
655 f.lookupCache = newState.lookupCache
656 f.downloadCache = newState.downloadCache
657
658 f.sumState = newState.sumState
659
660 return oldState
661 }
662
663
664
665
666
667 func (f *Fetcher) initGoSum() (bool, error) {
668 if f.goSumFile == "" {
669 return false, nil
670 }
671 if f.sumState.m != nil {
672 return true, nil
673 }
674
675 f.sumState.m = make(map[module.Version][]string)
676 f.sumState.status = make(map[modSum]modSumStatus)
677 f.sumState.w = make(map[string]map[module.Version][]string)
678
679 for _, fn := range f.workspaceGoSumFiles {
680 f.sumState.w[fn] = make(map[module.Version][]string)
681 _, err := readGoSumFile(f.sumState.w[fn], fn)
682 if err != nil {
683 return false, err
684 }
685 }
686
687 enabled, err := readGoSumFile(f.sumState.m, f.goSumFile)
688 f.sumState.enabled = enabled
689 return enabled, err
690 }
691
692 func readGoSumFile(dst map[module.Version][]string, file string) (bool, error) {
693 var (
694 data []byte
695 err error
696 )
697 if fsys.Replaced(file) {
698
699
700
701 data, err = os.ReadFile(fsys.Actual(file))
702 } else {
703 data, err = lockedfile.Read(file)
704 }
705 if err != nil && !os.IsNotExist(err) {
706 return false, err
707 }
708 readGoSum(dst, file, data)
709
710 return true, nil
711 }
712
713
714
715
716 const emptyGoModHash = "h1:G7mAYYxgmS0lVkHyy2hEOLQCFB0DlQFTMLWggykrydY="
717
718
719
720 func readGoSum(dst map[module.Version][]string, file string, data []byte) {
721 lineno := 0
722 for len(data) > 0 {
723 var line []byte
724 lineno++
725 i := bytes.IndexByte(data, '\n')
726 if i < 0 {
727 line, data = data, nil
728 } else {
729 line, data = data[:i], data[i+1:]
730 }
731 f := strings.Fields(string(line))
732 if len(f) == 0 {
733
734 continue
735 }
736 if len(f) != 3 {
737 if cfg.CmdName == "mod tidy" {
738
739 continue
740 } else {
741 base.Fatalf("malformed go.sum:\n%s:%d: wrong number of fields %v\n", file, lineno, len(f))
742 }
743 }
744 if f[2] == emptyGoModHash {
745
746 continue
747 }
748 mod := module.Version{Path: f[0], Version: f[1]}
749 dst[mod] = append(dst[mod], f[2])
750 }
751 }
752
753
754
755
756
757 func HaveSum(f *Fetcher, mod module.Version) bool {
758 f.mu.Lock()
759 defer f.mu.Unlock()
760 inited, err := f.initGoSum()
761 if err != nil || !inited {
762 return false
763 }
764 for _, goSums := range f.sumState.w {
765 for _, h := range goSums[mod] {
766 if !strings.HasPrefix(h, "h1:") {
767 continue
768 }
769 if !f.sumState.status[modSum{mod, h}].dirty {
770 return true
771 }
772 }
773 }
774 for _, h := range f.sumState.m[mod] {
775 if !strings.HasPrefix(h, "h1:") {
776 continue
777 }
778 if !f.sumState.status[modSum{mod, h}].dirty {
779 return true
780 }
781 }
782 return false
783 }
784
785
786
787
788
789
790
791 func (f *Fetcher) RecordedSum(mod module.Version) (sum string, ok bool) {
792 f.mu.Lock()
793 defer f.mu.Unlock()
794 inited, err := f.initGoSum()
795 foundSum := ""
796 if err != nil || !inited {
797 return "", false
798 }
799 for _, goSums := range f.sumState.w {
800 for _, h := range goSums[mod] {
801 if !strings.HasPrefix(h, "h1:") {
802 continue
803 }
804 if !f.sumState.status[modSum{mod, h}].dirty {
805 if foundSum != "" && foundSum != h {
806 return "", false
807 }
808 foundSum = h
809 }
810 }
811 }
812 for _, h := range f.sumState.m[mod] {
813 if !strings.HasPrefix(h, "h1:") {
814 continue
815 }
816 if !f.sumState.status[modSum{mod, h}].dirty {
817 if foundSum != "" && foundSum != h {
818 return "", false
819 }
820 foundSum = h
821 }
822 }
823 return foundSum, true
824 }
825
826
827 func (f *Fetcher) checkMod(ctx context.Context, mod module.Version) {
828
829 ziphash, err := CachePath(ctx, mod, "ziphash")
830 if err != nil {
831 base.Fatalf("verifying %v", module.VersionError(mod, err))
832 }
833 data, err := lockedfile.Read(ziphash)
834 if err != nil {
835 base.Fatalf("verifying %v", module.VersionError(mod, err))
836 }
837 data = bytes.TrimSpace(data)
838 if !isValidSum(data) {
839
840 zip, err := CachePath(ctx, mod, "zip")
841 if err != nil {
842 base.Fatalf("verifying %v", module.VersionError(mod, err))
843 }
844 err = hashZip(f, mod, zip, ziphash)
845 if err != nil {
846 base.Fatalf("verifying %v", module.VersionError(mod, err))
847 }
848 return
849 }
850 h := string(data)
851 if !strings.HasPrefix(h, "h1:") {
852 base.Fatalf("verifying %v", module.VersionError(mod, fmt.Errorf("unexpected ziphash: %q", h)))
853 }
854
855 if err := checkModSum(f, mod, h); err != nil {
856 base.Fatalf("%s", err)
857 }
858 }
859
860
861 func goModSum(data []byte) (string, error) {
862 return dirhash.Hash1([]string{"go.mod"}, func(string) (io.ReadCloser, error) {
863 return io.NopCloser(bytes.NewReader(data)), nil
864 })
865 }
866
867
868
869 func checkGoMod(f *Fetcher, path, version string, data []byte) error {
870 h, err := goModSum(data)
871 if err != nil {
872 return &module.ModuleError{Path: path, Version: version, Err: fmt.Errorf("verifying go.mod: %v", err)}
873 }
874
875 return checkModSum(f, module.Version{Path: path, Version: version + "/go.mod"}, h)
876 }
877
878
879
880
881
882 func checkModSum(f *Fetcher, mod module.Version, h string) error {
883
884
885
886
887
888
889 f.mu.Lock()
890 inited, err := f.initGoSum()
891 if err != nil {
892 f.mu.Unlock()
893 return err
894 }
895 done := inited && haveModSumLocked(f, mod, h)
896 if inited {
897 st := f.sumState.status[modSum{mod, h}]
898 st.used = true
899 f.sumState.status[modSum{mod, h}] = st
900 }
901 f.mu.Unlock()
902
903 if done && mod.Path != "golang.org/toolchain" {
904 return nil
905 }
906
907
908 if useSumDB(mod) {
909
910 if err := checkSumDB(mod, h); err != nil {
911 return err
912 }
913 }
914
915 if done {
916 return nil
917 }
918
919
920 if inited {
921 f.mu.Lock()
922 addModSumLocked(f, mod, h)
923 st := f.sumState.status[modSum{mod, h}]
924 st.dirty = true
925 f.sumState.status[modSum{mod, h}] = st
926 f.mu.Unlock()
927 }
928 return nil
929 }
930
931
932
933
934 func haveModSumLocked(f *Fetcher, mod module.Version, h string) bool {
935 sumFileName := "go.sum"
936 if strings.HasSuffix(f.goSumFile, "go.work.sum") {
937 sumFileName = "go.work.sum"
938 }
939 for _, vh := range f.sumState.m[mod] {
940 if h == vh {
941 return true
942 }
943 if strings.HasPrefix(vh, "h1:") {
944 base.Fatalf("verifying %s@%s: checksum mismatch\n\tdownloaded: %v\n\t%s: %v"+goSumMismatch, mod.Path, mod.Version, h, sumFileName, vh)
945 }
946 }
947
948 foundMatch := false
949
950
951 for goSumFile, goSums := range f.sumState.w {
952 for _, vh := range goSums[mod] {
953 if h == vh {
954 foundMatch = true
955 } else if strings.HasPrefix(vh, "h1:") {
956 base.Fatalf("verifying %s@%s: checksum mismatch\n\tdownloaded: %v\n\t%s: %v"+goSumMismatch, mod.Path, mod.Version, h, goSumFile, vh)
957 }
958 }
959 }
960 return foundMatch
961 }
962
963
964
965 func addModSumLocked(f *Fetcher, mod module.Version, h string) {
966 if haveModSumLocked(f, mod, h) {
967 return
968 }
969 if len(f.sumState.m[mod]) > 0 {
970 fmt.Fprintf(os.Stderr, "warning: verifying %s@%s: unknown hashes in go.sum: %v; adding %v"+hashVersionMismatch, mod.Path, mod.Version, strings.Join(f.sumState.m[mod], ", "), h)
971 }
972 f.sumState.m[mod] = append(f.sumState.m[mod], h)
973 }
974
975
976
977 func checkSumDB(mod module.Version, h string) error {
978 modWithoutSuffix := mod
979 noun := "module"
980 if before, found := strings.CutSuffix(mod.Version, "/go.mod"); found {
981 noun = "go.mod"
982 modWithoutSuffix.Version = before
983 }
984
985 db, lines, err := lookupSumDB(mod)
986 if err != nil {
987 return module.VersionError(modWithoutSuffix, fmt.Errorf("verifying %s: %v", noun, err))
988 }
989
990 have := mod.Path + " " + mod.Version + " " + h
991 prefix := mod.Path + " " + mod.Version + " h1:"
992 for _, line := range lines {
993 if line == have {
994 return nil
995 }
996 if strings.HasPrefix(line, prefix) {
997 return module.VersionError(modWithoutSuffix, fmt.Errorf("verifying %s: checksum mismatch\n\tdownloaded: %v\n\t%s: %v"+sumdbMismatch, noun, h, db, line[len(prefix)-len("h1:"):]))
998 }
999 }
1000 return module.VersionError(modWithoutSuffix, fmt.Errorf("verifying %s: checksum missing from sumdb response"+sumdbAbsent, noun))
1001 }
1002
1003
1004
1005 func Sum(ctx context.Context, mod module.Version) string {
1006 if cfg.GOMODCACHE == "" {
1007
1008 return ""
1009 }
1010
1011 ziphash, err := CachePath(ctx, mod, "ziphash")
1012 if err != nil {
1013 return ""
1014 }
1015 data, err := lockedfile.Read(ziphash)
1016 if err != nil {
1017 return ""
1018 }
1019 data = bytes.TrimSpace(data)
1020 if !isValidSum(data) {
1021 return ""
1022 }
1023 return string(data)
1024 }
1025
1026
1027
1028
1029
1030
1031 func isValidSum(data []byte) bool {
1032 if bytes.IndexByte(data, '\000') >= 0 {
1033 return false
1034 }
1035
1036 if len(data) != len("h1:")+base64.StdEncoding.EncodedLen(sha256.Size) {
1037 return false
1038 }
1039
1040 return true
1041 }
1042
1043 var ErrGoSumDirty = errors.New("updates to go.sum needed, disabled by -mod=readonly")
1044
1045
1046
1047
1048
1049
1050
1051 func (f *Fetcher) WriteGoSum(ctx context.Context, keep map[module.Version]bool, readonly bool) error {
1052 f.mu.Lock()
1053 defer f.mu.Unlock()
1054
1055
1056 if !f.sumState.enabled {
1057 return nil
1058 }
1059
1060
1061
1062
1063 dirty := false
1064 Outer:
1065 for m, hs := range f.sumState.m {
1066 for _, h := range hs {
1067 st := f.sumState.status[modSum{m, h}]
1068 if st.dirty && (!st.used || keep[m]) {
1069 dirty = true
1070 break Outer
1071 }
1072 }
1073 }
1074 if !dirty {
1075 return nil
1076 }
1077 if readonly {
1078 return ErrGoSumDirty
1079 }
1080 if fsys.Replaced(f.goSumFile) {
1081 base.Fatalf("go: updates to go.sum needed, but go.sum is part of the overlay specified with -overlay")
1082 }
1083
1084
1085
1086 if unlock, err := SideLock(ctx); err == nil {
1087 defer unlock()
1088 }
1089
1090 err := lockedfile.Transform(f.goSumFile, func(data []byte) ([]byte, error) {
1091 tidyGoSum := tidyGoSum(f, data, keep)
1092 return tidyGoSum, nil
1093 })
1094 if err != nil {
1095 return fmt.Errorf("updating go.sum: %w", err)
1096 }
1097
1098 f.sumState.status = make(map[modSum]modSumStatus)
1099 f.sumState.overwrite = false
1100 return nil
1101 }
1102
1103
1104
1105 func (f *Fetcher) TidyGoSum(keep map[module.Version]bool) (before, after []byte) {
1106 f.mu.Lock()
1107 defer f.mu.Unlock()
1108 before, err := lockedfile.Read(f.goSumFile)
1109 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1110 base.Fatalf("reading go.sum: %v", err)
1111 }
1112 after = tidyGoSum(f, before, keep)
1113 return before, after
1114 }
1115
1116
1117
1118 func tidyGoSum(f *Fetcher, data []byte, keep map[module.Version]bool) []byte {
1119 if !f.sumState.overwrite {
1120
1121
1122
1123
1124 f.sumState.m = make(map[module.Version][]string, len(f.sumState.m))
1125 readGoSum(f.sumState.m, f.goSumFile, data)
1126 for ms, st := range f.sumState.status {
1127 if st.used && !sumInWorkspaceModulesLocked(f, ms.mod) {
1128 addModSumLocked(f, ms.mod, ms.sum)
1129 }
1130 }
1131 }
1132
1133 mods := make([]module.Version, 0, len(f.sumState.m))
1134 for m := range f.sumState.m {
1135 mods = append(mods, m)
1136 }
1137 module.Sort(mods)
1138
1139 var buf bytes.Buffer
1140 for _, m := range mods {
1141 list := f.sumState.m[m]
1142 sort.Strings(list)
1143 str.Uniq(&list)
1144 for _, h := range list {
1145 st := f.sumState.status[modSum{m, h}]
1146 if (!st.dirty || (st.used && keep[m])) && !sumInWorkspaceModulesLocked(f, m) {
1147 fmt.Fprintf(&buf, "%s %s %s\n", m.Path, m.Version, h)
1148 }
1149 }
1150 }
1151 return buf.Bytes()
1152 }
1153
1154 func sumInWorkspaceModulesLocked(f *Fetcher, m module.Version) bool {
1155 for _, goSums := range f.sumState.w {
1156 if _, ok := goSums[m]; ok {
1157 return true
1158 }
1159 }
1160 return false
1161 }
1162
1163
1164
1165
1166
1167
1168
1169 func (f *Fetcher) TrimGoSum(keep map[module.Version]bool) {
1170 f.mu.Lock()
1171 defer f.mu.Unlock()
1172 inited, err := f.initGoSum()
1173 if err != nil {
1174 base.Fatalf("%s", err)
1175 }
1176 if !inited {
1177 return
1178 }
1179
1180 for m, hs := range f.sumState.m {
1181 if !keep[m] {
1182 for _, h := range hs {
1183 f.sumState.status[modSum{m, h}] = modSumStatus{used: false, dirty: true}
1184 }
1185 f.sumState.overwrite = true
1186 }
1187 }
1188 }
1189
1190 const goSumMismatch = `
1191
1192 SECURITY ERROR
1193 This download does NOT match an earlier download recorded in go.sum.
1194 The bits may have been replaced on the origin server, or an attacker may
1195 have intercepted the download attempt.
1196
1197 For more information, see 'go help module-auth'.
1198 `
1199
1200 const sumdbMismatch = `
1201
1202 SECURITY ERROR
1203 This download does NOT match the one reported by the checksum server.
1204 The bits may have been replaced on the origin server, or an attacker may
1205 have intercepted the download attempt.
1206
1207 For more information, see 'go help module-auth'.
1208 `
1209
1210 const sumdbAbsent = `
1211
1212 SECURITY ERROR
1213 This download does NOT match one reported by the checksum server.
1214 The checksum server has provided checksums, but the checksums do
1215 not contain an entry for the download.
1216 The checksum server may be malfunctioning, or an attacker may have
1217 intercepted the checksum request.
1218 The download cannot be verified.
1219
1220 For more information, see 'go help module-auth'.
1221 `
1222
1223 const hashVersionMismatch = `
1224
1225 SECURITY WARNING
1226 This download is listed in go.sum, but using an unknown hash algorithm.
1227 The download cannot be verified.
1228
1229 For more information, see 'go help module-auth'.
1230
1231 `
1232
1233 var HelpModuleAuth = &base.Command{
1234 UsageLine: "module-auth",
1235 Short: "module authentication using go.sum",
1236 Long: `
1237 When the go command downloads a module zip file or go.mod file into the
1238 module cache, it computes a cryptographic hash and compares it with a known
1239 value to verify the file hasn't changed since it was first downloaded. Known
1240 hashes are stored in a file in the module root directory named go.sum. Hashes
1241 may also be downloaded from the checksum database depending on the values of
1242 GOSUMDB, GOPRIVATE, and GONOSUMDB.
1243
1244 For details, see https://go.dev/ref/mod#authenticating.
1245 `,
1246 }
1247
1248 var HelpPrivate = &base.Command{
1249 UsageLine: "private",
1250 Short: "configuration for downloading non-public code",
1251 Long: `
1252 The go command defaults to downloading modules from the public Go module
1253 mirror at proxy.golang.org. It also defaults to validating downloaded modules,
1254 regardless of source, against the public Go checksum database at sum.golang.org.
1255 These defaults work well for publicly available source code.
1256
1257 The GOPRIVATE environment variable controls which modules the go command
1258 considers to be private (not available publicly) and should therefore not use
1259 the proxy or checksum database. The variable is a comma-separated list of
1260 glob patterns (in the syntax of Go's path.Match) of module path prefixes.
1261 For example,
1262
1263 GOPRIVATE=*.corp.example.com,rsc.io/private
1264
1265 causes the go command to treat as private any module with a path prefix
1266 matching either pattern, including git.corp.example.com/xyzzy, rsc.io/private,
1267 and rsc.io/private/quux.
1268
1269 For fine-grained control over module download and validation, the GONOPROXY
1270 and GONOSUMDB environment variables accept the same kind of glob list
1271 and override GOPRIVATE for the specific decision of whether to use the proxy
1272 and checksum database, respectively.
1273
1274 For example, if a company ran a module proxy serving private modules,
1275 users would configure go using:
1276
1277 GOPRIVATE=*.corp.example.com
1278 GOPROXY=proxy.example.com
1279 GONOPROXY=none
1280
1281 The GOPRIVATE variable is also used to define the "public" and "private"
1282 patterns for the GOVCS variable; see 'go help vcs'. For that usage,
1283 GOPRIVATE applies even in GOPATH mode. In that case, it matches import paths
1284 instead of module paths.
1285
1286 The 'go env -w' command (see 'go help env') can be used to set these variables
1287 for future go command invocations.
1288
1289 For more details, see https://go.dev/ref/mod#private-modules.
1290 `,
1291 }
1292
View as plain text