| 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/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 |
// 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 |
Scheme []string |
| 44 |
PingCmd string |
| 45 |
|
| 46 |
Status func(v *Cmd, rootDir string) (Status, error) |
| 47 |
} |
| 48 |
|
| 49 |
// Status is the current state of a local repository. |
| 50 |
type Status struct { |
| 51 |
Revision string // Optional. |
| 52 |
CommitTime time.Time // Optional. |
| 53 |
Uncommitted bool // Required. |
| 54 |
} |
| 55 |
|
| 56 |
var ( |
| 57 |
// VCSTestRepoURL is the URL of the HTTP server that serves the repos for |
| 58 |
// vcs-test.golang.org. |
| 59 |
// |
| 60 |
// In tests, this is set to the URL of an httptest.Server hosting a |
| 61 |
// cmd/go/internal/vcweb.Server. |
| 62 |
VCSTestRepoURL string |
| 63 |
|
| 64 |
// VCSTestHosts is the set of hosts supported by the vcs-test server. |
| 65 |
VCSTestHosts []string |
| 66 |
|
| 67 |
// VCSTestIsLocalHost reports whether the given URL refers to a local |
| 68 |
// (loopback) host, such as "localhost" or "127.0.0.1:8080". |
| 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 |
// If repo is not a URL, it's not secure. |
| 84 |
return false |
| 85 |
} |
| 86 |
if VCSTestRepoURL != "" && web.IsLocalHost(u) { |
| 87 |
// If the vcstest server is in use, it may redirect to other local ports for |
| 88 |
// other protocols (such as svn). Assume that all loopback addresses are |
| 89 |
// secure during testing. |
| 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 |
// GIT_ALLOW_PROTOCOL is an environment variable defined by Git. It is a |
| 99 |
// colon-separated list of schemes that are allowed to be used with git |
| 100 |
// fetch/clone. Any scheme not mentioned will be considered insecure. |
| 101 |
if allow := os.Getenv("GIT_ALLOW_PROTOCOL"); allow != "" { |
| 102 |
for _, s := range strings.Split(allow, ":") { |
| 103 |
if s == scheme { |
| 104 |
return true |
| 105 |
} |
| 106 |
} |
| 107 |
return false |
| 108 |
} |
| 109 |
} |
| 110 |
return defaultSecureScheme[scheme] |
| 111 |
} |
| 112 |
|
| 113 |
// A tagCmd describes a command to list available tags |
| 114 |
// that can be passed to tagSyncCmd. |
| 115 |
type tagCmd struct { |
| 116 |
cmd string // command to list tags |
| 117 |
pattern string // regexp to extract tags from list |
| 118 |
} |
| 119 |
|
| 120 |
// vcsList lists the known version control systems |
| 121 |
var vcsList = []*Cmd{ |
| 122 |
vcsHg, |
| 123 |
vcsGit, |
| 124 |
vcsSvn, |
| 125 |
vcsBzr, |
| 126 |
vcsFossil, |
| 127 |
} |
| 128 |
|
| 129 |
// vcsMod is a stub for the "mod" scheme. It's returned by |
| 130 |
// repoRootForImportPathDynamic, but is otherwise not treated as a VCS command. |
| 131 |
var vcsMod = &Cmd{Name: "mod"} |
| 132 |
|
| 133 |
// vcsByCmd returns the version control system for the given |
| 134 |
// command name (hg, git, svn, bzr). |
| 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 |
// vcsHg describes how to use Mercurial. |
| 145 |
var vcsHg = &Cmd{ |
| 146 |
Name: "Mercurial", |
| 147 |
Cmd: "hg", |
| 148 |
|
| 149 |
// HGPLAIN=+strictflags turns off additional output that a user may have |
| 150 |
// enabled via config options or certain extensions. |
| 151 |
Env: []string{"HGPLAIN=+strictflags"}, |
| 152 |
RootNames: []rootName{ |
| 153 |
{filename: ".hg", isDir: true}, |
| 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 |
// Output changeset ID and seconds since epoch. |
| 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 |
// Strip trailing timezone offset. |
| 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 |
// Also look for untracked files. |
| 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 |
// parseRevTime parses commit details in "revision:seconds" format. |
| 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(string(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 |
// vcsGit describes how to use Git. |
| 214 |
var vcsGit = &Cmd{ |
| 215 |
Name: "Git", |
| 216 |
Cmd: "git", |
| 217 |
RootNames: []rootName{ |
| 218 |
{filename: ".git", isDir: true}, |
| 219 |
}, |
| 220 |
|
| 221 |
Scheme: []string{"git", "https", "http", "git+ssh", "ssh"}, |
| 222 |
|
| 223 |
// Leave out the '--' separator in the ls-remote command: git 2.7.4 does not |
| 224 |
// support such a separator for that command, and this use should be safe |
| 225 |
// without it because the {scheme} value comes from the predefined list above. |
| 226 |
// See golang.org/issue/33836. |
| 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 |
// "git status" works for empty repositories, but "git log" does not. |
| 240 |
// Assume there are no commits in the repo when "git log" fails with |
| 241 |
// uncommitted files and skip tagging revision / committime. |
| 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 |
// vcsBzr describes how to use Bazaar. |
| 262 |
var vcsBzr = &Cmd{ |
| 263 |
Name: "Bazaar", |
| 264 |
Cmd: "bzr", |
| 265 |
RootNames: []rootName{ |
| 266 |
{filename: ".bzr", isDir: true}, |
| 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 |
// Expect (non-empty repositories only): |
| 282 |
// |
| 283 |
// revision-id: [email protected] |
| 284 |
// date: 2021-09-21 12:00:00 +1000 |
| 285 |
// ... |
| 286 |
var rev string |
| 287 |
var commitTime time.Time |
| 288 |
|
| 289 |
for _, line := range strings.Split(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 |
// Skip warning when working directory is set to an older revision. |
| 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 |
// vcsSvn describes how to use Subversion. |
| 332 |
var vcsSvn = &Cmd{ |
| 333 |
Name: "Subversion", |
| 334 |
Cmd: "svn", |
| 335 |
RootNames: []rootName{ |
| 336 |
{filename: ".svn", isDir: true}, |
| 337 |
}, |
| 338 |
|
| 339 |
// There is no tag command in subversion. |
| 340 |
// The branch information is all in the path names. |
| 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 |
// fossilRepoName is the name go get associates with a fossil repository. In the |
| 377 |
// real world the file can be named anything. |
| 378 |
const fossilRepoName = ".fossil" |
| 379 |
|
| 380 |
// vcsFossil describes how to use Fossil (fossil-scm.org) |
| 381 |
var vcsFossil = &Cmd{ |
| 382 |
Name: "Fossil", |
| 383 |
Cmd: "fossil", |
| 384 |
RootNames: []rootName{ |
| 385 |
{filename: ".fslckout", isDir: false}, |
| 386 |
{filename: "_FOSSIL_", isDir: false}, |
| 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 |
// Expect: |
| 403 |
// ... |
| 404 |
// checkout: 91ed71f22c77be0c3e250920f47bfd4e1f9024d2 2021-09-21 12:00:00 UTC |
| 405 |
// ... |
| 406 |
|
| 407 |
// Extract revision and commit time. |
| 408 |
// Ensure line ends with UTC (known timezone offset). |
| 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 |
// Also look for untracked changes. |
| 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 |
// run runs the command line cmd in the given directory. |
| 452 |
// keyval is a list of key, value pairs. run expands |
| 453 |
// instances of {key} in cmd into value, but only after |
| 454 |
// splitting cmd into individual arguments. |
| 455 |
// If an error occurs, run prints the command line and the |
| 456 |
// command's combined stdout+stderr to standard error. |
| 457 |
// Otherwise run discards the command's output. |
| 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 |
// runVerboseOnly is like run but only generates error output to standard error in verbose mode. |
| 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 |
// runOutput is like run but returns the output of the command. |
| 470 |
func (v *Cmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) { |
| 471 |
return v.run1(dir, cmd, keyval, true) |
| 472 |
} |
| 473 |
|
| 474 |
// runOutputVerboseOnly is like runOutput but only generates error output to |
| 475 |
// standard error in verbose mode. |
| 476 |
func (v *Cmd) runOutputVerboseOnly(dir string, cmd string, keyval ...string) ([]byte, error) { |
| 477 |
return v.run1(dir, cmd, keyval, false) |
| 478 |
} |
| 479 |
|
| 480 |
// run1 is the generalized implementation of run and runOutput. |
| 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 |
// Ping pings to determine scheme to use. |
| 545 |
func (v *Cmd) Ping(scheme, repo string) error { |
| 546 |
// Run the ping command in an arbitrary working directory, |
| 547 |
// but don't let the current working directory pollute the results. |
| 548 |
// In module mode, we expect GOMODCACHE to exist and be a safe place for |
| 549 |
// commands; in GOPATH mode, we expect that to be true of GOPATH/src. |
| 550 |
dir := cfg.GOMODCACHE |
| 551 |
if !cfg.ModulesEnabled { |
| 552 |
dir = filepath.Join(cfg.BuildContext.GOPATH, "src") |
| 553 |
} |
| 554 |
os.MkdirAll(dir, 0777) // Ignore errors — if unsuccessful, the command will likely fail. |
| 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 |
// A vcsPath describes how to convert an import path into a |
| 566 |
// version control system and repository name. |
| 567 |
type vcsPath struct { |
| 568 |
pathPrefix string // prefix this description applies to |
| 569 |
regexp *lazyregexp.Regexp // compiled pattern for import path |
| 570 |
repo string // repository to use (expand with match of re) |
| 571 |
vcs string // version control system to use (expand with match of re) |
| 572 |
check func(match map[string]string) error // additional checks |
| 573 |
schemelessRepo bool // if true, the repo pattern lacks a scheme |
| 574 |
} |
| 575 |
|
| 576 |
var allowmultiplevcs = godebug.New("allowmultiplevcs") |
| 577 |
|
| 578 |
// FromDir inspects dir and its parents to determine the |
| 579 |
// version control system and code repository to use. |
| 580 |
// If no repository is found, FromDir returns an error |
| 581 |
// equivalent to os.ErrNotExist. |
| 582 |
func FromDir(dir, srcRoot string) (repoDir string, vcsCmd *Cmd, err error) { |
| 583 |
// Clean and double-check that dir is in (a subdirectory of) srcRoot. |
| 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 isVCSRoot(dir, vcs.RootNames) { |
| 596 |
if vcsCmd == nil { |
| 597 |
// Record first VCS we find. |
| 598 |
vcsCmd = vcs |
| 599 |
repoDir = dir |
| 600 |
if allowmultiplevcs.Value() == "1" { |
| 601 |
allowmultiplevcs.IncNonDefault() |
| 602 |
return repoDir, vcsCmd, nil |
| 603 |
} |
| 604 |
// If allowmultiplevcs is not set, keep looking for |
| 605 |
// repositories in current and parent directories and report |
| 606 |
// an error if one is found to mitigate VCS injection |
| 607 |
// attacks. |
| 608 |
continue |
| 609 |
} |
| 610 |
if vcsCmd == vcsGit && vcs == vcsGit { |
| 611 |
// Nested Git is allowed, as this is how things like |
| 612 |
// submodules work. Git explicitly protects against |
| 613 |
// injection against itself. |
| 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 |
// Move to parent. |
| 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 |
// isVCSRoot identifies a VCS root by checking whether the directory contains |
| 635 |
// any of the listed root names. |
| 636 |
func isVCSRoot(dir string, rootNames []rootName) bool { |
| 637 |
for _, root := range rootNames { |
| 638 |
fi, err := os.Stat(filepath.Join(dir, root.filename)) |
| 639 |
if err == nil && fi.IsDir() == root.isDir { |
| 640 |
return true |
| 641 |
} |
| 642 |
} |
| 643 |
|
| 644 |
return false |
| 645 |
} |
| 646 |
|
| 647 |
type rootName struct { |
| 648 |
filename string |
| 649 |
isDir bool |
| 650 |
} |
| 651 |
|
| 652 |
type vcsNotFoundError struct { |
| 653 |
dir string |
| 654 |
} |
| 655 |
|
| 656 |
func (e *vcsNotFoundError) Error() string { |
| 657 |
return fmt.Sprintf("directory %q is not using a known version control system", e.dir) |
| 658 |
} |
| 659 |
|
| 660 |
func (e *vcsNotFoundError) Is(err error) bool { |
| 661 |
return err == os.ErrNotExist |
| 662 |
} |
| 663 |
|
| 664 |
// A govcsRule is a single GOVCS rule like private:hg|svn. |
| 665 |
type govcsRule struct { |
| 666 |
pattern string |
| 667 |
allowed []string |
| 668 |
} |
| 669 |
|
| 670 |
// A govcsConfig is a full GOVCS configuration. |
| 671 |
type govcsConfig []govcsRule |
| 672 |
|
| 673 |
func parseGOVCS(s string) (govcsConfig, error) { |
| 674 |
s = strings.TrimSpace(s) |
| 675 |
if s == "" { |
| 676 |
return nil, nil |
| 677 |
} |
| 678 |
var cfg govcsConfig |
| 679 |
have := make(map[string]string) |
| 680 |
for _, item := range strings.Split(s, ",") { |
| 681 |
item = strings.TrimSpace(item) |
| 682 |
if item == "" { |
| 683 |
return nil, fmt.Errorf("empty entry in GOVCS") |
| 684 |
} |
| 685 |
pattern, list, found := strings.Cut(item, ":") |
| 686 |
if !found { |
| 687 |
return nil, fmt.Errorf("malformed entry in GOVCS (missing colon): %q", item) |
| 688 |
} |
| 689 |
pattern, list = strings.TrimSpace(pattern), strings.TrimSpace(list) |
| 690 |
if pattern == "" { |
| 691 |
return nil, fmt.Errorf("empty pattern in GOVCS: %q", item) |
| 692 |
} |
| 693 |
if list == "" { |
| 694 |
return nil, fmt.Errorf("empty VCS list in GOVCS: %q", item) |
| 695 |
} |
| 696 |
if search.IsRelativePath(pattern) { |
| 697 |
return nil, fmt.Errorf("relative pattern not allowed in GOVCS: %q", pattern) |
| 698 |
} |
| 699 |
if old := have[pattern]; old != "" { |
| 700 |
return nil, fmt.Errorf("unreachable pattern in GOVCS: %q after %q", item, old) |
| 701 |
} |
| 702 |
have[pattern] = item |
| 703 |
allowed := strings.Split(list, "|") |
| 704 |
for i, a := range allowed { |
| 705 |
a = strings.TrimSpace(a) |
| 706 |
if a == "" { |
| 707 |
return nil, fmt.Errorf("empty VCS name in GOVCS: %q", item) |
| 708 |
} |
| 709 |
allowed[i] = a |
| 710 |
} |
| 711 |
cfg = append(cfg, govcsRule{pattern, allowed}) |
| 712 |
} |
| 713 |
return cfg, nil |
| 714 |
} |
| 715 |
|
| 716 |
func (c *govcsConfig) allow(path string, private bool, vcs string) bool { |
| 717 |
for _, rule := range *c { |
| 718 |
match := false |
| 719 |
switch rule.pattern { |
| 720 |
case "private": |
| 721 |
match = private |
| 722 |
case "public": |
| 723 |
match = !private |
| 724 |
default: |
| 725 |
// Note: rule.pattern is known to be comma-free, |
| 726 |
// so MatchPrefixPatterns is only matching a single pattern for us. |
| 727 |
match = module.MatchPrefixPatterns(rule.pattern, path) |
| 728 |
} |
| 729 |
if !match { |
| 730 |
continue |
| 731 |
} |
| 732 |
for _, allow := range rule.allowed { |
| 733 |
if allow == vcs || allow == "all" { |
| 734 |
return true |
| 735 |
} |
| 736 |
} |
| 737 |
return false |
| 738 |
} |
| 739 |
|
| 740 |
// By default, nothing is allowed. |
| 741 |
return false |
| 742 |
} |
| 743 |
|
| 744 |
var ( |
| 745 |
govcs govcsConfig |
| 746 |
govcsErr error |
| 747 |
govcsOnce sync.Once |
| 748 |
) |
| 749 |
|
| 750 |
// defaultGOVCS is the default setting for GOVCS. |
| 751 |
// Setting GOVCS adds entries ahead of these but does not remove them. |
| 752 |
// (They are appended to the parsed GOVCS setting.) |
| 753 |
// |
| 754 |
// The rationale behind allowing only Git and Mercurial is that |
| 755 |
// these two systems have had the most attention to issues |
| 756 |
// of being run as clients of untrusted servers. In contrast, |
| 757 |
// Bazaar, Fossil, and Subversion have primarily been used |
| 758 |
// in trusted, authenticated environments and are not as well |
| 759 |
// scrutinized as attack surfaces. |
| 760 |
// |
| 761 |
// See golang.org/issue/41730 for details. |
| 762 |
var defaultGOVCS = govcsConfig{ |
| 763 |
{"private", []string{"all"}}, |
| 764 |
{"public", []string{"git", "hg"}}, |
| 765 |
} |
| 766 |
|
| 767 |
// checkGOVCS checks whether the policy defined by the environment variable |
| 768 |
// GOVCS allows the given vcs command to be used with the given repository |
| 769 |
// root path. Note that root may not be a real package or module path; it's |
| 770 |
// the same as the root path in the go-import meta tag. |
| 771 |
func checkGOVCS(vcs *Cmd, root string) error { |
| 772 |
if vcs == vcsMod { |
| 773 |
// Direct module (proxy protocol) fetches don't |
| 774 |
// involve an external version control system |
| 775 |
// and are always allowed. |
| 776 |
return nil |
| 777 |
} |
| 778 |
|
| 779 |
govcsOnce.Do(func() { |
| 780 |
govcs, govcsErr = parseGOVCS(os.Getenv("GOVCS")) |
| 781 |
govcs = append(govcs, defaultGOVCS...) |
| 782 |
}) |
| 783 |
if govcsErr != nil { |
| 784 |
return govcsErr |
| 785 |
} |
| 786 |
|
| 787 |
private := module.MatchPrefixPatterns(cfg.GOPRIVATE, root) |
| 788 |
if !govcs.allow(root, private, vcs.Cmd) { |
| 789 |
what := "public" |
| 790 |
if private { |
| 791 |
what = "private" |
| 792 |
} |
| 793 |
return fmt.Errorf("GOVCS disallows using %s for %s %s; see 'go help vcs'", vcs.Cmd, what, root) |
| 794 |
} |
| 795 |
|
| 796 |
return nil |
| 797 |
} |
| 798 |
|
| 799 |
// RepoRoot describes the repository root for a tree of source code. |
| 800 |
type RepoRoot struct { |
| 801 |
Repo string // repository URL, including scheme |
| 802 |
Root string // import path corresponding to the SubDir |
| 803 |
SubDir string // subdirectory within the repo (empty for root) |
| 804 |
IsCustom bool // defined by served <meta> tags (as opposed to hard-coded pattern) |
| 805 |
VCS *Cmd |
| 806 |
} |
| 807 |
|
| 808 |
func httpPrefix(s string) string { |
| 809 |
for _, prefix := range [...]string{"http:", "https:"} { |
| 810 |
if strings.HasPrefix(s, prefix) { |
| 811 |
return prefix |
| 812 |
} |
| 813 |
} |
| 814 |
return "" |
| 815 |
} |
| 816 |
|
| 817 |
// ModuleMode specifies whether to prefer modules when looking up code sources. |
| 818 |
type ModuleMode int |
| 819 |
|
| 820 |
const ( |
| 821 |
IgnoreMod ModuleMode = iota |
| 822 |
PreferMod |
| 823 |
) |
| 824 |
|
| 825 |
// RepoRootForImportPath analyzes importPath to determine the |
| 826 |
// version control system, and code repository to use. |
| 827 |
func RepoRootForImportPath(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) { |
| 828 |
rr, err := repoRootFromVCSPaths(importPath, security, vcsPaths) |
| 829 |
if err == errUnknownSite { |
| 830 |
rr, err = repoRootForImportDynamic(importPath, mod, security) |
| 831 |
if err != nil { |
| 832 |
err = importErrorf(importPath, "unrecognized import path %q: %v", importPath, err) |
| 833 |
} |
| 834 |
} |
| 835 |
if err != nil { |
| 836 |
rr1, err1 := repoRootFromVCSPaths(importPath, security, vcsPathsAfterDynamic) |
| 837 |
if err1 == nil { |
| 838 |
rr = rr1 |
| 839 |
err = nil |
| 840 |
} |
| 841 |
} |
| 842 |
|
| 843 |
// Should have been taken care of above, but make sure. |
| 844 |
if err == nil && strings.Contains(importPath, "...") && strings.Contains(rr.Root, "...") { |
| 845 |
// Do not allow wildcards in the repo root. |
| 846 |
rr = nil |
| 847 |
err = importErrorf(importPath, "cannot expand ... in %q", importPath) |
| 848 |
} |
| 849 |
return rr, err |
| 850 |
} |
| 851 |
|
| 852 |
var errUnknownSite = errors.New("dynamic lookup required to find mapping") |
| 853 |
|
| 854 |
// repoRootFromVCSPaths attempts to map importPath to a repoRoot |
| 855 |
// using the mappings defined in vcsPaths. |
| 856 |
func repoRootFromVCSPaths(importPath string, security web.SecurityMode, vcsPaths []*vcsPath) (*RepoRoot, error) { |
| 857 |
if str.HasPathPrefix(importPath, "example.net") { |
| 858 |
// TODO(rsc): This should not be necessary, but it's required to keep |
| 859 |
// tests like ../../testdata/script/mod_get_extra.txt from using the network. |
| 860 |
// That script has everything it needs in the replacement set, but it is still |
| 861 |
// doing network calls. |
| 862 |
return nil, fmt.Errorf("no modules on example.net") |
| 863 |
} |
| 864 |
if importPath == "rsc.io" { |
| 865 |
// This special case allows tests like ../../testdata/script/govcs.txt |
| 866 |
// to avoid making any network calls. The module lookup for a path |
| 867 |
// like rsc.io/nonexist.svn/foo needs to not make a network call for |
| 868 |
// a lookup on rsc.io. |
| 869 |
return nil, fmt.Errorf("rsc.io is not a module") |
| 870 |
} |
| 871 |
// A common error is to use https://packagepath because that's what |
| 872 |
// hg and git require. Diagnose this helpfully. |
| 873 |
if prefix := httpPrefix(importPath); prefix != "" { |
| 874 |
// The importPath has been cleaned, so has only one slash. The pattern |
| 875 |
// ignores the slashes; the error message puts them back on the RHS at least. |
| 876 |
return nil, fmt.Errorf("%q not allowed in import path", prefix+"//") |
| 877 |
} |
| 878 |
for _, srv := range vcsPaths { |
| 879 |
if !str.HasPathPrefix(importPath, srv.pathPrefix) { |
| 880 |
continue |
| 881 |
} |
| 882 |
m := srv.regexp.FindStringSubmatch(importPath) |
| 883 |
if m == nil { |
| 884 |
if srv.pathPrefix != "" { |
| 885 |
return nil, importErrorf(importPath, "invalid %s import path %q", srv.pathPrefix, importPath) |
| 886 |
} |
| 887 |
continue |
| 888 |
} |
| 889 |
|
| 890 |
// Build map of named subexpression matches for expand. |
| 891 |
match := map[string]string{ |
| 892 |
"prefix": srv.pathPrefix + "/", |
| 893 |
"import": importPath, |
| 894 |
} |
| 895 |
for i, name := range srv.regexp.SubexpNames() { |
| 896 |
if name != "" && match[name] == "" { |
| 897 |
match[name] = m[i] |
| 898 |
} |
| 899 |
} |
| 900 |
if srv.vcs != "" { |
| 901 |
match["vcs"] = expand(match, srv.vcs) |
| 902 |
} |
| 903 |
if srv.repo != "" { |
| 904 |
match["repo"] = expand(match, srv.repo) |
| 905 |
} |
| 906 |
if srv.check != nil { |
| 907 |
if err := srv.check(match); err != nil { |
| 908 |
return nil, err |
| 909 |
} |
| 910 |
} |
| 911 |
vcs := vcsByCmd(match["vcs"]) |
| 912 |
if vcs == nil { |
| 913 |
return nil, fmt.Errorf("unknown version control system %q", match["vcs"]) |
| 914 |
} |
| 915 |
if err := checkGOVCS(vcs, match["root"]); err != nil { |
| 916 |
return nil, err |
| 917 |
} |
| 918 |
var repoURL string |
| 919 |
if !srv.schemelessRepo { |
| 920 |
repoURL = match["repo"] |
| 921 |
} else { |
| 922 |
repo := match["repo"] |
| 923 |
var ok bool |
| 924 |
repoURL, ok = interceptVCSTest(repo, vcs, security) |
| 925 |
if !ok { |
| 926 |
scheme, err := func() (string, error) { |
| 927 |
for _, s := range vcs.Scheme { |
| 928 |
if security == web.SecureOnly && !vcs.isSecureScheme(s) { |
| 929 |
continue |
| 930 |
} |
| 931 |
|
| 932 |
// If we know how to ping URL schemes for this VCS, |
| 933 |
// check that this repo works. |
| 934 |
// Otherwise, default to the first scheme |
| 935 |
// that meets the requested security level. |
| 936 |
if vcs.PingCmd == "" { |
| 937 |
return s, nil |
| 938 |
} |
| 939 |
if err := vcs.Ping(s, repo); err == nil { |
| 940 |
return s, nil |
| 941 |
} |
| 942 |
} |
| 943 |
securityFrag := "" |
| 944 |
if security == web.SecureOnly { |
| 945 |
securityFrag = "secure " |
| 946 |
} |
| 947 |
return "", fmt.Errorf("no %sprotocol found for repository", securityFrag) |
| 948 |
}() |
| 949 |
if err != nil { |
| 950 |
return nil, err |
| 951 |
} |
| 952 |
repoURL = scheme + "://" + repo |
| 953 |
} |
| 954 |
} |
| 955 |
rr := &RepoRoot{ |
| 956 |
Repo: repoURL, |
| 957 |
Root: match["root"], |
| 958 |
VCS: vcs, |
| 959 |
} |
| 960 |
return rr, nil |
| 961 |
} |
| 962 |
return nil, errUnknownSite |
| 963 |
} |
| 964 |
|
| 965 |
func interceptVCSTest(repo string, vcs *Cmd, security web.SecurityMode) (repoURL string, ok bool) { |
| 966 |
if VCSTestRepoURL == "" { |
| 967 |
return "", false |
| 968 |
} |
| 969 |
if vcs == vcsMod { |
| 970 |
// Since the "mod" protocol is implemented internally, |
| 971 |
// requests will be intercepted at a lower level (in cmd/go/internal/web). |
| 972 |
return "", false |
| 973 |
} |
| 974 |
|
| 975 |
if scheme, path, ok := strings.Cut(repo, "://"); ok { |
| 976 |
if security == web.SecureOnly && !vcs.isSecureScheme(scheme) { |
| 977 |
return "", false // Let the caller reject the original URL. |
| 978 |
} |
| 979 |
repo = path // Remove leading URL scheme if present. |
| 980 |
} |
| 981 |
for _, host := range VCSTestHosts { |
| 982 |
if !str.HasPathPrefix(repo, host) { |
| 983 |
continue |
| 984 |
} |
| 985 |
|
| 986 |
httpURL := VCSTestRepoURL + strings.TrimPrefix(repo, host) |
| 987 |
|
| 988 |
if vcs == vcsSvn { |
| 989 |
// Ping the vcweb HTTP server to tell it to initialize the SVN repository |
| 990 |
// and get the SVN server URL. |
| 991 |
u, err := urlpkg.Parse(httpURL + "?vcwebsvn=1") |
| 992 |
if err != nil { |
| 993 |
panic(fmt.Sprintf("invalid vcs-test repo URL: %v", err)) |
| 994 |
} |
| 995 |
svnURL, err := web.GetBytes(u) |
| 996 |
svnURL = bytes.TrimSpace(svnURL) |
| 997 |
if err == nil && len(svnURL) > 0 { |
| 998 |
return string(svnURL) + strings.TrimPrefix(repo, host), true |
| 999 |
} |
| 1000 |
|
| 1001 |
// vcs-test doesn't have a svn handler for the given path, |
| 1002 |
// so resolve the repo to HTTPS instead. |
| 1003 |
} |
| 1004 |
|
| 1005 |
return httpURL, true |
| 1006 |
} |
| 1007 |
return "", false |
| 1008 |
} |
| 1009 |
|
| 1010 |
// urlForImportPath returns a partially-populated URL for the given Go import path. |
| 1011 |
// |
| 1012 |
// The URL leaves the Scheme field blank so that web.Get will try any scheme |
| 1013 |
// allowed by the selected security mode. |
| 1014 |
func urlForImportPath(importPath string) (*urlpkg.URL, error) { |
| 1015 |
slash := strings.Index(importPath, "/") |
| 1016 |
if slash < 0 { |
| 1017 |
slash = len(importPath) |
| 1018 |
} |
| 1019 |
host, path := importPath[:slash], importPath[slash:] |
| 1020 |
if !strings.Contains(host, ".") { |
| 1021 |
return nil, errors.New("import path does not begin with hostname") |
| 1022 |
} |
| 1023 |
if len(path) == 0 { |
| 1024 |
path = "/" |
| 1025 |
} |
| 1026 |
return &urlpkg.URL{Host: host, Path: path, RawQuery: "go-get=1"}, nil |
| 1027 |
} |
| 1028 |
|
| 1029 |
// repoRootForImportDynamic finds a *RepoRoot for a custom domain that's not |
| 1030 |
// statically known by repoRootFromVCSPaths. |
| 1031 |
// |
| 1032 |
// This handles custom import paths like "name.tld/pkg/foo" or just "name.tld". |
| 1033 |
func repoRootForImportDynamic(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) { |
| 1034 |
url, err := urlForImportPath(importPath) |
| 1035 |
if err != nil { |
| 1036 |
return nil, err |
| 1037 |
} |
| 1038 |
resp, err := web.Get(security, url) |
| 1039 |
if err != nil { |
| 1040 |
msg := "https fetch: %v" |
| 1041 |
if security == web.Insecure { |
| 1042 |
msg = "http/" + msg |
| 1043 |
} |
| 1044 |
return nil, fmt.Errorf(msg, err) |
| 1045 |
} |
| 1046 |
body := resp.Body |
| 1047 |
defer body.Close() |
| 1048 |
imports, err := parseMetaGoImports(body, mod) |
| 1049 |
if len(imports) == 0 { |
| 1050 |
if respErr := resp.Err(); respErr != nil { |
| 1051 |
// If the server's status was not OK, prefer to report that instead of |
| 1052 |
// an XML parse error. |
| 1053 |
return nil, respErr |
| 1054 |
} |
| 1055 |
} |
| 1056 |
if err != nil { |
| 1057 |
return nil, fmt.Errorf("parsing %s: %v", importPath, err) |
| 1058 |
} |
| 1059 |
// Find the matched meta import. |
| 1060 |
mmi, err := matchGoImport(imports, importPath) |
| 1061 |
if err != nil { |
| 1062 |
if _, ok := err.(ImportMismatchError); !ok { |
| 1063 |
return nil, fmt.Errorf("parse %s: %v", url, err) |
| 1064 |
} |
| 1065 |
return nil, fmt.Errorf("parse %s: no go-import meta tags (%s)", resp.URL, err) |
| 1066 |
} |
| 1067 |
if cfg.BuildV { |
| 1068 |
log.Printf("get %q: found meta tag %#v at %s", importPath, mmi, url) |
| 1069 |
} |
| 1070 |
// If the import was "uni.edu/bob/project", which said the |
| 1071 |
// prefix was "uni.edu" and the RepoRoot was "evilroot.com", |
| 1072 |
// make sure we don't trust Bob and check out evilroot.com to |
| 1073 |
// "uni.edu" yet (possibly overwriting/preempting another |
| 1074 |
// non-evil student). Instead, first verify the root and see |
| 1075 |
// if it matches Bob's claim. |
| 1076 |
if mmi.Prefix != importPath { |
| 1077 |
if cfg.BuildV { |
| 1078 |
log.Printf("get %q: verifying non-authoritative meta tag", importPath) |
| 1079 |
} |
| 1080 |
var imports []metaImport |
| 1081 |
url, imports, err = metaImportsForPrefix(mmi.Prefix, mod, security) |
| 1082 |
if err != nil { |
| 1083 |
return nil, err |
| 1084 |
} |
| 1085 |
metaImport2, err := matchGoImport(imports, importPath) |
| 1086 |
if err != nil || mmi != metaImport2 { |
| 1087 |
return nil, fmt.Errorf("%s and %s disagree about go-import for %s", resp.URL, url, mmi.Prefix) |
| 1088 |
} |
| 1089 |
} |
| 1090 |
|
| 1091 |
if err := validateRepoSubDir(mmi.SubDir); err != nil { |
| 1092 |
return nil, fmt.Errorf("%s: invalid subdirectory %q: %v", resp.URL, mmi.SubDir, err) |
| 1093 |
} |
| 1094 |
|
| 1095 |
if err := validateRepoRoot(mmi.RepoRoot); err != nil { |
| 1096 |
return nil, fmt.Errorf("%s: invalid repo root %q: %v", resp.URL, mmi.RepoRoot, err) |
| 1097 |
} |
| 1098 |
var vcs *Cmd |
| 1099 |
if mmi.VCS == "mod" { |
| 1100 |
vcs = vcsMod |
| 1101 |
} else { |
| 1102 |
vcs = vcsByCmd(mmi.VCS) |
| 1103 |
if vcs == nil { |
| 1104 |
return nil, fmt.Errorf("%s: unknown vcs %q", resp.URL, mmi.VCS) |
| 1105 |
} |
| 1106 |
} |
| 1107 |
|
| 1108 |
if err := checkGOVCS(vcs, mmi.Prefix); err != nil { |
| 1109 |
return nil, err |
| 1110 |
} |
| 1111 |
|
| 1112 |
repoURL, ok := interceptVCSTest(mmi.RepoRoot, vcs, security) |
| 1113 |
if !ok { |
| 1114 |
repoURL = mmi.RepoRoot |
| 1115 |
} |
| 1116 |
rr := &RepoRoot{ |
| 1117 |
Repo: repoURL, |
| 1118 |
Root: mmi.Prefix, |
| 1119 |
SubDir: mmi.SubDir, |
| 1120 |
IsCustom: true, |
| 1121 |
VCS: vcs, |
| 1122 |
} |
| 1123 |
return rr, nil |
| 1124 |
} |
| 1125 |
|
| 1126 |
// validateRepoSubDir returns an error if subdir is not a valid subdirectory path. |
| 1127 |
// We consider a subdirectory path to be valid as long as it doesn't have a leading |
| 1128 |
// slash (/) or hyphen (-). |
| 1129 |
func validateRepoSubDir(subdir string) error { |
| 1130 |
if subdir == "" { |
| 1131 |
return nil |
| 1132 |
} |
| 1133 |
if subdir[0] == '/' { |
| 1134 |
return errors.New("leading slash") |
| 1135 |
} |
| 1136 |
if subdir[0] == '-' { |
| 1137 |
return errors.New("leading hyphen") |
| 1138 |
} |
| 1139 |
return nil |
| 1140 |
} |
| 1141 |
|
| 1142 |
// validateRepoRoot returns an error if repoRoot does not seem to be |
| 1143 |
// a valid URL with scheme. |
| 1144 |
func validateRepoRoot(repoRoot string) error { |
| 1145 |
url, err := urlpkg.Parse(repoRoot) |
| 1146 |
if err != nil { |
| 1147 |
return err |
| 1148 |
} |
| 1149 |
if url.Scheme == "" { |
| 1150 |
return errors.New("no scheme") |
| 1151 |
} |
| 1152 |
if url.Scheme == "file" { |
| 1153 |
return errors.New("file scheme disallowed") |
| 1154 |
} |
| 1155 |
return nil |
| 1156 |
} |
| 1157 |
|
| 1158 |
var fetchGroup singleflight.Group |
| 1159 |
var ( |
| 1160 |
fetchCacheMu sync.Mutex |
| 1161 |
fetchCache = map[string]fetchResult{} // key is metaImportsForPrefix's importPrefix |
| 1162 |
) |
| 1163 |
|
| 1164 |
// metaImportsForPrefix takes a package's root import path as declared in a <meta> tag |
| 1165 |
// and returns its HTML discovery URL and the parsed metaImport lines |
| 1166 |
// found on the page. |
| 1167 |
// |
| 1168 |
// The importPath is of the form "golang.org/x/tools". |
| 1169 |
// It is an error if no imports are found. |
| 1170 |
// url will still be valid if err != nil. |
| 1171 |
// The returned url will be of the form "https://golang.org/x/tools?go-get=1" |
| 1172 |
func metaImportsForPrefix(importPrefix string, mod ModuleMode, security web.SecurityMode) (*urlpkg.URL, []metaImport, error) { |
| 1173 |
setCache := func(res fetchResult) (fetchResult, error) { |
| 1174 |
fetchCacheMu.Lock() |
| 1175 |
defer fetchCacheMu.Unlock() |
| 1176 |
fetchCache[importPrefix] = res |
| 1177 |
return res, nil |
| 1178 |
} |
| 1179 |
|
| 1180 |
resi, _, _ := fetchGroup.Do(importPrefix, func() (resi any, err error) { |
| 1181 |
fetchCacheMu.Lock() |
| 1182 |
if res, ok := fetchCache[importPrefix]; ok { |
| 1183 |
fetchCacheMu.Unlock() |
| 1184 |
return res, nil |
| 1185 |
} |
| 1186 |
fetchCacheMu.Unlock() |
| 1187 |
|
| 1188 |
url, err := urlForImportPath(importPrefix) |
| 1189 |
if err != nil { |
| 1190 |
return setCache(fetchResult{err: err}) |
| 1191 |
} |
| 1192 |
resp, err := web.Get(security, url) |
| 1193 |
if err != nil { |
| 1194 |
return setCache(fetchResult{url: url, err: fmt.Errorf("fetching %s: %v", importPrefix, err)}) |
| 1195 |
} |
| 1196 |
body := resp.Body |
| 1197 |
defer body.Close() |
| 1198 |
imports, err := parseMetaGoImports(body, mod) |
| 1199 |
if len(imports) == 0 { |
| 1200 |
if respErr := resp.Err(); respErr != nil { |
| 1201 |
// If the server's status was not OK, prefer to report that instead of |
| 1202 |
// an XML parse error. |
| 1203 |
return setCache(fetchResult{url: url, err: respErr}) |
| 1204 |
} |
| 1205 |
} |
| 1206 |
if err != nil { |
| 1207 |
return setCache(fetchResult{url: url, err: fmt.Errorf("parsing %s: %v", resp.URL, err)}) |
| 1208 |
} |
| 1209 |
if len(imports) == 0 { |
| 1210 |
err = fmt.Errorf("fetching %s: no go-import meta tag found in %s", importPrefix, resp.URL) |
| 1211 |
} |
| 1212 |
return setCache(fetchResult{url: url, imports: imports, err: err}) |
| 1213 |
}) |
| 1214 |
res := resi.(fetchResult) |
| 1215 |
return res.url, res.imports, res.err |
| 1216 |
} |
| 1217 |
|
| 1218 |
type fetchResult struct { |
| 1219 |
url *urlpkg.URL |
| 1220 |
imports []metaImport |
| 1221 |
err error |
| 1222 |
} |
| 1223 |
|
| 1224 |
// metaImport represents the parsed <meta name="go-import" |
| 1225 |
// content="prefix vcs reporoot subdir" /> tags from HTML files. |
| 1226 |
type metaImport struct { |
| 1227 |
Prefix, VCS, RepoRoot, SubDir string |
| 1228 |
} |
| 1229 |
|
| 1230 |
// An ImportMismatchError is returned where metaImport/s are present |
| 1231 |
// but none match our import path. |
| 1232 |
type ImportMismatchError struct { |
| 1233 |
importPath string |
| 1234 |
mismatches []string // the meta imports that were discarded for not matching our importPath |
| 1235 |
} |
| 1236 |
|
| 1237 |
func (m ImportMismatchError) Error() string { |
| 1238 |
formattedStrings := make([]string, len(m.mismatches)) |
| 1239 |
for i, pre := range m.mismatches { |
| 1240 |
formattedStrings[i] = fmt.Sprintf("meta tag %s did not match import path %s", pre, m.importPath) |
| 1241 |
} |
| 1242 |
return strings.Join(formattedStrings, ", ") |
| 1243 |
} |
| 1244 |
|
| 1245 |
// matchGoImport returns the metaImport from imports matching importPath. |
| 1246 |
// An error is returned if there are multiple matches. |
| 1247 |
// An ImportMismatchError is returned if none match. |
| 1248 |
func matchGoImport(imports []metaImport, importPath string) (metaImport, error) { |
| 1249 |
match := -1 |
| 1250 |
|
| 1251 |
errImportMismatch := ImportMismatchError{importPath: importPath} |
| 1252 |
for i, im := range imports { |
| 1253 |
if !str.HasPathPrefix(importPath, im.Prefix) { |
| 1254 |
errImportMismatch.mismatches = append(errImportMismatch.mismatches, im.Prefix) |
| 1255 |
continue |
| 1256 |
} |
| 1257 |
|
| 1258 |
if match >= 0 { |
| 1259 |
if imports[match].VCS == "mod" && im.VCS != "mod" { |
| 1260 |
// All the mod entries precede all the non-mod entries. |
| 1261 |
// We have a mod entry and don't care about the rest, |
| 1262 |
// matching or not. |
| 1263 |
break |
| 1264 |
} |
| 1265 |
return metaImport{}, fmt.Errorf("multiple meta tags match import path %q", importPath) |
| 1266 |
} |
| 1267 |
match = i |
| 1268 |
} |
| 1269 |
|
| 1270 |
if match == -1 { |
| 1271 |
return metaImport{}, errImportMismatch |
| 1272 |
} |
| 1273 |
return imports[match], nil |
| 1274 |
} |
| 1275 |
|
| 1276 |
// expand rewrites s to replace {k} with match[k] for each key k in match. |
| 1277 |
func expand(match map[string]string, s string) string { |
| 1278 |
// We want to replace each match exactly once, and the result of expansion |
| 1279 |
// must not depend on the iteration order through the map. |
| 1280 |
// A strings.Replacer has exactly the properties we're looking for. |
| 1281 |
oldNew := make([]string, 0, 2*len(match)) |
| 1282 |
for k, v := range match { |
| 1283 |
oldNew = append(oldNew, "{"+k+"}", v) |
| 1284 |
} |
| 1285 |
return strings.NewReplacer(oldNew...).Replace(s) |
| 1286 |
} |
| 1287 |
|
| 1288 |
// vcsPaths defines the meaning of import paths referring to |
| 1289 |
// commonly-used VCS hosting sites (github.com/user/dir) |
| 1290 |
// and import paths referring to a fully-qualified importPath |
| 1291 |
// containing a VCS type (foo.com/repo.git/dir) |
| 1292 |
var vcsPaths = []*vcsPath{ |
| 1293 |
// GitHub |
| 1294 |
{ |
| 1295 |
pathPrefix: "github.com", |
| 1296 |
regexp: lazyregexp.New(`^(?P<root>github\.com/[\w.\-]+/[\w.\-]+)(/[\w.\-]+)*$`), |
| 1297 |
vcs: "git", |
| 1298 |
repo: "https://{root}", |
| 1299 |
check: noVCSSuffix, |
| 1300 |
}, |
| 1301 |
|
| 1302 |
// Bitbucket |
| 1303 |
{ |
| 1304 |
pathPrefix: "bitbucket.org", |
| 1305 |
regexp: lazyregexp.New(`^(?P<root>bitbucket\.org/(?P<bitname>[\w.\-]+/[\w.\-]+))(/[\w.\-]+)*$`), |
| 1306 |
vcs: "git", |
| 1307 |
repo: "https://{root}", |
| 1308 |
check: noVCSSuffix, |
| 1309 |
}, |
| 1310 |
|
| 1311 |
// IBM DevOps Services (JazzHub) |
| 1312 |
{ |
| 1313 |
pathPrefix: "hub.jazz.net/git", |
| 1314 |
regexp: lazyregexp.New(`^(?P<root>hub\.jazz\.net/git/[a-z0-9]+/[\w.\-]+)(/[\w.\-]+)*$`), |
| 1315 |
vcs: "git", |
| 1316 |
repo: "https://{root}", |
| 1317 |
check: noVCSSuffix, |
| 1318 |
}, |
| 1319 |
|
| 1320 |
// Git at Apache |
| 1321 |
{ |
| 1322 |
pathPrefix: "git.apache.org", |
| 1323 |
regexp: lazyregexp.New(`^(?P<root>git\.apache\.org/[a-z0-9_.\-]+\.git)(/[\w.\-]+)*$`), |
| 1324 |
vcs: "git", |
| 1325 |
repo: "https://{root}", |
| 1326 |
}, |
| 1327 |
|
| 1328 |
// Git at OpenStack |
| 1329 |
{ |
| 1330 |
pathPrefix: "git.openstack.org", |
| 1331 |
regexp: lazyregexp.New(`^(?P<root>git\.openstack\.org/[\w.\-]+/[\w.\-]+)(\.git)?(/[\w.\-]+)*$`), |
| 1332 |
vcs: "git", |
| 1333 |
repo: "https://{root}", |
| 1334 |
}, |
| 1335 |
|
| 1336 |
// chiselapp.com for fossil |
| 1337 |
{ |
| 1338 |
pathPrefix: "chiselapp.com", |
| 1339 |
regexp: lazyregexp.New(`^(?P<root>chiselapp\.com/user/[A-Za-z0-9]+/repository/[\w.\-]+)$`), |
| 1340 |
vcs: "fossil", |
| 1341 |
repo: "https://{root}", |
| 1342 |
}, |
| 1343 |
|
| 1344 |
// General syntax for any server. |
| 1345 |
// Must be last. |
| 1346 |
{ |
| 1347 |
regexp: lazyregexp.New(`(?P<root>(?P<repo>([a-z0-9.\-]+\.)+[a-z0-9.\-]+(:[0-9]+)?(/~?[\w.\-]+)+?)\.(?P<vcs>bzr|fossil|git|hg|svn))(/~?[\w.\-]+)*$`), |
| 1348 |
schemelessRepo: true, |
| 1349 |
}, |
| 1350 |
} |
| 1351 |
|
| 1352 |
// vcsPathsAfterDynamic gives additional vcsPaths entries |
| 1353 |
// to try after the dynamic HTML check. |
| 1354 |
// This gives those sites a chance to introduce <meta> tags |
| 1355 |
// as part of a graceful transition away from the hard-coded logic. |
| 1356 |
var vcsPathsAfterDynamic = []*vcsPath{ |
| 1357 |
// Launchpad. See golang.org/issue/11436. |
| 1358 |
{ |
| 1359 |
pathPrefix: "launchpad.net", |
| 1360 |
regexp: lazyregexp.New(`^(?P<root>launchpad\.net/((?P<project>[\w.\-]+)(?P<series>/[\w.\-]+)?|~[\w.\-]+/(\+junk|[\w.\-]+)/[\w.\-]+))(/[\w.\-]+)*$`), |
| 1361 |
vcs: "bzr", |
| 1362 |
repo: "https://{root}", |
| 1363 |
check: launchpadVCS, |
| 1364 |
}, |
| 1365 |
} |
| 1366 |
|
| 1367 |
// noVCSSuffix checks that the repository name does not |
| 1368 |
// end in .foo for any version control system foo. |
| 1369 |
// The usual culprit is ".git". |
| 1370 |
func noVCSSuffix(match map[string]string) error { |
| 1371 |
repo := match["repo"] |
| 1372 |
for _, vcs := range vcsList { |
| 1373 |
if strings.HasSuffix(repo, "."+vcs.Cmd) { |
| 1374 |
return fmt.Errorf("invalid version control suffix in %s path", match["prefix"]) |
| 1375 |
} |
| 1376 |
} |
| 1377 |
return nil |
| 1378 |
} |
| 1379 |
|
| 1380 |
// launchpadVCS solves the ambiguity for "lp.net/project/foo". In this case, |
| 1381 |
// "foo" could be a series name registered in Launchpad with its own branch, |
| 1382 |
// and it could also be the name of a directory within the main project |
| 1383 |
// branch one level up. |
| 1384 |
func launchpadVCS(match map[string]string) error { |
| 1385 |
if match["project"] == "" || match["series"] == "" { |
| 1386 |
return nil |
| 1387 |
} |
| 1388 |
url := &urlpkg.URL{ |
| 1389 |
Scheme: "https", |
| 1390 |
Host: "code.launchpad.net", |
| 1391 |
Path: expand(match, "/{project}{series}/.bzr/branch-format"), |
| 1392 |
} |
| 1393 |
_, err := web.GetBytes(url) |
| 1394 |
if err != nil { |
| 1395 |
match["root"] = expand(match, "launchpad.net/{project}") |
| 1396 |
match["repo"] = expand(match, "https://{root}") |
| 1397 |
} |
| 1398 |
return nil |
| 1399 |
} |
| 1400 |
|
| 1401 |
// importError is a copy of load.importError, made to avoid a dependency cycle |
| 1402 |
// on cmd/go/internal/load. It just needs to satisfy load.ImportPathError. |
| 1403 |
type importError struct { |
| 1404 |
importPath string |
| 1405 |
err error |
| 1406 |
} |
| 1407 |
|
| 1408 |
func importErrorf(path, format string, args ...any) error { |
| 1409 |
err := &importError{importPath: path, err: fmt.Errorf(format, args...)} |
| 1410 |
if errStr := err.Error(); !strings.Contains(errStr, path) { |
| 1411 |
panic(fmt.Sprintf("path %q not in error %q", path, errStr)) |
| 1412 |
} |
| 1413 |
return err |
| 1414 |
} |
| 1415 |
|
| 1416 |
func (e *importError) Error() string { |
| 1417 |
return e.err.Error() |
| 1418 |
} |
| 1419 |
|
| 1420 |
func (e *importError) Unwrap() error { |
| 1421 |
// Don't return e.err directly, since we're only wrapping an error if %w |
| 1422 |
// was passed to ImportErrorf. |
| 1423 |
return errors.Unwrap(e.err) |
| 1424 |
} |
| 1425 |
|
| 1426 |
func (e *importError) ImportPath() string { |
| 1427 |
return e.importPath |
| 1428 |
} |