Source file src/cmd/go/internal/vcs/vcs.go

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package vcs
     6  
     7  import (
     8  	"bytes"
     9  	"errors"
    10  	"fmt"
    11  	"internal/lazyregexp"
    12  	"internal/singleflight"
    13  	"io/fs"
    14  	"log"
    15  	urlpkg "net/url"
    16  	"os"
    17  	"os/exec"
    18  	"path/filepath"
    19  	"regexp"
    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  // A Cmd describes how to use a version control system
    36  // like Mercurial, Git, or Subversion.
    37  type Cmd struct {
    38  	Name      string
    39  	Cmd       string     // name of binary to invoke command
    40  	Env       []string   // any environment values to set/override
    41  	RootNames []rootName // filename and mode indicating the root of a checkout directory
    42  
    43  	CreateCmd   []string // commands to download a fresh copy of a repository
    44  	DownloadCmd []string // commands to download updates into an existing repository
    45  
    46  	TagCmd         []tagCmd // commands to list tags
    47  	TagLookupCmd   []tagCmd // commands to lookup tags before running tagSyncCmd
    48  	TagSyncCmd     []string // commands to sync to specific tag
    49  	TagSyncDefault []string // commands to sync to default tag
    50  
    51  	Scheme  []string
    52  	PingCmd string
    53  
    54  	RemoteRepo  func(v *Cmd, rootDir string) (remoteRepo string, err error)
    55  	ResolveRepo func(v *Cmd, rootDir, remoteRepo string) (realRepo string, err error)
    56  	Status      func(v *Cmd, rootDir string) (Status, error)
    57  }
    58  
    59  // Status is the current state of a local repository.
    60  type Status struct {
    61  	Revision    string    // Optional.
    62  	CommitTime  time.Time // Optional.
    63  	Uncommitted bool      // Required.
    64  }
    65  
    66  var (
    67  	// VCSTestRepoURL is the URL of the HTTP server that serves the repos for
    68  	// vcs-test.golang.org.
    69  	//
    70  	// In tests, this is set to the URL of an httptest.Server hosting a
    71  	// cmd/go/internal/vcweb.Server.
    72  	VCSTestRepoURL string
    73  
    74  	// VCSTestHosts is the set of hosts supported by the vcs-test server.
    75  	VCSTestHosts []string
    76  
    77  	// VCSTestIsLocalHost reports whether the given URL refers to a local
    78  	// (loopback) host, such as "localhost" or "127.0.0.1:8080".
    79  	VCSTestIsLocalHost func(*urlpkg.URL) bool
    80  )
    81  
    82  var defaultSecureScheme = map[string]bool{
    83  	"https":   true,
    84  	"git+ssh": true,
    85  	"bzr+ssh": true,
    86  	"svn+ssh": true,
    87  	"ssh":     true,
    88  }
    89  
    90  func (v *Cmd) IsSecure(repo string) bool {
    91  	u, err := urlpkg.Parse(repo)
    92  	if err != nil {
    93  		// If repo is not a URL, it's not secure.
    94  		return false
    95  	}
    96  	if VCSTestRepoURL != "" && web.IsLocalHost(u) {
    97  		// If the vcstest server is in use, it may redirect to other local ports for
    98  		// other protocols (such as svn). Assume that all loopback addresses are
    99  		// secure during testing.
   100  		return true
   101  	}
   102  	return v.isSecureScheme(u.Scheme)
   103  }
   104  
   105  func (v *Cmd) isSecureScheme(scheme string) bool {
   106  	switch v.Cmd {
   107  	case "git":
   108  		// GIT_ALLOW_PROTOCOL is an environment variable defined by Git. It is a
   109  		// colon-separated list of schemes that are allowed to be used with git
   110  		// fetch/clone. Any scheme not mentioned will be considered insecure.
   111  		if allow := os.Getenv("GIT_ALLOW_PROTOCOL"); allow != "" {
   112  			for _, s := range strings.Split(allow, ":") {
   113  				if s == scheme {
   114  					return true
   115  				}
   116  			}
   117  			return false
   118  		}
   119  	}
   120  	return defaultSecureScheme[scheme]
   121  }
   122  
   123  // A tagCmd describes a command to list available tags
   124  // that can be passed to tagSyncCmd.
   125  type tagCmd struct {
   126  	cmd     string // command to list tags
   127  	pattern string // regexp to extract tags from list
   128  }
   129  
   130  // vcsList lists the known version control systems
   131  var vcsList = []*Cmd{
   132  	vcsHg,
   133  	vcsGit,
   134  	vcsSvn,
   135  	vcsBzr,
   136  	vcsFossil,
   137  }
   138  
   139  // vcsMod is a stub for the "mod" scheme. It's returned by
   140  // repoRootForImportPathDynamic, but is otherwise not treated as a VCS command.
   141  var vcsMod = &Cmd{Name: "mod"}
   142  
   143  // vcsByCmd returns the version control system for the given
   144  // command name (hg, git, svn, bzr).
   145  func vcsByCmd(cmd string) *Cmd {
   146  	for _, vcs := range vcsList {
   147  		if vcs.Cmd == cmd {
   148  			return vcs
   149  		}
   150  	}
   151  	return nil
   152  }
   153  
   154  // vcsHg describes how to use Mercurial.
   155  var vcsHg = &Cmd{
   156  	Name: "Mercurial",
   157  	Cmd:  "hg",
   158  
   159  	// HGPLAIN=1 turns off additional output that a user may have enabled via
   160  	// config options or certain extensions.
   161  	Env: []string{"HGPLAIN=1"},
   162  	RootNames: []rootName{
   163  		{filename: ".hg", isDir: true},
   164  	},
   165  
   166  	CreateCmd:   []string{"clone -U -- {repo} {dir}"},
   167  	DownloadCmd: []string{"pull"},
   168  
   169  	// We allow both tag and branch names as 'tags'
   170  	// for selecting a version. This lets people have
   171  	// a go.release.r60 branch and a go1 branch
   172  	// and make changes in both, without constantly
   173  	// editing .hgtags.
   174  	TagCmd: []tagCmd{
   175  		{"tags", `^(\S+)`},
   176  		{"branches", `^(\S+)`},
   177  	},
   178  	TagSyncCmd:     []string{"update -r {tag}"},
   179  	TagSyncDefault: []string{"update default"},
   180  
   181  	Scheme:     []string{"https", "http", "ssh"},
   182  	PingCmd:    "identify -- {scheme}://{repo}",
   183  	RemoteRepo: hgRemoteRepo,
   184  	Status:     hgStatus,
   185  }
   186  
   187  func hgRemoteRepo(vcsHg *Cmd, rootDir string) (remoteRepo string, err error) {
   188  	out, err := vcsHg.runOutput(rootDir, "paths default")
   189  	if err != nil {
   190  		return "", err
   191  	}
   192  	return strings.TrimSpace(string(out)), nil
   193  }
   194  
   195  func hgStatus(vcsHg *Cmd, rootDir string) (Status, error) {
   196  	// Output changeset ID and seconds since epoch.
   197  	out, err := vcsHg.runOutputVerboseOnly(rootDir, `log -r. -T {node}:{date|hgdate}`)
   198  	if err != nil {
   199  		return Status{}, err
   200  	}
   201  
   202  	var rev string
   203  	var commitTime time.Time
   204  	if len(out) > 0 {
   205  		// Strip trailing timezone offset.
   206  		if i := bytes.IndexByte(out, ' '); i > 0 {
   207  			out = out[:i]
   208  		}
   209  		rev, commitTime, err = parseRevTime(out)
   210  		if err != nil {
   211  			return Status{}, err
   212  		}
   213  	}
   214  
   215  	// Also look for untracked files.
   216  	out, err = vcsHg.runOutputVerboseOnly(rootDir, "status -S")
   217  	if err != nil {
   218  		return Status{}, err
   219  	}
   220  	uncommitted := len(out) > 0
   221  
   222  	return Status{
   223  		Revision:    rev,
   224  		CommitTime:  commitTime,
   225  		Uncommitted: uncommitted,
   226  	}, nil
   227  }
   228  
   229  // parseRevTime parses commit details in "revision:seconds" format.
   230  func parseRevTime(out []byte) (string, time.Time, error) {
   231  	buf := string(bytes.TrimSpace(out))
   232  
   233  	i := strings.IndexByte(buf, ':')
   234  	if i < 1 {
   235  		return "", time.Time{}, errors.New("unrecognized VCS tool output")
   236  	}
   237  	rev := buf[:i]
   238  
   239  	secs, err := strconv.ParseInt(string(buf[i+1:]), 10, 64)
   240  	if err != nil {
   241  		return "", time.Time{}, fmt.Errorf("unrecognized VCS tool output: %v", err)
   242  	}
   243  
   244  	return rev, time.Unix(secs, 0), nil
   245  }
   246  
   247  // vcsGit describes how to use Git.
   248  var vcsGit = &Cmd{
   249  	Name: "Git",
   250  	Cmd:  "git",
   251  	RootNames: []rootName{
   252  		{filename: ".git", isDir: true},
   253  	},
   254  
   255  	CreateCmd:   []string{"clone -- {repo} {dir}", "-go-internal-cd {dir} submodule update --init --recursive"},
   256  	DownloadCmd: []string{"pull --ff-only", "submodule update --init --recursive"},
   257  
   258  	TagCmd: []tagCmd{
   259  		// tags/xxx matches a git tag named xxx
   260  		// origin/xxx matches a git branch named xxx on the default remote repository
   261  		{"show-ref", `(?:tags|origin)/(\S+)$`},
   262  	},
   263  	TagLookupCmd: []tagCmd{
   264  		{"show-ref tags/{tag} origin/{tag}", `((?:tags|origin)/\S+)$`},
   265  	},
   266  	TagSyncCmd: []string{"checkout {tag}", "submodule update --init --recursive"},
   267  	// both createCmd and downloadCmd update the working dir.
   268  	// No need to do more here. We used to 'checkout master'
   269  	// but that doesn't work if the default branch is not named master.
   270  	// DO NOT add 'checkout master' here.
   271  	// See golang.org/issue/9032.
   272  	TagSyncDefault: []string{"submodule update --init --recursive"},
   273  
   274  	Scheme: []string{"git", "https", "http", "git+ssh", "ssh"},
   275  
   276  	// Leave out the '--' separator in the ls-remote command: git 2.7.4 does not
   277  	// support such a separator for that command, and this use should be safe
   278  	// without it because the {scheme} value comes from the predefined list above.
   279  	// See golang.org/issue/33836.
   280  	PingCmd: "ls-remote {scheme}://{repo}",
   281  
   282  	RemoteRepo: gitRemoteRepo,
   283  	Status:     gitStatus,
   284  }
   285  
   286  // scpSyntaxRe matches the SCP-like addresses used by Git to access
   287  // repositories by SSH.
   288  var scpSyntaxRe = lazyregexp.New(`^(\w+)@([\w.-]+):(.*)$`)
   289  
   290  func gitRemoteRepo(vcsGit *Cmd, rootDir string) (remoteRepo string, err error) {
   291  	const cmd = "config remote.origin.url"
   292  	outb, err := vcsGit.run1(rootDir, cmd, nil, false)
   293  	if err != nil {
   294  		// if it doesn't output any message, it means the config argument is correct,
   295  		// but the config value itself doesn't exist
   296  		if outb != nil && len(outb) == 0 {
   297  			return "", errors.New("remote origin not found")
   298  		}
   299  		return "", err
   300  	}
   301  	out := strings.TrimSpace(string(outb))
   302  
   303  	var repoURL *urlpkg.URL
   304  	if m := scpSyntaxRe.FindStringSubmatch(out); m != nil {
   305  		// Match SCP-like syntax and convert it to a URL.
   306  		// Eg, "git@github.com:user/repo" becomes
   307  		// "ssh://git@github.com/user/repo".
   308  		repoURL = &urlpkg.URL{
   309  			Scheme: "ssh",
   310  			User:   urlpkg.User(m[1]),
   311  			Host:   m[2],
   312  			Path:   m[3],
   313  		}
   314  	} else {
   315  		repoURL, err = urlpkg.Parse(out)
   316  		if err != nil {
   317  			return "", err
   318  		}
   319  	}
   320  
   321  	// Iterate over insecure schemes too, because this function simply
   322  	// reports the state of the repo. If we can't see insecure schemes then
   323  	// we can't report the actual repo URL.
   324  	for _, s := range vcsGit.Scheme {
   325  		if repoURL.Scheme == s {
   326  			return repoURL.String(), nil
   327  		}
   328  	}
   329  	return "", errors.New("unable to parse output of git " + cmd)
   330  }
   331  
   332  func gitStatus(vcsGit *Cmd, rootDir string) (Status, error) {
   333  	out, err := vcsGit.runOutputVerboseOnly(rootDir, "status --porcelain")
   334  	if err != nil {
   335  		return Status{}, err
   336  	}
   337  	uncommitted := len(out) > 0
   338  
   339  	// "git status" works for empty repositories, but "git log" does not.
   340  	// Assume there are no commits in the repo when "git log" fails with
   341  	// uncommitted files and skip tagging revision / committime.
   342  	var rev string
   343  	var commitTime time.Time
   344  	out, err = vcsGit.runOutputVerboseOnly(rootDir, "-c log.showsignature=false log -1 --format=%H:%ct")
   345  	if err != nil && !uncommitted {
   346  		return Status{}, err
   347  	} else if err == nil {
   348  		rev, commitTime, err = parseRevTime(out)
   349  		if err != nil {
   350  			return Status{}, err
   351  		}
   352  	}
   353  
   354  	return Status{
   355  		Revision:    rev,
   356  		CommitTime:  commitTime,
   357  		Uncommitted: uncommitted,
   358  	}, nil
   359  }
   360  
   361  // vcsBzr describes how to use Bazaar.
   362  var vcsBzr = &Cmd{
   363  	Name: "Bazaar",
   364  	Cmd:  "bzr",
   365  	RootNames: []rootName{
   366  		{filename: ".bzr", isDir: true},
   367  	},
   368  
   369  	CreateCmd: []string{"branch -- {repo} {dir}"},
   370  
   371  	// Without --overwrite bzr will not pull tags that changed.
   372  	// Replace by --overwrite-tags after http://pad.lv/681792 goes in.
   373  	DownloadCmd: []string{"pull --overwrite"},
   374  
   375  	TagCmd:         []tagCmd{{"tags", `^(\S+)`}},
   376  	TagSyncCmd:     []string{"update -r {tag}"},
   377  	TagSyncDefault: []string{"update -r revno:-1"},
   378  
   379  	Scheme:      []string{"https", "http", "bzr", "bzr+ssh"},
   380  	PingCmd:     "info -- {scheme}://{repo}",
   381  	RemoteRepo:  bzrRemoteRepo,
   382  	ResolveRepo: bzrResolveRepo,
   383  	Status:      bzrStatus,
   384  }
   385  
   386  func bzrRemoteRepo(vcsBzr *Cmd, rootDir string) (remoteRepo string, err error) {
   387  	outb, err := vcsBzr.runOutput(rootDir, "config parent_location")
   388  	if err != nil {
   389  		return "", err
   390  	}
   391  	return strings.TrimSpace(string(outb)), nil
   392  }
   393  
   394  func bzrResolveRepo(vcsBzr *Cmd, rootDir, remoteRepo string) (realRepo string, err error) {
   395  	outb, err := vcsBzr.runOutput(rootDir, "info "+remoteRepo)
   396  	if err != nil {
   397  		return "", err
   398  	}
   399  	out := string(outb)
   400  
   401  	// Expect:
   402  	// ...
   403  	//   (branch root|repository branch): <URL>
   404  	// ...
   405  
   406  	found := false
   407  	for _, prefix := range []string{"\n  branch root: ", "\n  repository branch: "} {
   408  		i := strings.Index(out, prefix)
   409  		if i >= 0 {
   410  			out = out[i+len(prefix):]
   411  			found = true
   412  			break
   413  		}
   414  	}
   415  	if !found {
   416  		return "", fmt.Errorf("unable to parse output of bzr info")
   417  	}
   418  
   419  	i := strings.Index(out, "\n")
   420  	if i < 0 {
   421  		return "", fmt.Errorf("unable to parse output of bzr info")
   422  	}
   423  	out = out[:i]
   424  	return strings.TrimSpace(out), nil
   425  }
   426  
   427  func bzrStatus(vcsBzr *Cmd, rootDir string) (Status, error) {
   428  	outb, err := vcsBzr.runOutputVerboseOnly(rootDir, "version-info")
   429  	if err != nil {
   430  		return Status{}, err
   431  	}
   432  	out := string(outb)
   433  
   434  	// Expect (non-empty repositories only):
   435  	//
   436  	// revision-id: gopher@gopher.net-20211021072330-qshok76wfypw9lpm
   437  	// date: 2021-09-21 12:00:00 +1000
   438  	// ...
   439  	var rev string
   440  	var commitTime time.Time
   441  
   442  	for _, line := range strings.Split(out, "\n") {
   443  		i := strings.IndexByte(line, ':')
   444  		if i < 0 {
   445  			continue
   446  		}
   447  		key := line[:i]
   448  		value := strings.TrimSpace(line[i+1:])
   449  
   450  		switch key {
   451  		case "revision-id":
   452  			rev = value
   453  		case "date":
   454  			var err error
   455  			commitTime, err = time.Parse("2006-01-02 15:04:05 -0700", value)
   456  			if err != nil {
   457  				return Status{}, errors.New("unable to parse output of bzr version-info")
   458  			}
   459  		}
   460  	}
   461  
   462  	outb, err = vcsBzr.runOutputVerboseOnly(rootDir, "status")
   463  	if err != nil {
   464  		return Status{}, err
   465  	}
   466  
   467  	// Skip warning when working directory is set to an older revision.
   468  	if bytes.HasPrefix(outb, []byte("working tree is out of date")) {
   469  		i := bytes.IndexByte(outb, '\n')
   470  		if i < 0 {
   471  			i = len(outb)
   472  		}
   473  		outb = outb[:i]
   474  	}
   475  	uncommitted := len(outb) > 0
   476  
   477  	return Status{
   478  		Revision:    rev,
   479  		CommitTime:  commitTime,
   480  		Uncommitted: uncommitted,
   481  	}, nil
   482  }
   483  
   484  // vcsSvn describes how to use Subversion.
   485  var vcsSvn = &Cmd{
   486  	Name: "Subversion",
   487  	Cmd:  "svn",
   488  	RootNames: []rootName{
   489  		{filename: ".svn", isDir: true},
   490  	},
   491  
   492  	CreateCmd:   []string{"checkout -- {repo} {dir}"},
   493  	DownloadCmd: []string{"update"},
   494  
   495  	// There is no tag command in subversion.
   496  	// The branch information is all in the path names.
   497  
   498  	Scheme:     []string{"https", "http", "svn", "svn+ssh"},
   499  	PingCmd:    "info -- {scheme}://{repo}",
   500  	RemoteRepo: svnRemoteRepo,
   501  }
   502  
   503  func svnRemoteRepo(vcsSvn *Cmd, rootDir string) (remoteRepo string, err error) {
   504  	outb, err := vcsSvn.runOutput(rootDir, "info")
   505  	if err != nil {
   506  		return "", err
   507  	}
   508  	out := string(outb)
   509  
   510  	// Expect:
   511  	//
   512  	//	 ...
   513  	// 	URL: <URL>
   514  	// 	...
   515  	//
   516  	// Note that we're not using the Repository Root line,
   517  	// because svn allows checking out subtrees.
   518  	// The URL will be the URL of the subtree (what we used with 'svn co')
   519  	// while the Repository Root may be a much higher parent.
   520  	i := strings.Index(out, "\nURL: ")
   521  	if i < 0 {
   522  		return "", fmt.Errorf("unable to parse output of svn info")
   523  	}
   524  	out = out[i+len("\nURL: "):]
   525  	i = strings.Index(out, "\n")
   526  	if i < 0 {
   527  		return "", fmt.Errorf("unable to parse output of svn info")
   528  	}
   529  	out = out[:i]
   530  	return strings.TrimSpace(out), nil
   531  }
   532  
   533  // fossilRepoName is the name go get associates with a fossil repository. In the
   534  // real world the file can be named anything.
   535  const fossilRepoName = ".fossil"
   536  
   537  // vcsFossil describes how to use Fossil (fossil-scm.org)
   538  var vcsFossil = &Cmd{
   539  	Name: "Fossil",
   540  	Cmd:  "fossil",
   541  	RootNames: []rootName{
   542  		{filename: ".fslckout", isDir: false},
   543  		{filename: "_FOSSIL_", isDir: false},
   544  	},
   545  
   546  	CreateCmd:   []string{"-go-internal-mkdir {dir} clone -- {repo} " + filepath.Join("{dir}", fossilRepoName), "-go-internal-cd {dir} open .fossil"},
   547  	DownloadCmd: []string{"up"},
   548  
   549  	TagCmd:         []tagCmd{{"tag ls", `(.*)`}},
   550  	TagSyncCmd:     []string{"up tag:{tag}"},
   551  	TagSyncDefault: []string{"up trunk"},
   552  
   553  	Scheme:     []string{"https", "http"},
   554  	RemoteRepo: fossilRemoteRepo,
   555  	Status:     fossilStatus,
   556  }
   557  
   558  func fossilRemoteRepo(vcsFossil *Cmd, rootDir string) (remoteRepo string, err error) {
   559  	out, err := vcsFossil.runOutput(rootDir, "remote-url")
   560  	if err != nil {
   561  		return "", err
   562  	}
   563  	return strings.TrimSpace(string(out)), nil
   564  }
   565  
   566  var errFossilInfo = errors.New("unable to parse output of fossil info")
   567  
   568  func fossilStatus(vcsFossil *Cmd, rootDir string) (Status, error) {
   569  	outb, err := vcsFossil.runOutputVerboseOnly(rootDir, "info")
   570  	if err != nil {
   571  		return Status{}, err
   572  	}
   573  	out := string(outb)
   574  
   575  	// Expect:
   576  	// ...
   577  	// checkout:     91ed71f22c77be0c3e250920f47bfd4e1f9024d2 2021-09-21 12:00:00 UTC
   578  	// ...
   579  
   580  	// Extract revision and commit time.
   581  	// Ensure line ends with UTC (known timezone offset).
   582  	const prefix = "\ncheckout:"
   583  	const suffix = " UTC"
   584  	i := strings.Index(out, prefix)
   585  	if i < 0 {
   586  		return Status{}, errFossilInfo
   587  	}
   588  	checkout := out[i+len(prefix):]
   589  	i = strings.Index(checkout, suffix)
   590  	if i < 0 {
   591  		return Status{}, errFossilInfo
   592  	}
   593  	checkout = strings.TrimSpace(checkout[:i])
   594  
   595  	i = strings.IndexByte(checkout, ' ')
   596  	if i < 0 {
   597  		return Status{}, errFossilInfo
   598  	}
   599  	rev := checkout[:i]
   600  
   601  	commitTime, err := time.ParseInLocation(time.DateTime, checkout[i+1:], time.UTC)
   602  	if err != nil {
   603  		return Status{}, fmt.Errorf("%v: %v", errFossilInfo, err)
   604  	}
   605  
   606  	// Also look for untracked changes.
   607  	outb, err = vcsFossil.runOutputVerboseOnly(rootDir, "changes --differ")
   608  	if err != nil {
   609  		return Status{}, err
   610  	}
   611  	uncommitted := len(outb) > 0
   612  
   613  	return Status{
   614  		Revision:    rev,
   615  		CommitTime:  commitTime,
   616  		Uncommitted: uncommitted,
   617  	}, nil
   618  }
   619  
   620  func (v *Cmd) String() string {
   621  	return v.Name
   622  }
   623  
   624  // run runs the command line cmd in the given directory.
   625  // keyval is a list of key, value pairs. run expands
   626  // instances of {key} in cmd into value, but only after
   627  // splitting cmd into individual arguments.
   628  // If an error occurs, run prints the command line and the
   629  // command's combined stdout+stderr to standard error.
   630  // Otherwise run discards the command's output.
   631  func (v *Cmd) run(dir string, cmd string, keyval ...string) error {
   632  	_, err := v.run1(dir, cmd, keyval, true)
   633  	return err
   634  }
   635  
   636  // runVerboseOnly is like run but only generates error output to standard error in verbose mode.
   637  func (v *Cmd) runVerboseOnly(dir string, cmd string, keyval ...string) error {
   638  	_, err := v.run1(dir, cmd, keyval, false)
   639  	return err
   640  }
   641  
   642  // runOutput is like run but returns the output of the command.
   643  func (v *Cmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) {
   644  	return v.run1(dir, cmd, keyval, true)
   645  }
   646  
   647  // runOutputVerboseOnly is like runOutput but only generates error output to
   648  // standard error in verbose mode.
   649  func (v *Cmd) runOutputVerboseOnly(dir string, cmd string, keyval ...string) ([]byte, error) {
   650  	return v.run1(dir, cmd, keyval, false)
   651  }
   652  
   653  // run1 is the generalized implementation of run and runOutput.
   654  func (v *Cmd) run1(dir string, cmdline string, keyval []string, verbose bool) ([]byte, error) {
   655  	m := make(map[string]string)
   656  	for i := 0; i < len(keyval); i += 2 {
   657  		m[keyval[i]] = keyval[i+1]
   658  	}
   659  	args := strings.Fields(cmdline)
   660  	for i, arg := range args {
   661  		args[i] = expand(m, arg)
   662  	}
   663  
   664  	if len(args) >= 2 && args[0] == "-go-internal-mkdir" {
   665  		var err error
   666  		if filepath.IsAbs(args[1]) {
   667  			err = os.Mkdir(args[1], fs.ModePerm)
   668  		} else {
   669  			err = os.Mkdir(filepath.Join(dir, args[1]), fs.ModePerm)
   670  		}
   671  		if err != nil {
   672  			return nil, err
   673  		}
   674  		args = args[2:]
   675  	}
   676  
   677  	if len(args) >= 2 && args[0] == "-go-internal-cd" {
   678  		if filepath.IsAbs(args[1]) {
   679  			dir = args[1]
   680  		} else {
   681  			dir = filepath.Join(dir, args[1])
   682  		}
   683  		args = args[2:]
   684  	}
   685  
   686  	_, err := pathcache.LookPath(v.Cmd)
   687  	if err != nil {
   688  		fmt.Fprintf(os.Stderr,
   689  			"go: missing %s command. See https://golang.org/s/gogetcmd\n",
   690  			v.Name)
   691  		return nil, err
   692  	}
   693  
   694  	cmd := exec.Command(v.Cmd, args...)
   695  	cmd.Dir = dir
   696  	if v.Env != nil {
   697  		cmd.Env = append(cmd.Environ(), v.Env...)
   698  	}
   699  	if cfg.BuildX {
   700  		fmt.Fprintf(os.Stderr, "cd %s\n", dir)
   701  		fmt.Fprintf(os.Stderr, "%s %s\n", v.Cmd, strings.Join(args, " "))
   702  	}
   703  	out, err := cmd.Output()
   704  	if err != nil {
   705  		if verbose || cfg.BuildV {
   706  			fmt.Fprintf(os.Stderr, "# cd %s; %s %s\n", dir, v.Cmd, strings.Join(args, " "))
   707  			if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 {
   708  				os.Stderr.Write(ee.Stderr)
   709  			} else {
   710  				fmt.Fprintln(os.Stderr, err.Error())
   711  			}
   712  		}
   713  	}
   714  	return out, err
   715  }
   716  
   717  // Ping pings to determine scheme to use.
   718  func (v *Cmd) Ping(scheme, repo string) error {
   719  	// Run the ping command in an arbitrary working directory,
   720  	// but don't let the current working directory pollute the results.
   721  	// In module mode, we expect GOMODCACHE to exist and be a safe place for
   722  	// commands; in GOPATH mode, we expect that to be true of GOPATH/src.
   723  	dir := cfg.GOMODCACHE
   724  	if !cfg.ModulesEnabled {
   725  		dir = filepath.Join(cfg.BuildContext.GOPATH, "src")
   726  	}
   727  	os.MkdirAll(dir, 0777) // Ignore errors — if unsuccessful, the command will likely fail.
   728  
   729  	release, err := base.AcquireNet()
   730  	if err != nil {
   731  		return err
   732  	}
   733  	defer release()
   734  
   735  	return v.runVerboseOnly(dir, v.PingCmd, "scheme", scheme, "repo", repo)
   736  }
   737  
   738  // Create creates a new copy of repo in dir.
   739  // The parent of dir must exist; dir must not.
   740  func (v *Cmd) Create(dir, repo string) error {
   741  	release, err := base.AcquireNet()
   742  	if err != nil {
   743  		return err
   744  	}
   745  	defer release()
   746  
   747  	for _, cmd := range v.CreateCmd {
   748  		if err := v.run(filepath.Dir(dir), cmd, "dir", dir, "repo", repo); err != nil {
   749  			return err
   750  		}
   751  	}
   752  	return nil
   753  }
   754  
   755  // Download downloads any new changes for the repo in dir.
   756  func (v *Cmd) Download(dir string) error {
   757  	release, err := base.AcquireNet()
   758  	if err != nil {
   759  		return err
   760  	}
   761  	defer release()
   762  
   763  	for _, cmd := range v.DownloadCmd {
   764  		if err := v.run(dir, cmd); err != nil {
   765  			return err
   766  		}
   767  	}
   768  	return nil
   769  }
   770  
   771  // Tags returns the list of available tags for the repo in dir.
   772  func (v *Cmd) Tags(dir string) ([]string, error) {
   773  	var tags []string
   774  	for _, tc := range v.TagCmd {
   775  		out, err := v.runOutput(dir, tc.cmd)
   776  		if err != nil {
   777  			return nil, err
   778  		}
   779  		re := regexp.MustCompile(`(?m-s)` + tc.pattern)
   780  		for _, m := range re.FindAllStringSubmatch(string(out), -1) {
   781  			tags = append(tags, m[1])
   782  		}
   783  	}
   784  	return tags, nil
   785  }
   786  
   787  // TagSync syncs the repo in dir to the named tag,
   788  // which either is a tag returned by tags or is v.tagDefault.
   789  func (v *Cmd) TagSync(dir, tag string) error {
   790  	if v.TagSyncCmd == nil {
   791  		return nil
   792  	}
   793  	if tag != "" {
   794  		for _, tc := range v.TagLookupCmd {
   795  			out, err := v.runOutput(dir, tc.cmd, "tag", tag)
   796  			if err != nil {
   797  				return err
   798  			}
   799  			re := regexp.MustCompile(`(?m-s)` + tc.pattern)
   800  			m := re.FindStringSubmatch(string(out))
   801  			if len(m) > 1 {
   802  				tag = m[1]
   803  				break
   804  			}
   805  		}
   806  	}
   807  
   808  	release, err := base.AcquireNet()
   809  	if err != nil {
   810  		return err
   811  	}
   812  	defer release()
   813  
   814  	if tag == "" && v.TagSyncDefault != nil {
   815  		for _, cmd := range v.TagSyncDefault {
   816  			if err := v.run(dir, cmd); err != nil {
   817  				return err
   818  			}
   819  		}
   820  		return nil
   821  	}
   822  
   823  	for _, cmd := range v.TagSyncCmd {
   824  		if err := v.run(dir, cmd, "tag", tag); err != nil {
   825  			return err
   826  		}
   827  	}
   828  	return nil
   829  }
   830  
   831  // A vcsPath describes how to convert an import path into a
   832  // version control system and repository name.
   833  type vcsPath struct {
   834  	pathPrefix     string                              // prefix this description applies to
   835  	regexp         *lazyregexp.Regexp                  // compiled pattern for import path
   836  	repo           string                              // repository to use (expand with match of re)
   837  	vcs            string                              // version control system to use (expand with match of re)
   838  	check          func(match map[string]string) error // additional checks
   839  	schemelessRepo bool                                // if true, the repo pattern lacks a scheme
   840  }
   841  
   842  // FromDir inspects dir and its parents to determine the
   843  // version control system and code repository to use.
   844  // If no repository is found, FromDir returns an error
   845  // equivalent to os.ErrNotExist.
   846  func FromDir(dir, srcRoot string, allowNesting bool) (repoDir string, vcsCmd *Cmd, err error) {
   847  	// Clean and double-check that dir is in (a subdirectory of) srcRoot.
   848  	dir = filepath.Clean(dir)
   849  	if srcRoot != "" {
   850  		srcRoot = filepath.Clean(srcRoot)
   851  		if len(dir) <= len(srcRoot) || dir[len(srcRoot)] != filepath.Separator {
   852  			return "", nil, fmt.Errorf("directory %q is outside source root %q", dir, srcRoot)
   853  		}
   854  	}
   855  
   856  	origDir := dir
   857  	for len(dir) > len(srcRoot) {
   858  		for _, vcs := range vcsList {
   859  			if isVCSRoot(dir, vcs.RootNames) {
   860  				// Record first VCS we find.
   861  				// If allowNesting is false (as it is in GOPATH), keep looking for
   862  				// repositories in parent directories and report an error if one is
   863  				// found to mitigate VCS injection attacks.
   864  				if vcsCmd == nil {
   865  					vcsCmd = vcs
   866  					repoDir = dir
   867  					if allowNesting {
   868  						return repoDir, vcsCmd, nil
   869  					}
   870  					continue
   871  				}
   872  				// Otherwise, we have one VCS inside a different VCS.
   873  				return "", nil, fmt.Errorf("directory %q uses %s, but parent %q uses %s",
   874  					repoDir, vcsCmd.Cmd, dir, vcs.Cmd)
   875  			}
   876  		}
   877  
   878  		// Move to parent.
   879  		ndir := filepath.Dir(dir)
   880  		if len(ndir) >= len(dir) {
   881  			break
   882  		}
   883  		dir = ndir
   884  	}
   885  	if vcsCmd == nil {
   886  		return "", nil, &vcsNotFoundError{dir: origDir}
   887  	}
   888  	return repoDir, vcsCmd, nil
   889  }
   890  
   891  // isVCSRoot identifies a VCS root by checking whether the directory contains
   892  // any of the listed root names.
   893  func isVCSRoot(dir string, rootNames []rootName) bool {
   894  	for _, root := range rootNames {
   895  		fi, err := os.Stat(filepath.Join(dir, root.filename))
   896  		if err == nil && fi.IsDir() == root.isDir {
   897  			return true
   898  		}
   899  	}
   900  
   901  	return false
   902  }
   903  
   904  type rootName struct {
   905  	filename string
   906  	isDir    bool
   907  }
   908  
   909  type vcsNotFoundError struct {
   910  	dir string
   911  }
   912  
   913  func (e *vcsNotFoundError) Error() string {
   914  	return fmt.Sprintf("directory %q is not using a known version control system", e.dir)
   915  }
   916  
   917  func (e *vcsNotFoundError) Is(err error) bool {
   918  	return err == os.ErrNotExist
   919  }
   920  
   921  // A govcsRule is a single GOVCS rule like private:hg|svn.
   922  type govcsRule struct {
   923  	pattern string
   924  	allowed []string
   925  }
   926  
   927  // A govcsConfig is a full GOVCS configuration.
   928  type govcsConfig []govcsRule
   929  
   930  func parseGOVCS(s string) (govcsConfig, error) {
   931  	s = strings.TrimSpace(s)
   932  	if s == "" {
   933  		return nil, nil
   934  	}
   935  	var cfg govcsConfig
   936  	have := make(map[string]string)
   937  	for _, item := range strings.Split(s, ",") {
   938  		item = strings.TrimSpace(item)
   939  		if item == "" {
   940  			return nil, fmt.Errorf("empty entry in GOVCS")
   941  		}
   942  		pattern, list, found := strings.Cut(item, ":")
   943  		if !found {
   944  			return nil, fmt.Errorf("malformed entry in GOVCS (missing colon): %q", item)
   945  		}
   946  		pattern, list = strings.TrimSpace(pattern), strings.TrimSpace(list)
   947  		if pattern == "" {
   948  			return nil, fmt.Errorf("empty pattern in GOVCS: %q", item)
   949  		}
   950  		if list == "" {
   951  			return nil, fmt.Errorf("empty VCS list in GOVCS: %q", item)
   952  		}
   953  		if search.IsRelativePath(pattern) {
   954  			return nil, fmt.Errorf("relative pattern not allowed in GOVCS: %q", pattern)
   955  		}
   956  		if old := have[pattern]; old != "" {
   957  			return nil, fmt.Errorf("unreachable pattern in GOVCS: %q after %q", item, old)
   958  		}
   959  		have[pattern] = item
   960  		allowed := strings.Split(list, "|")
   961  		for i, a := range allowed {
   962  			a = strings.TrimSpace(a)
   963  			if a == "" {
   964  				return nil, fmt.Errorf("empty VCS name in GOVCS: %q", item)
   965  			}
   966  			allowed[i] = a
   967  		}
   968  		cfg = append(cfg, govcsRule{pattern, allowed})
   969  	}
   970  	return cfg, nil
   971  }
   972  
   973  func (c *govcsConfig) allow(path string, private bool, vcs string) bool {
   974  	for _, rule := range *c {
   975  		match := false
   976  		switch rule.pattern {
   977  		case "private":
   978  			match = private
   979  		case "public":
   980  			match = !private
   981  		default:
   982  			// Note: rule.pattern is known to be comma-free,
   983  			// so MatchPrefixPatterns is only matching a single pattern for us.
   984  			match = module.MatchPrefixPatterns(rule.pattern, path)
   985  		}
   986  		if !match {
   987  			continue
   988  		}
   989  		for _, allow := range rule.allowed {
   990  			if allow == vcs || allow == "all" {
   991  				return true
   992  			}
   993  		}
   994  		return false
   995  	}
   996  
   997  	// By default, nothing is allowed.
   998  	return false
   999  }
  1000  
  1001  var (
  1002  	govcs     govcsConfig
  1003  	govcsErr  error
  1004  	govcsOnce sync.Once
  1005  )
  1006  
  1007  // defaultGOVCS is the default setting for GOVCS.
  1008  // Setting GOVCS adds entries ahead of these but does not remove them.
  1009  // (They are appended to the parsed GOVCS setting.)
  1010  //
  1011  // The rationale behind allowing only Git and Mercurial is that
  1012  // these two systems have had the most attention to issues
  1013  // of being run as clients of untrusted servers. In contrast,
  1014  // Bazaar, Fossil, and Subversion have primarily been used
  1015  // in trusted, authenticated environments and are not as well
  1016  // scrutinized as attack surfaces.
  1017  //
  1018  // See golang.org/issue/41730 for details.
  1019  var defaultGOVCS = govcsConfig{
  1020  	{"private", []string{"all"}},
  1021  	{"public", []string{"git", "hg"}},
  1022  }
  1023  
  1024  // checkGOVCS checks whether the policy defined by the environment variable
  1025  // GOVCS allows the given vcs command to be used with the given repository
  1026  // root path. Note that root may not be a real package or module path; it's
  1027  // the same as the root path in the go-import meta tag.
  1028  func checkGOVCS(vcs *Cmd, root string) error {
  1029  	if vcs == vcsMod {
  1030  		// Direct module (proxy protocol) fetches don't
  1031  		// involve an external version control system
  1032  		// and are always allowed.
  1033  		return nil
  1034  	}
  1035  
  1036  	govcsOnce.Do(func() {
  1037  		govcs, govcsErr = parseGOVCS(os.Getenv("GOVCS"))
  1038  		govcs = append(govcs, defaultGOVCS...)
  1039  	})
  1040  	if govcsErr != nil {
  1041  		return govcsErr
  1042  	}
  1043  
  1044  	private := module.MatchPrefixPatterns(cfg.GOPRIVATE, root)
  1045  	if !govcs.allow(root, private, vcs.Cmd) {
  1046  		what := "public"
  1047  		if private {
  1048  			what = "private"
  1049  		}
  1050  		return fmt.Errorf("GOVCS disallows using %s for %s %s; see 'go help vcs'", vcs.Cmd, what, root)
  1051  	}
  1052  
  1053  	return nil
  1054  }
  1055  
  1056  // RepoRoot describes the repository root for a tree of source code.
  1057  type RepoRoot struct {
  1058  	Repo     string // repository URL, including scheme
  1059  	Root     string // import path corresponding to root of repo
  1060  	IsCustom bool   // defined by served <meta> tags (as opposed to hard-coded pattern)
  1061  	VCS      *Cmd
  1062  }
  1063  
  1064  func httpPrefix(s string) string {
  1065  	for _, prefix := range [...]string{"http:", "https:"} {
  1066  		if strings.HasPrefix(s, prefix) {
  1067  			return prefix
  1068  		}
  1069  	}
  1070  	return ""
  1071  }
  1072  
  1073  // ModuleMode specifies whether to prefer modules when looking up code sources.
  1074  type ModuleMode int
  1075  
  1076  const (
  1077  	IgnoreMod ModuleMode = iota
  1078  	PreferMod
  1079  )
  1080  
  1081  // RepoRootForImportPath analyzes importPath to determine the
  1082  // version control system, and code repository to use.
  1083  func RepoRootForImportPath(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) {
  1084  	rr, err := repoRootFromVCSPaths(importPath, security, vcsPaths)
  1085  	if err == errUnknownSite {
  1086  		rr, err = repoRootForImportDynamic(importPath, mod, security)
  1087  		if err != nil {
  1088  			err = importErrorf(importPath, "unrecognized import path %q: %v", importPath, err)
  1089  		}
  1090  	}
  1091  	if err != nil {
  1092  		rr1, err1 := repoRootFromVCSPaths(importPath, security, vcsPathsAfterDynamic)
  1093  		if err1 == nil {
  1094  			rr = rr1
  1095  			err = nil
  1096  		}
  1097  	}
  1098  
  1099  	// Should have been taken care of above, but make sure.
  1100  	if err == nil && strings.Contains(importPath, "...") && strings.Contains(rr.Root, "...") {
  1101  		// Do not allow wildcards in the repo root.
  1102  		rr = nil
  1103  		err = importErrorf(importPath, "cannot expand ... in %q", importPath)
  1104  	}
  1105  	return rr, err
  1106  }
  1107  
  1108  var errUnknownSite = errors.New("dynamic lookup required to find mapping")
  1109  
  1110  // repoRootFromVCSPaths attempts to map importPath to a repoRoot
  1111  // using the mappings defined in vcsPaths.
  1112  func repoRootFromVCSPaths(importPath string, security web.SecurityMode, vcsPaths []*vcsPath) (*RepoRoot, error) {
  1113  	if str.HasPathPrefix(importPath, "example.net") {
  1114  		// TODO(rsc): This should not be necessary, but it's required to keep
  1115  		// tests like ../../testdata/script/mod_get_extra.txt from using the network.
  1116  		// That script has everything it needs in the replacement set, but it is still
  1117  		// doing network calls.
  1118  		return nil, fmt.Errorf("no modules on example.net")
  1119  	}
  1120  	if importPath == "rsc.io" {
  1121  		// This special case allows tests like ../../testdata/script/govcs.txt
  1122  		// to avoid making any network calls. The module lookup for a path
  1123  		// like rsc.io/nonexist.svn/foo needs to not make a network call for
  1124  		// a lookup on rsc.io.
  1125  		return nil, fmt.Errorf("rsc.io is not a module")
  1126  	}
  1127  	// A common error is to use https://packagepath because that's what
  1128  	// hg and git require. Diagnose this helpfully.
  1129  	if prefix := httpPrefix(importPath); prefix != "" {
  1130  		// The importPath has been cleaned, so has only one slash. The pattern
  1131  		// ignores the slashes; the error message puts them back on the RHS at least.
  1132  		return nil, fmt.Errorf("%q not allowed in import path", prefix+"//")
  1133  	}
  1134  	for _, srv := range vcsPaths {
  1135  		if !str.HasPathPrefix(importPath, srv.pathPrefix) {
  1136  			continue
  1137  		}
  1138  		m := srv.regexp.FindStringSubmatch(importPath)
  1139  		if m == nil {
  1140  			if srv.pathPrefix != "" {
  1141  				return nil, importErrorf(importPath, "invalid %s import path %q", srv.pathPrefix, importPath)
  1142  			}
  1143  			continue
  1144  		}
  1145  
  1146  		// Build map of named subexpression matches for expand.
  1147  		match := map[string]string{
  1148  			"prefix": srv.pathPrefix + "/",
  1149  			"import": importPath,
  1150  		}
  1151  		for i, name := range srv.regexp.SubexpNames() {
  1152  			if name != "" && match[name] == "" {
  1153  				match[name] = m[i]
  1154  			}
  1155  		}
  1156  		if srv.vcs != "" {
  1157  			match["vcs"] = expand(match, srv.vcs)
  1158  		}
  1159  		if srv.repo != "" {
  1160  			match["repo"] = expand(match, srv.repo)
  1161  		}
  1162  		if srv.check != nil {
  1163  			if err := srv.check(match); err != nil {
  1164  				return nil, err
  1165  			}
  1166  		}
  1167  		vcs := vcsByCmd(match["vcs"])
  1168  		if vcs == nil {
  1169  			return nil, fmt.Errorf("unknown version control system %q", match["vcs"])
  1170  		}
  1171  		if err := checkGOVCS(vcs, match["root"]); err != nil {
  1172  			return nil, err
  1173  		}
  1174  		var repoURL string
  1175  		if !srv.schemelessRepo {
  1176  			repoURL = match["repo"]
  1177  		} else {
  1178  			repo := match["repo"]
  1179  			var ok bool
  1180  			repoURL, ok = interceptVCSTest(repo, vcs, security)
  1181  			if !ok {
  1182  				scheme, err := func() (string, error) {
  1183  					for _, s := range vcs.Scheme {
  1184  						if security == web.SecureOnly && !vcs.isSecureScheme(s) {
  1185  							continue
  1186  						}
  1187  
  1188  						// If we know how to ping URL schemes for this VCS,
  1189  						// check that this repo works.
  1190  						// Otherwise, default to the first scheme
  1191  						// that meets the requested security level.
  1192  						if vcs.PingCmd == "" {
  1193  							return s, nil
  1194  						}
  1195  						if err := vcs.Ping(s, repo); err == nil {
  1196  							return s, nil
  1197  						}
  1198  					}
  1199  					securityFrag := ""
  1200  					if security == web.SecureOnly {
  1201  						securityFrag = "secure "
  1202  					}
  1203  					return "", fmt.Errorf("no %sprotocol found for repository", securityFrag)
  1204  				}()
  1205  				if err != nil {
  1206  					return nil, err
  1207  				}
  1208  				repoURL = scheme + "://" + repo
  1209  			}
  1210  		}
  1211  		rr := &RepoRoot{
  1212  			Repo: repoURL,
  1213  			Root: match["root"],
  1214  			VCS:  vcs,
  1215  		}
  1216  		return rr, nil
  1217  	}
  1218  	return nil, errUnknownSite
  1219  }
  1220  
  1221  func interceptVCSTest(repo string, vcs *Cmd, security web.SecurityMode) (repoURL string, ok bool) {
  1222  	if VCSTestRepoURL == "" {
  1223  		return "", false
  1224  	}
  1225  	if vcs == vcsMod {
  1226  		// Since the "mod" protocol is implemented internally,
  1227  		// requests will be intercepted at a lower level (in cmd/go/internal/web).
  1228  		return "", false
  1229  	}
  1230  
  1231  	if scheme, path, ok := strings.Cut(repo, "://"); ok {
  1232  		if security == web.SecureOnly && !vcs.isSecureScheme(scheme) {
  1233  			return "", false // Let the caller reject the original URL.
  1234  		}
  1235  		repo = path // Remove leading URL scheme if present.
  1236  	}
  1237  	for _, host := range VCSTestHosts {
  1238  		if !str.HasPathPrefix(repo, host) {
  1239  			continue
  1240  		}
  1241  
  1242  		httpURL := VCSTestRepoURL + strings.TrimPrefix(repo, host)
  1243  
  1244  		if vcs == vcsSvn {
  1245  			// Ping the vcweb HTTP server to tell it to initialize the SVN repository
  1246  			// and get the SVN server URL.
  1247  			u, err := urlpkg.Parse(httpURL + "?vcwebsvn=1")
  1248  			if err != nil {
  1249  				panic(fmt.Sprintf("invalid vcs-test repo URL: %v", err))
  1250  			}
  1251  			svnURL, err := web.GetBytes(u)
  1252  			svnURL = bytes.TrimSpace(svnURL)
  1253  			if err == nil && len(svnURL) > 0 {
  1254  				return string(svnURL) + strings.TrimPrefix(repo, host), true
  1255  			}
  1256  
  1257  			// vcs-test doesn't have a svn handler for the given path,
  1258  			// so resolve the repo to HTTPS instead.
  1259  		}
  1260  
  1261  		return httpURL, true
  1262  	}
  1263  	return "", false
  1264  }
  1265  
  1266  // urlForImportPath returns a partially-populated URL for the given Go import path.
  1267  //
  1268  // The URL leaves the Scheme field blank so that web.Get will try any scheme
  1269  // allowed by the selected security mode.
  1270  func urlForImportPath(importPath string) (*urlpkg.URL, error) {
  1271  	slash := strings.Index(importPath, "/")
  1272  	if slash < 0 {
  1273  		slash = len(importPath)
  1274  	}
  1275  	host, path := importPath[:slash], importPath[slash:]
  1276  	if !strings.Contains(host, ".") {
  1277  		return nil, errors.New("import path does not begin with hostname")
  1278  	}
  1279  	if len(path) == 0 {
  1280  		path = "/"
  1281  	}
  1282  	return &urlpkg.URL{Host: host, Path: path, RawQuery: "go-get=1"}, nil
  1283  }
  1284  
  1285  // repoRootForImportDynamic finds a *RepoRoot for a custom domain that's not
  1286  // statically known by repoRootFromVCSPaths.
  1287  //
  1288  // This handles custom import paths like "name.tld/pkg/foo" or just "name.tld".
  1289  func repoRootForImportDynamic(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) {
  1290  	url, err := urlForImportPath(importPath)
  1291  	if err != nil {
  1292  		return nil, err
  1293  	}
  1294  	resp, err := web.Get(security, url)
  1295  	if err != nil {
  1296  		msg := "https fetch: %v"
  1297  		if security == web.Insecure {
  1298  			msg = "http/" + msg
  1299  		}
  1300  		return nil, fmt.Errorf(msg, err)
  1301  	}
  1302  	body := resp.Body
  1303  	defer body.Close()
  1304  	imports, err := parseMetaGoImports(body, mod)
  1305  	if len(imports) == 0 {
  1306  		if respErr := resp.Err(); respErr != nil {
  1307  			// If the server's status was not OK, prefer to report that instead of
  1308  			// an XML parse error.
  1309  			return nil, respErr
  1310  		}
  1311  	}
  1312  	if err != nil {
  1313  		return nil, fmt.Errorf("parsing %s: %v", importPath, err)
  1314  	}
  1315  	// Find the matched meta import.
  1316  	mmi, err := matchGoImport(imports, importPath)
  1317  	if err != nil {
  1318  		if _, ok := err.(ImportMismatchError); !ok {
  1319  			return nil, fmt.Errorf("parse %s: %v", url, err)
  1320  		}
  1321  		return nil, fmt.Errorf("parse %s: no go-import meta tags (%s)", resp.URL, err)
  1322  	}
  1323  	if cfg.BuildV {
  1324  		log.Printf("get %q: found meta tag %#v at %s", importPath, mmi, url)
  1325  	}
  1326  	// If the import was "uni.edu/bob/project", which said the
  1327  	// prefix was "uni.edu" and the RepoRoot was "evilroot.com",
  1328  	// make sure we don't trust Bob and check out evilroot.com to
  1329  	// "uni.edu" yet (possibly overwriting/preempting another
  1330  	// non-evil student). Instead, first verify the root and see
  1331  	// if it matches Bob's claim.
  1332  	if mmi.Prefix != importPath {
  1333  		if cfg.BuildV {
  1334  			log.Printf("get %q: verifying non-authoritative meta tag", importPath)
  1335  		}
  1336  		var imports []metaImport
  1337  		url, imports, err = metaImportsForPrefix(mmi.Prefix, mod, security)
  1338  		if err != nil {
  1339  			return nil, err
  1340  		}
  1341  		metaImport2, err := matchGoImport(imports, importPath)
  1342  		if err != nil || mmi != metaImport2 {
  1343  			return nil, fmt.Errorf("%s and %s disagree about go-import for %s", resp.URL, url, mmi.Prefix)
  1344  		}
  1345  	}
  1346  
  1347  	if err := validateRepoRoot(mmi.RepoRoot); err != nil {
  1348  		return nil, fmt.Errorf("%s: invalid repo root %q: %v", resp.URL, mmi.RepoRoot, err)
  1349  	}
  1350  	var vcs *Cmd
  1351  	if mmi.VCS == "mod" {
  1352  		vcs = vcsMod
  1353  	} else {
  1354  		vcs = vcsByCmd(mmi.VCS)
  1355  		if vcs == nil {
  1356  			return nil, fmt.Errorf("%s: unknown vcs %q", resp.URL, mmi.VCS)
  1357  		}
  1358  	}
  1359  
  1360  	if err := checkGOVCS(vcs, mmi.Prefix); err != nil {
  1361  		return nil, err
  1362  	}
  1363  
  1364  	repoURL, ok := interceptVCSTest(mmi.RepoRoot, vcs, security)
  1365  	if !ok {
  1366  		repoURL = mmi.RepoRoot
  1367  	}
  1368  	rr := &RepoRoot{
  1369  		Repo:     repoURL,
  1370  		Root:     mmi.Prefix,
  1371  		IsCustom: true,
  1372  		VCS:      vcs,
  1373  	}
  1374  	return rr, nil
  1375  }
  1376  
  1377  // validateRepoRoot returns an error if repoRoot does not seem to be
  1378  // a valid URL with scheme.
  1379  func validateRepoRoot(repoRoot string) error {
  1380  	url, err := urlpkg.Parse(repoRoot)
  1381  	if err != nil {
  1382  		return err
  1383  	}
  1384  	if url.Scheme == "" {
  1385  		return errors.New("no scheme")
  1386  	}
  1387  	if url.Scheme == "file" {
  1388  		return errors.New("file scheme disallowed")
  1389  	}
  1390  	return nil
  1391  }
  1392  
  1393  var fetchGroup singleflight.Group
  1394  var (
  1395  	fetchCacheMu sync.Mutex
  1396  	fetchCache   = map[string]fetchResult{} // key is metaImportsForPrefix's importPrefix
  1397  )
  1398  
  1399  // metaImportsForPrefix takes a package's root import path as declared in a <meta> tag
  1400  // and returns its HTML discovery URL and the parsed metaImport lines
  1401  // found on the page.
  1402  //
  1403  // The importPath is of the form "golang.org/x/tools".
  1404  // It is an error if no imports are found.
  1405  // url will still be valid if err != nil.
  1406  // The returned url will be of the form "https://golang.org/x/tools?go-get=1"
  1407  func metaImportsForPrefix(importPrefix string, mod ModuleMode, security web.SecurityMode) (*urlpkg.URL, []metaImport, error) {
  1408  	setCache := func(res fetchResult) (fetchResult, error) {
  1409  		fetchCacheMu.Lock()
  1410  		defer fetchCacheMu.Unlock()
  1411  		fetchCache[importPrefix] = res
  1412  		return res, nil
  1413  	}
  1414  
  1415  	resi, _, _ := fetchGroup.Do(importPrefix, func() (resi any, err error) {
  1416  		fetchCacheMu.Lock()
  1417  		if res, ok := fetchCache[importPrefix]; ok {
  1418  			fetchCacheMu.Unlock()
  1419  			return res, nil
  1420  		}
  1421  		fetchCacheMu.Unlock()
  1422  
  1423  		url, err := urlForImportPath(importPrefix)
  1424  		if err != nil {
  1425  			return setCache(fetchResult{err: err})
  1426  		}
  1427  		resp, err := web.Get(security, url)
  1428  		if err != nil {
  1429  			return setCache(fetchResult{url: url, err: fmt.Errorf("fetching %s: %v", importPrefix, err)})
  1430  		}
  1431  		body := resp.Body
  1432  		defer body.Close()
  1433  		imports, err := parseMetaGoImports(body, mod)
  1434  		if len(imports) == 0 {
  1435  			if respErr := resp.Err(); respErr != nil {
  1436  				// If the server's status was not OK, prefer to report that instead of
  1437  				// an XML parse error.
  1438  				return setCache(fetchResult{url: url, err: respErr})
  1439  			}
  1440  		}
  1441  		if err != nil {
  1442  			return setCache(fetchResult{url: url, err: fmt.Errorf("parsing %s: %v", resp.URL, err)})
  1443  		}
  1444  		if len(imports) == 0 {
  1445  			err = fmt.Errorf("fetching %s: no go-import meta tag found in %s", importPrefix, resp.URL)
  1446  		}
  1447  		return setCache(fetchResult{url: url, imports: imports, err: err})
  1448  	})
  1449  	res := resi.(fetchResult)
  1450  	return res.url, res.imports, res.err
  1451  }
  1452  
  1453  type fetchResult struct {
  1454  	url     *urlpkg.URL
  1455  	imports []metaImport
  1456  	err     error
  1457  }
  1458  
  1459  // metaImport represents the parsed <meta name="go-import"
  1460  // content="prefix vcs reporoot" /> tags from HTML files.
  1461  type metaImport struct {
  1462  	Prefix, VCS, RepoRoot string
  1463  }
  1464  
  1465  // An ImportMismatchError is returned where metaImport/s are present
  1466  // but none match our import path.
  1467  type ImportMismatchError struct {
  1468  	importPath string
  1469  	mismatches []string // the meta imports that were discarded for not matching our importPath
  1470  }
  1471  
  1472  func (m ImportMismatchError) Error() string {
  1473  	formattedStrings := make([]string, len(m.mismatches))
  1474  	for i, pre := range m.mismatches {
  1475  		formattedStrings[i] = fmt.Sprintf("meta tag %s did not match import path %s", pre, m.importPath)
  1476  	}
  1477  	return strings.Join(formattedStrings, ", ")
  1478  }
  1479  
  1480  // matchGoImport returns the metaImport from imports matching importPath.
  1481  // An error is returned if there are multiple matches.
  1482  // An ImportMismatchError is returned if none match.
  1483  func matchGoImport(imports []metaImport, importPath string) (metaImport, error) {
  1484  	match := -1
  1485  
  1486  	errImportMismatch := ImportMismatchError{importPath: importPath}
  1487  	for i, im := range imports {
  1488  		if !str.HasPathPrefix(importPath, im.Prefix) {
  1489  			errImportMismatch.mismatches = append(errImportMismatch.mismatches, im.Prefix)
  1490  			continue
  1491  		}
  1492  
  1493  		if match >= 0 {
  1494  			if imports[match].VCS == "mod" && im.VCS != "mod" {
  1495  				// All the mod entries precede all the non-mod entries.
  1496  				// We have a mod entry and don't care about the rest,
  1497  				// matching or not.
  1498  				break
  1499  			}
  1500  			return metaImport{}, fmt.Errorf("multiple meta tags match import path %q", importPath)
  1501  		}
  1502  		match = i
  1503  	}
  1504  
  1505  	if match == -1 {
  1506  		return metaImport{}, errImportMismatch
  1507  	}
  1508  	return imports[match], nil
  1509  }
  1510  
  1511  // expand rewrites s to replace {k} with match[k] for each key k in match.
  1512  func expand(match map[string]string, s string) string {
  1513  	// We want to replace each match exactly once, and the result of expansion
  1514  	// must not depend on the iteration order through the map.
  1515  	// A strings.Replacer has exactly the properties we're looking for.
  1516  	oldNew := make([]string, 0, 2*len(match))
  1517  	for k, v := range match {
  1518  		oldNew = append(oldNew, "{"+k+"}", v)
  1519  	}
  1520  	return strings.NewReplacer(oldNew...).Replace(s)
  1521  }
  1522  
  1523  // vcsPaths defines the meaning of import paths referring to
  1524  // commonly-used VCS hosting sites (github.com/user/dir)
  1525  // and import paths referring to a fully-qualified importPath
  1526  // containing a VCS type (foo.com/repo.git/dir)
  1527  var vcsPaths = []*vcsPath{
  1528  	// GitHub
  1529  	{
  1530  		pathPrefix: "github.com",
  1531  		regexp:     lazyregexp.New(`^(?P<root>github\.com/[\w.\-]+/[\w.\-]+)(/[\w.\-]+)*$`),
  1532  		vcs:        "git",
  1533  		repo:       "https://{root}",
  1534  		check:      noVCSSuffix,
  1535  	},
  1536  
  1537  	// Bitbucket
  1538  	{
  1539  		pathPrefix: "bitbucket.org",
  1540  		regexp:     lazyregexp.New(`^(?P<root>bitbucket\.org/(?P<bitname>[\w.\-]+/[\w.\-]+))(/[\w.\-]+)*$`),
  1541  		vcs:        "git",
  1542  		repo:       "https://{root}",
  1543  		check:      noVCSSuffix,
  1544  	},
  1545  
  1546  	// IBM DevOps Services (JazzHub)
  1547  	{
  1548  		pathPrefix: "hub.jazz.net/git",
  1549  		regexp:     lazyregexp.New(`^(?P<root>hub\.jazz\.net/git/[a-z0-9]+/[\w.\-]+)(/[\w.\-]+)*$`),
  1550  		vcs:        "git",
  1551  		repo:       "https://{root}",
  1552  		check:      noVCSSuffix,
  1553  	},
  1554  
  1555  	// Git at Apache
  1556  	{
  1557  		pathPrefix: "git.apache.org",
  1558  		regexp:     lazyregexp.New(`^(?P<root>git\.apache\.org/[a-z0-9_.\-]+\.git)(/[\w.\-]+)*$`),
  1559  		vcs:        "git",
  1560  		repo:       "https://{root}",
  1561  	},
  1562  
  1563  	// Git at OpenStack
  1564  	{
  1565  		pathPrefix: "git.openstack.org",
  1566  		regexp:     lazyregexp.New(`^(?P<root>git\.openstack\.org/[\w.\-]+/[\w.\-]+)(\.git)?(/[\w.\-]+)*$`),
  1567  		vcs:        "git",
  1568  		repo:       "https://{root}",
  1569  	},
  1570  
  1571  	// chiselapp.com for fossil
  1572  	{
  1573  		pathPrefix: "chiselapp.com",
  1574  		regexp:     lazyregexp.New(`^(?P<root>chiselapp\.com/user/[A-Za-z0-9]+/repository/[\w.\-]+)$`),
  1575  		vcs:        "fossil",
  1576  		repo:       "https://{root}",
  1577  	},
  1578  
  1579  	// General syntax for any server.
  1580  	// Must be last.
  1581  	{
  1582  		regexp:         lazyregexp.New(`(?P<root>(?P<repo>([a-z0-9.\-]+\.)+[a-z0-9.\-]+(:[0-9]+)?(/~?[\w.\-]+)+?)\.(?P<vcs>bzr|fossil|git|hg|svn))(/~?[\w.\-]+)*$`),
  1583  		schemelessRepo: true,
  1584  	},
  1585  }
  1586  
  1587  // vcsPathsAfterDynamic gives additional vcsPaths entries
  1588  // to try after the dynamic HTML check.
  1589  // This gives those sites a chance to introduce <meta> tags
  1590  // as part of a graceful transition away from the hard-coded logic.
  1591  var vcsPathsAfterDynamic = []*vcsPath{
  1592  	// Launchpad. See golang.org/issue/11436.
  1593  	{
  1594  		pathPrefix: "launchpad.net",
  1595  		regexp:     lazyregexp.New(`^(?P<root>launchpad\.net/((?P<project>[\w.\-]+)(?P<series>/[\w.\-]+)?|~[\w.\-]+/(\+junk|[\w.\-]+)/[\w.\-]+))(/[\w.\-]+)*$`),
  1596  		vcs:        "bzr",
  1597  		repo:       "https://{root}",
  1598  		check:      launchpadVCS,
  1599  	},
  1600  }
  1601  
  1602  // noVCSSuffix checks that the repository name does not
  1603  // end in .foo for any version control system foo.
  1604  // The usual culprit is ".git".
  1605  func noVCSSuffix(match map[string]string) error {
  1606  	repo := match["repo"]
  1607  	for _, vcs := range vcsList {
  1608  		if strings.HasSuffix(repo, "."+vcs.Cmd) {
  1609  			return fmt.Errorf("invalid version control suffix in %s path", match["prefix"])
  1610  		}
  1611  	}
  1612  	return nil
  1613  }
  1614  
  1615  // launchpadVCS solves the ambiguity for "lp.net/project/foo". In this case,
  1616  // "foo" could be a series name registered in Launchpad with its own branch,
  1617  // and it could also be the name of a directory within the main project
  1618  // branch one level up.
  1619  func launchpadVCS(match map[string]string) error {
  1620  	if match["project"] == "" || match["series"] == "" {
  1621  		return nil
  1622  	}
  1623  	url := &urlpkg.URL{
  1624  		Scheme: "https",
  1625  		Host:   "code.launchpad.net",
  1626  		Path:   expand(match, "/{project}{series}/.bzr/branch-format"),
  1627  	}
  1628  	_, err := web.GetBytes(url)
  1629  	if err != nil {
  1630  		match["root"] = expand(match, "launchpad.net/{project}")
  1631  		match["repo"] = expand(match, "https://{root}")
  1632  	}
  1633  	return nil
  1634  }
  1635  
  1636  // importError is a copy of load.importError, made to avoid a dependency cycle
  1637  // on cmd/go/internal/load. It just needs to satisfy load.ImportPathError.
  1638  type importError struct {
  1639  	importPath string
  1640  	err        error
  1641  }
  1642  
  1643  func importErrorf(path, format string, args ...any) error {
  1644  	err := &importError{importPath: path, err: fmt.Errorf(format, args...)}
  1645  	if errStr := err.Error(); !strings.Contains(errStr, path) {
  1646  		panic(fmt.Sprintf("path %q not in error %q", path, errStr))
  1647  	}
  1648  	return err
  1649  }
  1650  
  1651  func (e *importError) Error() string {
  1652  	return e.err.Error()
  1653  }
  1654  
  1655  func (e *importError) Unwrap() error {
  1656  	// Don't return e.err directly, since we're only wrapping an error if %w
  1657  	// was passed to ImportErrorf.
  1658  	return errors.Unwrap(e.err)
  1659  }
  1660  
  1661  func (e *importError) ImportPath() string {
  1662  	return e.importPath
  1663  }
  1664  

View as plain text