code.gitea.io/gitea@v1.22.3/modules/git/command.go (about)

     1  // Copyright 2015 The Gogs Authors. All rights reserved.
     2  // Copyright 2016 The Gitea Authors. All rights reserved.
     3  // SPDX-License-Identifier: MIT
     4  
     5  package git
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"errors"
    11  	"fmt"
    12  	"io"
    13  	"os"
    14  	"os/exec"
    15  	"runtime"
    16  	"strings"
    17  	"time"
    18  
    19  	"code.gitea.io/gitea/modules/git/internal" //nolint:depguard // only this file can use the internal type CmdArg, other files and packages should use AddXxx functions
    20  	"code.gitea.io/gitea/modules/log"
    21  	"code.gitea.io/gitea/modules/process"
    22  	"code.gitea.io/gitea/modules/util"
    23  )
    24  
    25  // TrustedCmdArgs returns the trusted arguments for git command.
    26  // It's mainly for passing user-provided and trusted arguments to git command
    27  // In most cases, it shouldn't be used. Use AddXxx function instead
    28  type TrustedCmdArgs []internal.CmdArg
    29  
    30  var (
    31  	// globalCommandArgs global command args for external package setting
    32  	globalCommandArgs TrustedCmdArgs
    33  
    34  	// defaultCommandExecutionTimeout default command execution timeout duration
    35  	defaultCommandExecutionTimeout = 360 * time.Second
    36  )
    37  
    38  // DefaultLocale is the default LC_ALL to run git commands in.
    39  const DefaultLocale = "C"
    40  
    41  // Command represents a command with its subcommands or arguments.
    42  type Command struct {
    43  	prog             string
    44  	args             []string
    45  	parentContext    context.Context
    46  	desc             string
    47  	globalArgsLength int
    48  	brokenArgs       []string
    49  }
    50  
    51  func (c *Command) String() string {
    52  	return c.toString(false)
    53  }
    54  
    55  func (c *Command) toString(sanitizing bool) string {
    56  	// WARNING: this function is for debugging purposes only. It's much better than old code (which only joins args with space),
    57  	// It's impossible to make a simple and 100% correct implementation of argument quoting for different platforms.
    58  	debugQuote := func(s string) string {
    59  		if strings.ContainsAny(s, " `'\"\t\r\n") {
    60  			return fmt.Sprintf("%q", s)
    61  		}
    62  		return s
    63  	}
    64  	a := make([]string, 0, len(c.args)+1)
    65  	a = append(a, debugQuote(c.prog))
    66  	for _, arg := range c.args {
    67  		if sanitizing && (strings.Contains(arg, "://") && strings.Contains(arg, "@")) {
    68  			a = append(a, debugQuote(util.SanitizeCredentialURLs(arg)))
    69  		} else {
    70  			a = append(a, debugQuote(arg))
    71  		}
    72  	}
    73  	return strings.Join(a, " ")
    74  }
    75  
    76  // NewCommand creates and returns a new Git Command based on given command and arguments.
    77  // Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead.
    78  func NewCommand(ctx context.Context, args ...internal.CmdArg) *Command {
    79  	// Make an explicit copy of globalCommandArgs, otherwise append might overwrite it
    80  	cargs := make([]string, 0, len(globalCommandArgs)+len(args))
    81  	for _, arg := range globalCommandArgs {
    82  		cargs = append(cargs, string(arg))
    83  	}
    84  	for _, arg := range args {
    85  		cargs = append(cargs, string(arg))
    86  	}
    87  	return &Command{
    88  		prog:             GitExecutable,
    89  		args:             cargs,
    90  		parentContext:    ctx,
    91  		globalArgsLength: len(globalCommandArgs),
    92  	}
    93  }
    94  
    95  // NewCommandContextNoGlobals creates and returns a new Git Command based on given command and arguments only with the specify args and don't care global command args
    96  // Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead.
    97  func NewCommandContextNoGlobals(ctx context.Context, args ...internal.CmdArg) *Command {
    98  	cargs := make([]string, 0, len(args))
    99  	for _, arg := range args {
   100  		cargs = append(cargs, string(arg))
   101  	}
   102  	return &Command{
   103  		prog:          GitExecutable,
   104  		args:          cargs,
   105  		parentContext: ctx,
   106  	}
   107  }
   108  
   109  // SetParentContext sets the parent context for this command
   110  func (c *Command) SetParentContext(ctx context.Context) *Command {
   111  	c.parentContext = ctx
   112  	return c
   113  }
   114  
   115  // SetDescription sets the description for this command which be returned on c.String()
   116  func (c *Command) SetDescription(desc string) *Command {
   117  	c.desc = desc
   118  	return c
   119  }
   120  
   121  // isSafeArgumentValue checks if the argument is safe to be used as a value (not an option)
   122  func isSafeArgumentValue(s string) bool {
   123  	return s == "" || s[0] != '-'
   124  }
   125  
   126  // isValidArgumentOption checks if the argument is a valid option (starting with '-').
   127  // It doesn't check whether the option is supported or not
   128  func isValidArgumentOption(s string) bool {
   129  	return s != "" && s[0] == '-'
   130  }
   131  
   132  // AddArguments adds new git arguments (option/value) to the command. It only accepts string literals, or trusted CmdArg.
   133  // Type CmdArg is in the internal package, so it can not be used outside of this package directly,
   134  // it makes sure that user-provided arguments won't cause RCE risks.
   135  // User-provided arguments should be passed by other AddXxx functions
   136  func (c *Command) AddArguments(args ...internal.CmdArg) *Command {
   137  	for _, arg := range args {
   138  		c.args = append(c.args, string(arg))
   139  	}
   140  	return c
   141  }
   142  
   143  // AddOptionValues adds a new option with a list of non-option values
   144  // For example: AddOptionValues("--opt", val) means 2 arguments: {"--opt", val}.
   145  // The values are treated as dynamic argument values. It equals to: AddArguments("--opt") then AddDynamicArguments(val).
   146  func (c *Command) AddOptionValues(opt internal.CmdArg, args ...string) *Command {
   147  	if !isValidArgumentOption(string(opt)) {
   148  		c.brokenArgs = append(c.brokenArgs, string(opt))
   149  		return c
   150  	}
   151  	c.args = append(c.args, string(opt))
   152  	c.AddDynamicArguments(args...)
   153  	return c
   154  }
   155  
   156  // AddOptionFormat adds a new option with a format string and arguments
   157  // For example: AddOptionFormat("--opt=%s %s", val1, val2) means 1 argument: {"--opt=val1 val2"}.
   158  func (c *Command) AddOptionFormat(opt string, args ...any) *Command {
   159  	if !isValidArgumentOption(opt) {
   160  		c.brokenArgs = append(c.brokenArgs, opt)
   161  		return c
   162  	}
   163  	// a quick check to make sure the format string matches the number of arguments, to find low-level mistakes ASAP
   164  	if strings.Count(strings.ReplaceAll(opt, "%%", ""), "%") != len(args) {
   165  		c.brokenArgs = append(c.brokenArgs, opt)
   166  		return c
   167  	}
   168  	s := fmt.Sprintf(opt, args...)
   169  	c.args = append(c.args, s)
   170  	return c
   171  }
   172  
   173  // AddDynamicArguments adds new dynamic argument values to the command.
   174  // The arguments may come from user input and can not be trusted, so no leading '-' is allowed to avoid passing options.
   175  // TODO: in the future, this function can be renamed to AddArgumentValues
   176  func (c *Command) AddDynamicArguments(args ...string) *Command {
   177  	for _, arg := range args {
   178  		if !isSafeArgumentValue(arg) {
   179  			c.brokenArgs = append(c.brokenArgs, arg)
   180  		}
   181  	}
   182  	if len(c.brokenArgs) != 0 {
   183  		return c
   184  	}
   185  	c.args = append(c.args, args...)
   186  	return c
   187  }
   188  
   189  // AddDashesAndList adds the "--" and then add the list as arguments, it's usually for adding file list
   190  // At the moment, this function can be only called once, maybe in future it can be refactored to support multiple calls (if necessary)
   191  func (c *Command) AddDashesAndList(list ...string) *Command {
   192  	c.args = append(c.args, "--")
   193  	// Some old code also checks `arg != ""`, IMO it's not necessary.
   194  	// If the check is needed, the list should be prepared before the call to this function
   195  	c.args = append(c.args, list...)
   196  	return c
   197  }
   198  
   199  // ToTrustedCmdArgs converts a list of strings (trusted as argument) to TrustedCmdArgs
   200  // In most cases, it shouldn't be used. Use NewCommand().AddXxx() function instead
   201  func ToTrustedCmdArgs(args []string) TrustedCmdArgs {
   202  	ret := make(TrustedCmdArgs, len(args))
   203  	for i, arg := range args {
   204  		ret[i] = internal.CmdArg(arg)
   205  	}
   206  	return ret
   207  }
   208  
   209  // RunOpts represents parameters to run the command. If UseContextTimeout is specified, then Timeout is ignored.
   210  type RunOpts struct {
   211  	Env               []string
   212  	Timeout           time.Duration
   213  	UseContextTimeout bool
   214  
   215  	// Dir is the working dir for the git command, however:
   216  	// FIXME: this could be incorrect in many cases, for example:
   217  	// * /some/path/.git
   218  	// * /some/path/.git/gitea-data/data/repositories/user/repo.git
   219  	// If "user/repo.git" is invalid/broken, then running git command in it will use "/some/path/.git", and produce unexpected results
   220  	// The correct approach is to use `--git-dir" global argument
   221  	Dir string
   222  
   223  	Stdout, Stderr io.Writer
   224  
   225  	// Stdin is used for passing input to the command
   226  	// The caller must make sure the Stdin writer is closed properly to finish the Run function.
   227  	// Otherwise, the Run function may hang for long time or forever, especially when the Git's context deadline is not the same as the caller's.
   228  	// Some common mistakes:
   229  	// * `defer stdinWriter.Close()` then call `cmd.Run()`: the Run() would never return if the command is killed by timeout
   230  	// * `go { case <- parentContext.Done(): stdinWriter.Close() }` with `cmd.Run(DefaultTimeout)`: the command would have been killed by timeout but the Run doesn't return until stdinWriter.Close()
   231  	// * `go { if stdoutReader.Read() err != nil: stdinWriter.Close() }` with `cmd.Run()`: the stdoutReader may never return error if the command is killed by timeout
   232  	// In the future, ideally the git module itself should have full control of the stdin, to avoid such problems and make it easier to refactor to a better architecture.
   233  	Stdin io.Reader
   234  
   235  	PipelineFunc func(context.Context, context.CancelFunc) error
   236  }
   237  
   238  func commonBaseEnvs() []string {
   239  	// at the moment, do not set "GIT_CONFIG_NOSYSTEM", users may have put some configs like "receive.certNonceSeed" in it
   240  	envs := []string{
   241  		"HOME=" + HomeDir(),        // make Gitea use internal git config only, to prevent conflicts with user's git config
   242  		"GIT_NO_REPLACE_OBJECTS=1", // ignore replace references (https://git-scm.com/docs/git-replace)
   243  	}
   244  
   245  	// some environment variables should be passed to git command
   246  	passThroughEnvKeys := []string{
   247  		"GNUPGHOME", // git may call gnupg to do commit signing
   248  	}
   249  	for _, key := range passThroughEnvKeys {
   250  		if val, ok := os.LookupEnv(key); ok {
   251  			envs = append(envs, key+"="+val)
   252  		}
   253  	}
   254  	return envs
   255  }
   256  
   257  // CommonGitCmdEnvs returns the common environment variables for a "git" command.
   258  func CommonGitCmdEnvs() []string {
   259  	return append(commonBaseEnvs(), []string{
   260  		"LC_ALL=" + DefaultLocale,
   261  		"GIT_TERMINAL_PROMPT=0", // avoid prompting for credentials interactively, supported since git v2.3
   262  	}...)
   263  }
   264  
   265  // CommonCmdServEnvs is like CommonGitCmdEnvs, but it only returns minimal required environment variables for the "gitea serv" command
   266  func CommonCmdServEnvs() []string {
   267  	return commonBaseEnvs()
   268  }
   269  
   270  var ErrBrokenCommand = errors.New("git command is broken")
   271  
   272  // Run runs the command with the RunOpts
   273  func (c *Command) Run(opts *RunOpts) error {
   274  	if len(c.brokenArgs) != 0 {
   275  		log.Error("git command is broken: %s, broken args: %s", c.String(), strings.Join(c.brokenArgs, " "))
   276  		return ErrBrokenCommand
   277  	}
   278  	if opts == nil {
   279  		opts = &RunOpts{}
   280  	}
   281  
   282  	// We must not change the provided options
   283  	timeout := opts.Timeout
   284  	if timeout <= 0 {
   285  		timeout = defaultCommandExecutionTimeout
   286  	}
   287  
   288  	if len(opts.Dir) == 0 {
   289  		log.Debug("git.Command.Run: %s", c)
   290  	} else {
   291  		log.Debug("git.Command.RunDir(%s): %s", opts.Dir, c)
   292  	}
   293  
   294  	desc := c.desc
   295  	if desc == "" {
   296  		if opts.Dir == "" {
   297  			desc = fmt.Sprintf("git: %s", c.toString(true))
   298  		} else {
   299  			desc = fmt.Sprintf("git(dir:%s): %s", opts.Dir, c.toString(true))
   300  		}
   301  	}
   302  
   303  	var ctx context.Context
   304  	var cancel context.CancelFunc
   305  	var finished context.CancelFunc
   306  
   307  	if opts.UseContextTimeout {
   308  		ctx, cancel, finished = process.GetManager().AddContext(c.parentContext, desc)
   309  	} else {
   310  		ctx, cancel, finished = process.GetManager().AddContextTimeout(c.parentContext, timeout, desc)
   311  	}
   312  	defer finished()
   313  
   314  	startTime := time.Now()
   315  
   316  	cmd := exec.CommandContext(ctx, c.prog, c.args...)
   317  	if opts.Env == nil {
   318  		cmd.Env = os.Environ()
   319  	} else {
   320  		cmd.Env = opts.Env
   321  	}
   322  
   323  	process.SetSysProcAttribute(cmd)
   324  	cmd.Env = append(cmd.Env, CommonGitCmdEnvs()...)
   325  	cmd.Dir = opts.Dir
   326  	cmd.Stdout = opts.Stdout
   327  	cmd.Stderr = opts.Stderr
   328  	cmd.Stdin = opts.Stdin
   329  	if err := cmd.Start(); err != nil {
   330  		return err
   331  	}
   332  
   333  	if opts.PipelineFunc != nil {
   334  		err := opts.PipelineFunc(ctx, cancel)
   335  		if err != nil {
   336  			cancel()
   337  			_ = cmd.Wait()
   338  			return err
   339  		}
   340  	}
   341  
   342  	err := cmd.Wait()
   343  	elapsed := time.Since(startTime)
   344  	if elapsed > time.Second {
   345  		log.Debug("slow git.Command.Run: %s (%s)", c, elapsed)
   346  	}
   347  
   348  	// We need to check if the context is canceled by the program on Windows.
   349  	// This is because Windows does not have signal checking when terminating the process.
   350  	// It always returns exit code 1, unlike Linux, which has many exit codes for signals.
   351  	if runtime.GOOS == "windows" &&
   352  		err != nil &&
   353  		err.Error() == "" &&
   354  		cmd.ProcessState.ExitCode() == 1 &&
   355  		ctx.Err() == context.Canceled {
   356  		return ctx.Err()
   357  	}
   358  
   359  	if err != nil && ctx.Err() != context.DeadlineExceeded {
   360  		return err
   361  	}
   362  
   363  	return ctx.Err()
   364  }
   365  
   366  type RunStdError interface {
   367  	error
   368  	Unwrap() error
   369  	Stderr() string
   370  }
   371  
   372  type runStdError struct {
   373  	err    error
   374  	stderr string
   375  	errMsg string
   376  }
   377  
   378  func (r *runStdError) Error() string {
   379  	// the stderr must be in the returned error text, some code only checks `strings.Contains(err.Error(), "git error")`
   380  	if r.errMsg == "" {
   381  		r.errMsg = ConcatenateError(r.err, r.stderr).Error()
   382  	}
   383  	return r.errMsg
   384  }
   385  
   386  func (r *runStdError) Unwrap() error {
   387  	return r.err
   388  }
   389  
   390  func (r *runStdError) Stderr() string {
   391  	return r.stderr
   392  }
   393  
   394  func IsErrorExitCode(err error, code int) bool {
   395  	var exitError *exec.ExitError
   396  	if errors.As(err, &exitError) {
   397  		return exitError.ExitCode() == code
   398  	}
   399  	return false
   400  }
   401  
   402  // RunStdString runs the command with options and returns stdout/stderr as string. and store stderr to returned error (err combined with stderr).
   403  func (c *Command) RunStdString(opts *RunOpts) (stdout, stderr string, runErr RunStdError) {
   404  	stdoutBytes, stderrBytes, err := c.RunStdBytes(opts)
   405  	stdout = util.UnsafeBytesToString(stdoutBytes)
   406  	stderr = util.UnsafeBytesToString(stderrBytes)
   407  	if err != nil {
   408  		return stdout, stderr, &runStdError{err: err, stderr: stderr}
   409  	}
   410  	// even if there is no err, there could still be some stderr output, so we just return stdout/stderr as they are
   411  	return stdout, stderr, nil
   412  }
   413  
   414  // RunStdBytes runs the command with options and returns stdout/stderr as bytes. and store stderr to returned error (err combined with stderr).
   415  func (c *Command) RunStdBytes(opts *RunOpts) (stdout, stderr []byte, runErr RunStdError) {
   416  	if opts == nil {
   417  		opts = &RunOpts{}
   418  	}
   419  	if opts.Stdout != nil || opts.Stderr != nil {
   420  		// we must panic here, otherwise there would be bugs if developers set Stdin/Stderr by mistake, and it would be very difficult to debug
   421  		panic("stdout and stderr field must be nil when using RunStdBytes")
   422  	}
   423  	stdoutBuf := &bytes.Buffer{}
   424  	stderrBuf := &bytes.Buffer{}
   425  
   426  	// We must not change the provided options as it could break future calls - therefore make a copy.
   427  	newOpts := &RunOpts{
   428  		Env:               opts.Env,
   429  		Timeout:           opts.Timeout,
   430  		UseContextTimeout: opts.UseContextTimeout,
   431  		Dir:               opts.Dir,
   432  		Stdout:            stdoutBuf,
   433  		Stderr:            stderrBuf,
   434  		Stdin:             opts.Stdin,
   435  		PipelineFunc:      opts.PipelineFunc,
   436  	}
   437  
   438  	err := c.Run(newOpts)
   439  	stderr = stderrBuf.Bytes()
   440  	if err != nil {
   441  		return nil, stderr, &runStdError{err: err, stderr: util.UnsafeBytesToString(stderr)}
   442  	}
   443  	// even if there is no err, there could still be some stderr output
   444  	return stdoutBuf.Bytes(), stderr, nil
   445  }
   446  
   447  // AllowLFSFiltersArgs return globalCommandArgs with lfs filter, it should only be used for tests
   448  func AllowLFSFiltersArgs() TrustedCmdArgs {
   449  	// Now here we should explicitly allow lfs filters to run
   450  	filteredLFSGlobalArgs := make(TrustedCmdArgs, len(globalCommandArgs))
   451  	j := 0
   452  	for _, arg := range globalCommandArgs {
   453  		if strings.Contains(string(arg), "lfs") {
   454  			j--
   455  		} else {
   456  			filteredLFSGlobalArgs[j] = arg
   457  			j++
   458  		}
   459  	}
   460  	return filteredLFSGlobalArgs[:j]
   461  }