1
2
3
4
5 package vcs
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "internal/godebug"
12 "internal/lazyregexp"
13 "internal/singleflight"
14 "io/fs"
15 "log"
16 urlpkg "net/url"
17 "os"
18 "os/exec"
19 "path/filepath"
20 "strconv"
21 "strings"
22 "sync"
23 "time"
24
25 "cmd/go/internal/base"
26 "cmd/go/internal/cfg"
27 "cmd/go/internal/search"
28 "cmd/go/internal/str"
29 "cmd/go/internal/web"
30 "cmd/internal/pathcache"
31
32 "golang.org/x/mod/module"
33 )
34
35
36
37 type Cmd struct {
38 Name string
39 Cmd string
40 Env []string
41 Roots []isVCSRoot
42
43 Scheme []string
44 PingCmd string
45
46 Status func(v *Cmd, rootDir string) (Status, error)
47 }
48
49
50 type Status struct {
51 Revision string
52 CommitTime time.Time
53 Uncommitted bool
54 }
55
56 var (
57
58
59
60
61
62 VCSTestRepoURL string
63
64
65 VCSTestHosts []string
66
67
68
69 VCSTestIsLocalHost func(*urlpkg.URL) bool
70 )
71
72 var defaultSecureScheme = map[string]bool{
73 "https": true,
74 "git+ssh": true,
75 "bzr+ssh": true,
76 "svn+ssh": true,
77 "ssh": true,
78 }
79
80 func (v *Cmd) IsSecure(repo string) bool {
81 u, err := urlpkg.Parse(repo)
82 if err != nil {
83
84 return false
85 }
86 if VCSTestRepoURL != "" && web.IsLocalHost(u) {
87
88
89
90 return true
91 }
92 return v.isSecureScheme(u.Scheme)
93 }
94
95 func (v *Cmd) isSecureScheme(scheme string) bool {
96 switch v.Cmd {
97 case "git":
98
99
100
101 if allow := os.Getenv("GIT_ALLOW_PROTOCOL"); allow != "" {
102 for s := range strings.SplitSeq(allow, ":") {
103 if s == scheme {
104 return true
105 }
106 }
107 return false
108 }
109 }
110 return defaultSecureScheme[scheme]
111 }
112
113
114
115 type tagCmd struct {
116 cmd string
117 pattern string
118 }
119
120
121 var vcsList = []*Cmd{
122 vcsHg,
123 vcsGit,
124 vcsSvn,
125 vcsBzr,
126 vcsFossil,
127 }
128
129
130
131 var vcsMod = &Cmd{Name: "mod"}
132
133
134
135 func vcsByCmd(cmd string) *Cmd {
136 for _, vcs := range vcsList {
137 if vcs.Cmd == cmd {
138 return vcs
139 }
140 }
141 return nil
142 }
143
144
145 var vcsHg = &Cmd{
146 Name: "Mercurial",
147 Cmd: "hg",
148
149
150
151 Env: []string{"HGPLAIN=+strictflags"},
152 Roots: []isVCSRoot{
153 vcsDirRoot(".hg"),
154 },
155
156 Scheme: []string{"https", "http", "ssh"},
157 PingCmd: "identify -- {scheme}://{repo}",
158 Status: hgStatus,
159 }
160
161 func hgStatus(vcsHg *Cmd, rootDir string) (Status, error) {
162
163 out, err := vcsHg.runOutputVerboseOnly(rootDir, `log -r. -T {node}:{date|hgdate}`)
164 if err != nil {
165 return Status{}, err
166 }
167
168 var rev string
169 var commitTime time.Time
170 if len(out) > 0 {
171
172 if i := bytes.IndexByte(out, ' '); i > 0 {
173 out = out[:i]
174 }
175 rev, commitTime, err = parseRevTime(out)
176 if err != nil {
177 return Status{}, err
178 }
179 }
180
181
182 out, err = vcsHg.runOutputVerboseOnly(rootDir, "status -S")
183 if err != nil {
184 return Status{}, err
185 }
186 uncommitted := len(out) > 0
187
188 return Status{
189 Revision: rev,
190 CommitTime: commitTime,
191 Uncommitted: uncommitted,
192 }, nil
193 }
194
195
196 func parseRevTime(out []byte) (string, time.Time, error) {
197 buf := string(bytes.TrimSpace(out))
198
199 i := strings.IndexByte(buf, ':')
200 if i < 1 {
201 return "", time.Time{}, errors.New("unrecognized VCS tool output")
202 }
203 rev := buf[:i]
204
205 secs, err := strconv.ParseInt(buf[i+1:], 10, 64)
206 if err != nil {
207 return "", time.Time{}, fmt.Errorf("unrecognized VCS tool output: %v", err)
208 }
209
210 return rev, time.Unix(secs, 0), nil
211 }
212
213
214 var vcsGit = &Cmd{
215 Name: "Git",
216 Cmd: "git",
217 Roots: []isVCSRoot{
218 vcsGitRoot{},
219 },
220
221 Scheme: []string{"git", "https", "http", "git+ssh", "ssh"},
222
223
224
225
226
227 PingCmd: "ls-remote {scheme}://{repo}",
228
229 Status: gitStatus,
230 }
231
232 func gitStatus(vcsGit *Cmd, rootDir string) (Status, error) {
233 out, err := vcsGit.runOutputVerboseOnly(rootDir, "status --porcelain")
234 if err != nil {
235 return Status{}, err
236 }
237 uncommitted := len(out) > 0
238
239
240
241
242 var rev string
243 var commitTime time.Time
244 out, err = vcsGit.runOutputVerboseOnly(rootDir, "-c log.showsignature=false log -1 --format=%H:%ct")
245 if err != nil && !uncommitted {
246 return Status{}, err
247 } else if err == nil {
248 rev, commitTime, err = parseRevTime(out)
249 if err != nil {
250 return Status{}, err
251 }
252 }
253
254 return Status{
255 Revision: rev,
256 CommitTime: commitTime,
257 Uncommitted: uncommitted,
258 }, nil
259 }
260
261
262 var vcsBzr = &Cmd{
263 Name: "Bazaar",
264 Cmd: "bzr",
265 Roots: []isVCSRoot{
266 vcsDirRoot(".bzr"),
267 },
268
269 Scheme: []string{"https", "http", "bzr", "bzr+ssh"},
270 PingCmd: "info -- {scheme}://{repo}",
271 Status: bzrStatus,
272 }
273
274 func bzrStatus(vcsBzr *Cmd, rootDir string) (Status, error) {
275 outb, err := vcsBzr.runOutputVerboseOnly(rootDir, "version-info")
276 if err != nil {
277 return Status{}, err
278 }
279 out := string(outb)
280
281
282
283
284
285
286 var rev string
287 var commitTime time.Time
288
289 for line := range strings.SplitSeq(out, "\n") {
290 i := strings.IndexByte(line, ':')
291 if i < 0 {
292 continue
293 }
294 key := line[:i]
295 value := strings.TrimSpace(line[i+1:])
296
297 switch key {
298 case "revision-id":
299 rev = value
300 case "date":
301 var err error
302 commitTime, err = time.Parse("2006-01-02 15:04:05 -0700", value)
303 if err != nil {
304 return Status{}, errors.New("unable to parse output of bzr version-info")
305 }
306 }
307 }
308
309 outb, err = vcsBzr.runOutputVerboseOnly(rootDir, "status")
310 if err != nil {
311 return Status{}, err
312 }
313
314
315 if bytes.HasPrefix(outb, []byte("working tree is out of date")) {
316 i := bytes.IndexByte(outb, '\n')
317 if i < 0 {
318 i = len(outb)
319 }
320 outb = outb[:i]
321 }
322 uncommitted := len(outb) > 0
323
324 return Status{
325 Revision: rev,
326 CommitTime: commitTime,
327 Uncommitted: uncommitted,
328 }, nil
329 }
330
331
332 var vcsSvn = &Cmd{
333 Name: "Subversion",
334 Cmd: "svn",
335 Roots: []isVCSRoot{
336 vcsDirRoot(".svn"),
337 },
338
339
340
341
342 Scheme: []string{"https", "http", "svn", "svn+ssh"},
343 PingCmd: "info -- {scheme}://{repo}",
344 Status: svnStatus,
345 }
346
347 func svnStatus(vcsSvn *Cmd, rootDir string) (Status, error) {
348 out, err := vcsSvn.runOutputVerboseOnly(rootDir, "info --show-item last-changed-revision")
349 if err != nil {
350 return Status{}, err
351 }
352 rev := strings.TrimSpace(string(out))
353
354 out, err = vcsSvn.runOutputVerboseOnly(rootDir, "info --show-item last-changed-date")
355 if err != nil {
356 return Status{}, err
357 }
358 commitTime, err := time.Parse(time.RFC3339, strings.TrimSpace(string(out)))
359 if err != nil {
360 return Status{}, fmt.Errorf("unable to parse output of svn info: %v", err)
361 }
362
363 out, err = vcsSvn.runOutputVerboseOnly(rootDir, "status")
364 if err != nil {
365 return Status{}, err
366 }
367 uncommitted := len(out) > 0
368
369 return Status{
370 Revision: rev,
371 CommitTime: commitTime,
372 Uncommitted: uncommitted,
373 }, nil
374 }
375
376
377
378 const fossilRepoName = ".fossil"
379
380
381 var vcsFossil = &Cmd{
382 Name: "Fossil",
383 Cmd: "fossil",
384 Roots: []isVCSRoot{
385 vcsFileRoot(".fslckout"),
386 vcsFileRoot("_FOSSIL_"),
387 },
388
389 Scheme: []string{"https", "http"},
390 Status: fossilStatus,
391 }
392
393 var errFossilInfo = errors.New("unable to parse output of fossil info")
394
395 func fossilStatus(vcsFossil *Cmd, rootDir string) (Status, error) {
396 outb, err := vcsFossil.runOutputVerboseOnly(rootDir, "info")
397 if err != nil {
398 return Status{}, err
399 }
400 out := string(outb)
401
402
403
404
405
406
407
408
409 const prefix = "\ncheckout:"
410 const suffix = " UTC"
411 i := strings.Index(out, prefix)
412 if i < 0 {
413 return Status{}, errFossilInfo
414 }
415 checkout := out[i+len(prefix):]
416 i = strings.Index(checkout, suffix)
417 if i < 0 {
418 return Status{}, errFossilInfo
419 }
420 checkout = strings.TrimSpace(checkout[:i])
421
422 i = strings.IndexByte(checkout, ' ')
423 if i < 0 {
424 return Status{}, errFossilInfo
425 }
426 rev := checkout[:i]
427
428 commitTime, err := time.ParseInLocation(time.DateTime, checkout[i+1:], time.UTC)
429 if err != nil {
430 return Status{}, fmt.Errorf("%v: %v", errFossilInfo, err)
431 }
432
433
434 outb, err = vcsFossil.runOutputVerboseOnly(rootDir, "changes --differ")
435 if err != nil {
436 return Status{}, err
437 }
438 uncommitted := len(outb) > 0
439
440 return Status{
441 Revision: rev,
442 CommitTime: commitTime,
443 Uncommitted: uncommitted,
444 }, nil
445 }
446
447 func (v *Cmd) String() string {
448 return v.Name
449 }
450
451
452
453
454
455
456
457
458 func (v *Cmd) run(dir string, cmd string, keyval ...string) error {
459 _, err := v.run1(dir, cmd, keyval, true)
460 return err
461 }
462
463
464 func (v *Cmd) runVerboseOnly(dir string, cmd string, keyval ...string) error {
465 _, err := v.run1(dir, cmd, keyval, false)
466 return err
467 }
468
469
470 func (v *Cmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) {
471 return v.run1(dir, cmd, keyval, true)
472 }
473
474
475
476 func (v *Cmd) runOutputVerboseOnly(dir string, cmd string, keyval ...string) ([]byte, error) {
477 return v.run1(dir, cmd, keyval, false)
478 }
479
480
481 func (v *Cmd) run1(dir string, cmdline string, keyval []string, verbose bool) ([]byte, error) {
482 m := make(map[string]string)
483 for i := 0; i < len(keyval); i += 2 {
484 m[keyval[i]] = keyval[i+1]
485 }
486 args := strings.Fields(cmdline)
487 for i, arg := range args {
488 args[i] = expand(m, arg)
489 }
490
491 if len(args) >= 2 && args[0] == "--go-internal-mkdir" {
492 var err error
493 if filepath.IsAbs(args[1]) {
494 err = os.Mkdir(args[1], fs.ModePerm)
495 } else {
496 err = os.Mkdir(filepath.Join(dir, args[1]), fs.ModePerm)
497 }
498 if err != nil {
499 return nil, err
500 }
501 args = args[2:]
502 }
503
504 if len(args) >= 2 && args[0] == "--go-internal-cd" {
505 if filepath.IsAbs(args[1]) {
506 dir = args[1]
507 } else {
508 dir = filepath.Join(dir, args[1])
509 }
510 args = args[2:]
511 }
512
513 _, err := pathcache.LookPath(v.Cmd)
514 if err != nil {
515 fmt.Fprintf(os.Stderr,
516 "go: missing %s command. See https://golang.org/s/gogetcmd\n",
517 v.Name)
518 return nil, err
519 }
520
521 cmd := exec.Command(v.Cmd, args...)
522 cmd.Dir = dir
523 if v.Env != nil {
524 cmd.Env = append(cmd.Environ(), v.Env...)
525 }
526 if cfg.BuildX {
527 fmt.Fprintf(os.Stderr, "cd %s\n", dir)
528 fmt.Fprintf(os.Stderr, "%s %s\n", v.Cmd, strings.Join(args, " "))
529 }
530 out, err := cmd.Output()
531 if err != nil {
532 if verbose || cfg.BuildV {
533 fmt.Fprintf(os.Stderr, "# cd %s; %s %s\n", dir, v.Cmd, strings.Join(args, " "))
534 if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 {
535 os.Stderr.Write(ee.Stderr)
536 } else {
537 fmt.Fprintln(os.Stderr, err.Error())
538 }
539 }
540 }
541 return out, err
542 }
543
544
545 func (v *Cmd) Ping(scheme, repo string) error {
546
547
548
549
550 dir := cfg.GOMODCACHE
551 if !cfg.ModulesEnabled {
552 dir = filepath.Join(cfg.BuildContext.GOPATH, "src")
553 }
554 os.MkdirAll(dir, 0o777)
555
556 release, err := base.AcquireNet()
557 if err != nil {
558 return err
559 }
560 defer release()
561
562 return v.runVerboseOnly(dir, v.PingCmd, "scheme", scheme, "repo", repo)
563 }
564
565
566
567 type vcsPath struct {
568 pathPrefix string
569 regexp *lazyregexp.Regexp
570 repo string
571 vcs string
572 check func(match map[string]string) error
573 schemelessRepo bool
574 }
575
576 var allowmultiplevcs = godebug.New("allowmultiplevcs")
577
578
579
580
581
582 func FromDir(dir, srcRoot string) (repoDir string, vcsCmd *Cmd, err error) {
583
584 dir = filepath.Clean(dir)
585 if srcRoot != "" {
586 srcRoot = filepath.Clean(srcRoot)
587 if len(dir) <= len(srcRoot) || dir[len(srcRoot)] != filepath.Separator {
588 return "", nil, fmt.Errorf("directory %q is outside source root %q", dir, srcRoot)
589 }
590 }
591
592 origDir := dir
593 for len(dir) > len(srcRoot) {
594 for _, vcs := range vcsList {
595 if isVCSRootDir(dir, vcs.Roots) {
596 if vcsCmd == nil {
597
598 vcsCmd = vcs
599 repoDir = dir
600 if allowmultiplevcs.Value() == "1" {
601 allowmultiplevcs.IncNonDefault()
602 return repoDir, vcsCmd, nil
603 }
604
605
606
607
608 continue
609 }
610 if vcsCmd == vcsGit && vcs == vcsGit {
611
612
613
614 continue
615 }
616 return "", nil, fmt.Errorf("multiple VCS detected: %s in %q, and %s in %q",
617 vcsCmd.Cmd, repoDir, vcs.Cmd, dir)
618 }
619 }
620
621
622 ndir := filepath.Dir(dir)
623 if len(ndir) >= len(dir) {
624 break
625 }
626 dir = ndir
627 }
628 if vcsCmd == nil {
629 return "", nil, &vcsNotFoundError{dir: origDir}
630 }
631 return repoDir, vcsCmd, nil
632 }
633
634
635 func isVCSRootDir(dir string, roots []isVCSRoot) bool {
636 for _, root := range roots {
637 if root.isRoot(dir) {
638 return true
639 }
640 }
641 return false
642 }
643
644 type isVCSRoot interface {
645 isRoot(dir string) bool
646 }
647
648
649 type vcsFileRoot string
650
651 func (vfr vcsFileRoot) isRoot(dir string) bool {
652 fi, err := os.Stat(filepath.Join(dir, string(vfr)))
653 return err == nil && fi.Mode().IsRegular()
654 }
655
656
657 type vcsDirRoot string
658
659 func (vdr vcsDirRoot) isRoot(dir string) bool {
660 fi, err := os.Stat(filepath.Join(dir, string(vdr)))
661 return err == nil && fi.IsDir()
662 }
663
664
665
666 type vcsGitRoot struct{}
667
668 func (vcsGitRoot) isRoot(dir string) bool {
669 path := filepath.Join(dir, ".git")
670 fi, err := os.Stat(path)
671 if err != nil {
672 return false
673 }
674 if fi.IsDir() {
675 return true
676 }
677
678
679 if !fi.Mode().IsRegular() || fi.Size() == 0 || fi.Size() > 4096 {
680 return false
681 }
682 raw, err := os.ReadFile(path)
683 if err != nil {
684 return false
685 }
686 rest, ok := strings.CutPrefix(string(raw), "gitdir:")
687 if !ok {
688 return false
689 }
690 gitdir := strings.TrimSpace(rest)
691 if gitdir == "" {
692 return false
693 }
694 if !filepath.IsAbs(gitdir) {
695 gitdir = filepath.Join(dir, gitdir)
696 }
697 fi, err = os.Stat(gitdir)
698 return err == nil && fi.IsDir()
699 }
700
701 type vcsNotFoundError struct {
702 dir string
703 }
704
705 func (e *vcsNotFoundError) Error() string {
706 return fmt.Sprintf("directory %q is not using a known version control system", e.dir)
707 }
708
709 func (e *vcsNotFoundError) Is(err error) bool {
710 return err == os.ErrNotExist
711 }
712
713
714 type govcsRule struct {
715 pattern string
716 allowed []string
717 }
718
719
720 type govcsConfig []govcsRule
721
722 func parseGOVCS(s string) (govcsConfig, error) {
723 s = strings.TrimSpace(s)
724 if s == "" {
725 return nil, nil
726 }
727 var cfg govcsConfig
728 have := make(map[string]string)
729 for item := range strings.SplitSeq(s, ",") {
730 item = strings.TrimSpace(item)
731 if item == "" {
732 return nil, fmt.Errorf("empty entry in GOVCS")
733 }
734 pattern, list, found := strings.Cut(item, ":")
735 if !found {
736 return nil, fmt.Errorf("malformed entry in GOVCS (missing colon): %q", item)
737 }
738 pattern, list = strings.TrimSpace(pattern), strings.TrimSpace(list)
739 if pattern == "" {
740 return nil, fmt.Errorf("empty pattern in GOVCS: %q", item)
741 }
742 if list == "" {
743 return nil, fmt.Errorf("empty VCS list in GOVCS: %q", item)
744 }
745 if search.IsRelativePath(pattern) {
746 return nil, fmt.Errorf("relative pattern not allowed in GOVCS: %q", pattern)
747 }
748 if old := have[pattern]; old != "" {
749 return nil, fmt.Errorf("unreachable pattern in GOVCS: %q after %q", item, old)
750 }
751 have[pattern] = item
752 allowed := strings.Split(list, "|")
753 for i, a := range allowed {
754 a = strings.TrimSpace(a)
755 if a == "" {
756 return nil, fmt.Errorf("empty VCS name in GOVCS: %q", item)
757 }
758 allowed[i] = a
759 }
760 cfg = append(cfg, govcsRule{pattern, allowed})
761 }
762 return cfg, nil
763 }
764
765 func (c *govcsConfig) allow(path string, private bool, vcs string) bool {
766 for _, rule := range *c {
767 match := false
768 switch rule.pattern {
769 case "private":
770 match = private
771 case "public":
772 match = !private
773 default:
774
775
776 match = module.MatchPrefixPatterns(rule.pattern, path)
777 }
778 if !match {
779 continue
780 }
781 for _, allow := range rule.allowed {
782 if allow == vcs || allow == "all" {
783 return true
784 }
785 }
786 return false
787 }
788
789
790 return false
791 }
792
793 var (
794 govcs govcsConfig
795 govcsErr error
796 govcsOnce sync.Once
797 )
798
799
800
801
802
803
804
805
806
807
808
809
810
811 var defaultGOVCS = govcsConfig{
812 {"private", []string{"all"}},
813 {"public", []string{"git", "hg"}},
814 }
815
816
817
818
819
820 func checkGOVCS(vcs *Cmd, root string) error {
821 if vcs == vcsMod {
822
823
824
825 return nil
826 }
827
828 govcsOnce.Do(func() {
829 govcs, govcsErr = parseGOVCS(os.Getenv("GOVCS"))
830 govcs = append(govcs, defaultGOVCS...)
831 })
832 if govcsErr != nil {
833 return govcsErr
834 }
835
836 private := module.MatchPrefixPatterns(cfg.GOPRIVATE, root)
837 if !govcs.allow(root, private, vcs.Cmd) {
838 what := "public"
839 if private {
840 what = "private"
841 }
842 return fmt.Errorf("GOVCS disallows using %s for %s %s; see 'go help vcs'", vcs.Cmd, what, root)
843 }
844
845 return nil
846 }
847
848
849 type RepoRoot struct {
850 Repo string
851 Root string
852 SubDir string
853 IsCustom bool
854 VCS *Cmd
855 }
856
857 func httpPrefix(s string) string {
858 for _, prefix := range [...]string{"http:", "https:"} {
859 if strings.HasPrefix(s, prefix) {
860 return prefix
861 }
862 }
863 return ""
864 }
865
866
867 type ModuleMode int
868
869 const (
870 IgnoreMod ModuleMode = iota
871 PreferMod
872 )
873
874
875
876 func RepoRootForImportPath(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) {
877 rr, err := repoRootFromVCSPaths(importPath, security, vcsPaths)
878 if err == errUnknownSite {
879 rr, err = repoRootForImportDynamic(importPath, mod, security)
880 if err != nil {
881 err = importErrorf(importPath, "unrecognized import path %q: %v", importPath, err)
882 }
883 }
884 if err != nil {
885 rr1, err1 := repoRootFromVCSPaths(importPath, security, vcsPathsAfterDynamic)
886 if err1 == nil {
887 rr = rr1
888 err = nil
889 }
890 }
891
892
893 if err == nil && strings.Contains(importPath, "...") && strings.Contains(rr.Root, "...") {
894
895 rr = nil
896 err = importErrorf(importPath, "cannot expand ... in %q", importPath)
897 }
898 return rr, err
899 }
900
901 var errUnknownSite = errors.New("dynamic lookup required to find mapping")
902
903
904
905 func repoRootFromVCSPaths(importPath string, security web.SecurityMode, vcsPaths []*vcsPath) (*RepoRoot, error) {
906 if str.HasPathPrefix(importPath, "example.net") {
907
908
909
910
911 return nil, fmt.Errorf("no modules on example.net")
912 }
913 if importPath == "rsc.io" {
914
915
916
917
918 return nil, fmt.Errorf("rsc.io is not a module")
919 }
920
921
922 if prefix := httpPrefix(importPath); prefix != "" {
923
924
925 return nil, fmt.Errorf("%q not allowed in import path", prefix+"//")
926 }
927 for _, srv := range vcsPaths {
928 if !str.HasPathPrefix(importPath, srv.pathPrefix) {
929 continue
930 }
931 m := srv.regexp.FindStringSubmatch(importPath)
932 if m == nil {
933 if srv.pathPrefix != "" {
934 return nil, importErrorf(importPath, "invalid %s import path %q", srv.pathPrefix, importPath)
935 }
936 continue
937 }
938
939
940 match := map[string]string{
941 "prefix": srv.pathPrefix + "/",
942 "import": importPath,
943 }
944 for i, name := range srv.regexp.SubexpNames() {
945 if name != "" && match[name] == "" {
946 match[name] = m[i]
947 }
948 }
949 if srv.vcs != "" {
950 match["vcs"] = expand(match, srv.vcs)
951 }
952 if srv.repo != "" {
953 match["repo"] = expand(match, srv.repo)
954 }
955 if srv.check != nil {
956 if err := srv.check(match); err != nil {
957 return nil, err
958 }
959 }
960 vcs := vcsByCmd(match["vcs"])
961 if vcs == nil {
962 return nil, fmt.Errorf("unknown version control system %q", match["vcs"])
963 }
964 if err := checkGOVCS(vcs, match["root"]); err != nil {
965 return nil, err
966 }
967 var repoURL string
968 if !srv.schemelessRepo {
969 repoURL = match["repo"]
970 } else {
971 repo := match["repo"]
972 var ok bool
973 repoURL, ok = interceptVCSTest(repo, vcs, security)
974 if !ok {
975 scheme, err := func() (string, error) {
976 for _, s := range vcs.Scheme {
977 if security == web.SecureOnly && !vcs.isSecureScheme(s) {
978 continue
979 }
980
981
982
983
984
985 if vcs.PingCmd == "" {
986 return s, nil
987 }
988 if err := vcs.Ping(s, repo); err == nil {
989 return s, nil
990 }
991 }
992 securityFrag := ""
993 if security == web.SecureOnly {
994 securityFrag = "secure "
995 }
996 return "", fmt.Errorf("no %sprotocol found for repository", securityFrag)
997 }()
998 if err != nil {
999 return nil, err
1000 }
1001 repoURL = scheme + "://" + repo
1002 }
1003 }
1004 rr := &RepoRoot{
1005 Repo: repoURL,
1006 Root: match["root"],
1007 VCS: vcs,
1008 }
1009 return rr, nil
1010 }
1011 return nil, errUnknownSite
1012 }
1013
1014 func interceptVCSTest(repo string, vcs *Cmd, security web.SecurityMode) (repoURL string, ok bool) {
1015 if VCSTestRepoURL == "" {
1016 return "", false
1017 }
1018 if vcs == vcsMod {
1019
1020
1021 return "", false
1022 }
1023
1024 if scheme, path, ok := strings.Cut(repo, "://"); ok {
1025 if security == web.SecureOnly && !vcs.isSecureScheme(scheme) {
1026 return "", false
1027 }
1028 repo = path
1029 }
1030 for _, host := range VCSTestHosts {
1031 if !str.HasPathPrefix(repo, host) {
1032 continue
1033 }
1034
1035 httpURL := VCSTestRepoURL + strings.TrimPrefix(repo, host)
1036
1037 if vcs == vcsSvn {
1038
1039
1040 u, err := urlpkg.Parse(httpURL + "?vcwebsvn=1")
1041 if err != nil {
1042 panic(fmt.Sprintf("invalid vcs-test repo URL: %v", err))
1043 }
1044 svnURL, err := web.GetBytes(u)
1045 svnURL = bytes.TrimSpace(svnURL)
1046 if err == nil && len(svnURL) > 0 {
1047 return string(svnURL) + strings.TrimPrefix(repo, host), true
1048 }
1049
1050
1051
1052 }
1053
1054 return httpURL, true
1055 }
1056 return "", false
1057 }
1058
1059
1060
1061
1062
1063 func urlForImportPath(importPath string) (*urlpkg.URL, error) {
1064 slash := strings.Index(importPath, "/")
1065 if slash < 0 {
1066 slash = len(importPath)
1067 }
1068 host, path := importPath[:slash], importPath[slash:]
1069 if !strings.Contains(host, ".") {
1070 return nil, errors.New("import path does not begin with hostname")
1071 }
1072 if len(path) == 0 {
1073 path = "/"
1074 }
1075 return &urlpkg.URL{Host: host, Path: path, RawQuery: "go-get=1"}, nil
1076 }
1077
1078
1079
1080
1081
1082 func repoRootForImportDynamic(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) {
1083 url, err := urlForImportPath(importPath)
1084 if err != nil {
1085 return nil, err
1086 }
1087 resp, err := web.Get(security, url)
1088 if err != nil {
1089 msg := "https fetch: %v"
1090 if security == web.Insecure {
1091 msg = "http/" + msg
1092 }
1093 return nil, fmt.Errorf(msg, err)
1094 }
1095 body := resp.Body
1096 defer body.Close()
1097 imports, err := parseMetaGoImports(body, mod)
1098 if len(imports) == 0 {
1099 if respErr := resp.Err(); respErr != nil {
1100
1101
1102 return nil, respErr
1103 }
1104 }
1105 if err != nil {
1106 return nil, fmt.Errorf("parsing %s: %v", importPath, err)
1107 }
1108
1109 mmi, err := matchGoImport(imports, importPath)
1110 if err != nil {
1111 if _, ok := err.(ImportMismatchError); !ok {
1112 return nil, fmt.Errorf("parse %s: %v", url, err)
1113 }
1114 return nil, fmt.Errorf("parse %s: no go-import meta tags (%s)", resp.URL, err)
1115 }
1116 if cfg.BuildV {
1117 log.Printf("get %q: found meta tag %#v at %s", importPath, mmi, url)
1118 }
1119
1120
1121
1122
1123
1124
1125 if mmi.Prefix != importPath {
1126 if cfg.BuildV {
1127 log.Printf("get %q: verifying non-authoritative meta tag", importPath)
1128 }
1129 var imports []metaImport
1130 url, imports, err = metaImportsForPrefix(mmi.Prefix, mod, security)
1131 if err != nil {
1132 return nil, err
1133 }
1134 metaImport2, err := matchGoImport(imports, importPath)
1135 if err != nil || mmi != metaImport2 {
1136 return nil, fmt.Errorf("%s and %s disagree about go-import for %s", resp.URL, url, mmi.Prefix)
1137 }
1138 }
1139
1140 if err := validateRepoSubDir(mmi.SubDir); err != nil {
1141 return nil, fmt.Errorf("%s: invalid subdirectory %q: %v", resp.URL, mmi.SubDir, err)
1142 }
1143
1144 if err := validateRepoRoot(mmi.RepoRoot); err != nil {
1145 return nil, fmt.Errorf("%s: invalid repo root %q: %v", resp.URL, mmi.RepoRoot, err)
1146 }
1147 var vcs *Cmd
1148 if mmi.VCS == "mod" {
1149 vcs = vcsMod
1150 } else {
1151 vcs = vcsByCmd(mmi.VCS)
1152 if vcs == nil {
1153 return nil, fmt.Errorf("%s: unknown vcs %q", resp.URL, mmi.VCS)
1154 }
1155 }
1156
1157 if err := checkGOVCS(vcs, mmi.Prefix); err != nil {
1158 return nil, err
1159 }
1160
1161 repoURL, ok := interceptVCSTest(mmi.RepoRoot, vcs, security)
1162 if !ok {
1163 repoURL = mmi.RepoRoot
1164 }
1165 rr := &RepoRoot{
1166 Repo: repoURL,
1167 Root: mmi.Prefix,
1168 SubDir: mmi.SubDir,
1169 IsCustom: true,
1170 VCS: vcs,
1171 }
1172 return rr, nil
1173 }
1174
1175
1176
1177
1178 func validateRepoSubDir(subdir string) error {
1179 if subdir == "" {
1180 return nil
1181 }
1182 if subdir[0] == '/' {
1183 return errors.New("leading slash")
1184 }
1185 if subdir[0] == '-' {
1186 return errors.New("leading hyphen")
1187 }
1188 return nil
1189 }
1190
1191
1192
1193 func validateRepoRoot(repoRoot string) error {
1194 url, err := urlpkg.Parse(repoRoot)
1195 if err != nil {
1196 return err
1197 }
1198 if url.Scheme == "" {
1199 return errors.New("no scheme")
1200 }
1201 if url.Scheme == "file" {
1202 return errors.New("file scheme disallowed")
1203 }
1204 return nil
1205 }
1206
1207 var fetchGroup singleflight.Group
1208 var (
1209 fetchCacheMu sync.Mutex
1210 fetchCache = map[string]fetchResult{}
1211 )
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221 func metaImportsForPrefix(importPrefix string, mod ModuleMode, security web.SecurityMode) (*urlpkg.URL, []metaImport, error) {
1222 setCache := func(res fetchResult) (fetchResult, error) {
1223 fetchCacheMu.Lock()
1224 defer fetchCacheMu.Unlock()
1225 fetchCache[importPrefix] = res
1226 return res, nil
1227 }
1228
1229 resi, _, _ := fetchGroup.Do(importPrefix, func() (resi any, err error) {
1230 fetchCacheMu.Lock()
1231 if res, ok := fetchCache[importPrefix]; ok {
1232 fetchCacheMu.Unlock()
1233 return res, nil
1234 }
1235 fetchCacheMu.Unlock()
1236
1237 url, err := urlForImportPath(importPrefix)
1238 if err != nil {
1239 return setCache(fetchResult{err: err})
1240 }
1241 resp, err := web.Get(security, url)
1242 if err != nil {
1243 return setCache(fetchResult{url: url, err: fmt.Errorf("fetching %s: %v", importPrefix, err)})
1244 }
1245 body := resp.Body
1246 defer body.Close()
1247 imports, err := parseMetaGoImports(body, mod)
1248 if len(imports) == 0 {
1249 if respErr := resp.Err(); respErr != nil {
1250
1251
1252 return setCache(fetchResult{url: url, err: respErr})
1253 }
1254 }
1255 if err != nil {
1256 return setCache(fetchResult{url: url, err: fmt.Errorf("parsing %s: %v", resp.URL, err)})
1257 }
1258 if len(imports) == 0 {
1259 err = fmt.Errorf("fetching %s: no go-import meta tag found in %s", importPrefix, resp.URL)
1260 }
1261 return setCache(fetchResult{url: url, imports: imports, err: err})
1262 })
1263 res := resi.(fetchResult)
1264 return res.url, res.imports, res.err
1265 }
1266
1267 type fetchResult struct {
1268 url *urlpkg.URL
1269 imports []metaImport
1270 err error
1271 }
1272
1273
1274
1275 type metaImport struct {
1276 Prefix, VCS, RepoRoot, SubDir string
1277 }
1278
1279
1280
1281 type ImportMismatchError struct {
1282 importPath string
1283 mismatches []string
1284 }
1285
1286 func (m ImportMismatchError) Error() string {
1287 formattedStrings := make([]string, len(m.mismatches))
1288 for i, pre := range m.mismatches {
1289 formattedStrings[i] = fmt.Sprintf("meta tag %s did not match import path %s", pre, m.importPath)
1290 }
1291 return strings.Join(formattedStrings, ", ")
1292 }
1293
1294
1295
1296
1297 func matchGoImport(imports []metaImport, importPath string) (metaImport, error) {
1298 match := -1
1299
1300 errImportMismatch := ImportMismatchError{importPath: importPath}
1301 for i, im := range imports {
1302 if !str.HasPathPrefix(importPath, im.Prefix) {
1303 errImportMismatch.mismatches = append(errImportMismatch.mismatches, im.Prefix)
1304 continue
1305 }
1306
1307 if match >= 0 {
1308 if imports[match].VCS == "mod" && im.VCS != "mod" {
1309
1310
1311
1312 break
1313 }
1314 return metaImport{}, fmt.Errorf("multiple meta tags match import path %q", importPath)
1315 }
1316 match = i
1317 }
1318
1319 if match == -1 {
1320 return metaImport{}, errImportMismatch
1321 }
1322 return imports[match], nil
1323 }
1324
1325
1326 func expand(match map[string]string, s string) string {
1327
1328
1329
1330 oldNew := make([]string, 0, 2*len(match))
1331 for k, v := range match {
1332 oldNew = append(oldNew, "{"+k+"}", v)
1333 }
1334 return strings.NewReplacer(oldNew...).Replace(s)
1335 }
1336
1337
1338
1339
1340
1341 var vcsPaths = []*vcsPath{
1342
1343 {
1344 pathPrefix: "github.com",
1345 regexp: lazyregexp.New(`^(?P<root>github\.com/[\w.\-]+/[\w.\-]+)(/[\w.\-]+)*$`),
1346 vcs: "git",
1347 repo: "https://{root}",
1348 check: noVCSSuffix,
1349 },
1350
1351
1352 {
1353 pathPrefix: "bitbucket.org",
1354 regexp: lazyregexp.New(`^(?P<root>bitbucket\.org/(?P<bitname>[\w.\-]+/[\w.\-]+))(/[\w.\-]+)*$`),
1355 vcs: "git",
1356 repo: "https://{root}",
1357 check: noVCSSuffix,
1358 },
1359
1360
1361 {
1362 pathPrefix: "hub.jazz.net/git",
1363 regexp: lazyregexp.New(`^(?P<root>hub\.jazz\.net/git/[a-z0-9]+/[\w.\-]+)(/[\w.\-]+)*$`),
1364 vcs: "git",
1365 repo: "https://{root}",
1366 check: noVCSSuffix,
1367 },
1368
1369
1370 {
1371 pathPrefix: "git.apache.org",
1372 regexp: lazyregexp.New(`^(?P<root>git\.apache\.org/[a-z0-9_.\-]+\.git)(/[\w.\-]+)*$`),
1373 vcs: "git",
1374 repo: "https://{root}",
1375 },
1376
1377
1378 {
1379 pathPrefix: "git.openstack.org",
1380 regexp: lazyregexp.New(`^(?P<root>git\.openstack\.org/[\w.\-]+/[\w.\-]+)(\.git)?(/[\w.\-]+)*$`),
1381 vcs: "git",
1382 repo: "https://{root}",
1383 },
1384
1385
1386 {
1387 pathPrefix: "chiselapp.com",
1388 regexp: lazyregexp.New(`^(?P<root>chiselapp\.com/user/[A-Za-z0-9]+/repository/[\w.\-]+)$`),
1389 vcs: "fossil",
1390 repo: "https://{root}",
1391 },
1392
1393
1394
1395 {
1396 regexp: lazyregexp.New(`(?P<root>(?P<repo>([a-z0-9.\-]+\.)+[a-z0-9.\-]+(:[0-9]+)?(/~?[\w.\-]+)+?)\.(?P<vcs>bzr|fossil|git|hg|svn))(/~?[\w.\-]+)*$`),
1397 schemelessRepo: true,
1398 },
1399 }
1400
1401
1402
1403
1404
1405 var vcsPathsAfterDynamic = []*vcsPath{
1406
1407 {
1408 pathPrefix: "launchpad.net",
1409 regexp: lazyregexp.New(`^(?P<root>launchpad\.net/((?P<project>[\w.\-]+)(?P<series>/[\w.\-]+)?|~[\w.\-]+/(\+junk|[\w.\-]+)/[\w.\-]+))(/[\w.\-]+)*$`),
1410 vcs: "bzr",
1411 repo: "https://{root}",
1412 check: launchpadVCS,
1413 },
1414 }
1415
1416
1417
1418
1419 func noVCSSuffix(match map[string]string) error {
1420 repo := match["repo"]
1421 for _, vcs := range vcsList {
1422 if strings.HasSuffix(repo, "."+vcs.Cmd) {
1423 return fmt.Errorf("invalid version control suffix in %s path", match["prefix"])
1424 }
1425 }
1426 return nil
1427 }
1428
1429
1430
1431
1432
1433 func launchpadVCS(match map[string]string) error {
1434 if match["project"] == "" || match["series"] == "" {
1435 return nil
1436 }
1437 url := &urlpkg.URL{
1438 Scheme: "https",
1439 Host: "code.launchpad.net",
1440 Path: expand(match, "/{project}{series}/.bzr/branch-format"),
1441 }
1442 _, err := web.GetBytes(url)
1443 if err != nil {
1444 match["root"] = expand(match, "launchpad.net/{project}")
1445 match["repo"] = expand(match, "https://{root}")
1446 }
1447 return nil
1448 }
1449
1450
1451
1452 type importError struct {
1453 importPath string
1454 err error
1455 }
1456
1457 func importErrorf(path, format string, args ...any) error {
1458 err := &importError{importPath: path, err: fmt.Errorf(format, args...)}
1459 if errStr := err.Error(); !strings.Contains(errStr, path) {
1460 panic(fmt.Sprintf("path %q not in error %q", path, errStr))
1461 }
1462 return err
1463 }
1464
1465 func (e *importError) Error() string {
1466 return e.err.Error()
1467 }
1468
1469 func (e *importError) Unwrap() error {
1470
1471
1472 return errors.Unwrap(e.err)
1473 }
1474
1475 func (e *importError) ImportPath() string {
1476 return e.importPath
1477 }
1478
View as plain text