1
// Copyright 2015 The Gogs Authors. All rights reserved.
2
// Copyright 2016 The Gitea Authors. All rights reserved.
3
// SPDX-License-Identifier: MIT
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"
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
31
// globalCommandArgs global command args for external package setting
32
globalCommandArgs TrustedCmdArgs
34
// defaultCommandExecutionTimeout default command execution timeout duration
35
defaultCommandExecutionTimeout = 360 * time.Second
38
// DefaultLocale is the default LC_ALL to run git commands in.
39
const DefaultLocale = "C"
41
// Command represents a command with its subcommands or arguments.
45
parentContext context.Context
51
func (c *Command) String() string {
52
return c.toString(false)
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)
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)))
70
a = append(a, debugQuote(arg))
73
return strings.Join(a, " ")
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))
84
for _, arg := range args {
85
cargs = append(cargs, string(arg))
91
globalArgsLength: len(globalCommandArgs),
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))
109
// SetParentContext sets the parent context for this command
110
func (c *Command) SetParentContext(ctx context.Context) *Command {
111
c.parentContext = ctx
115
// SetDescription sets the description for this command which be returned on c.String()
116
func (c *Command) SetDescription(desc string) *Command {
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] != '-'
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] == '-'
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))
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))
151
c.args = append(c.args, string(opt))
152
c.AddDynamicArguments(args...)
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)
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)
168
s := fmt.Sprintf(opt, args...)
169
c.args = append(c.args, s)
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)
182
if len(c.brokenArgs) != 0 {
185
c.args = append(c.args, args...)
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...)
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)
209
// RunOpts represents parameters to run the command. If UseContextTimeout is specified, then Timeout is ignored.
212
Timeout time.Duration
213
UseContextTimeout bool
215
// Dir is the working dir for the git command, however:
216
// FIXME: this could be incorrect in many cases, for example:
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
223
Stdout, Stderr io.Writer
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.
235
PipelineFunc func(context.Context, context.CancelFunc) error
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
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)
245
// some environment variables should be passed to git command
246
passThroughEnvKeys := []string{
247
"GNUPGHOME", // git may call gnupg to do commit signing
249
for _, key := range passThroughEnvKeys {
250
if val, ok := os.LookupEnv(key); ok {
251
envs = append(envs, key+"="+val)
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
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()
270
var ErrBrokenCommand = errors.New("git command is broken")
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
282
// We must not change the provided options
283
timeout := opts.Timeout
285
timeout = defaultCommandExecutionTimeout
288
if len(opts.Dir) == 0 {
289
log.Debug("git.Command.Run: %s", c)
291
log.Debug("git.Command.RunDir(%s): %s", opts.Dir, c)
297
desc = fmt.Sprintf("git: %s", c.toString(true))
299
desc = fmt.Sprintf("git(dir:%s): %s", opts.Dir, c.toString(true))
303
var ctx context.Context
304
var cancel context.CancelFunc
305
var finished context.CancelFunc
307
if opts.UseContextTimeout {
308
ctx, cancel, finished = process.GetManager().AddContext(c.parentContext, desc)
310
ctx, cancel, finished = process.GetManager().AddContextTimeout(c.parentContext, timeout, desc)
314
startTime := time.Now()
316
cmd := exec.CommandContext(ctx, c.prog, c.args...)
318
cmd.Env = os.Environ()
323
process.SetSysProcAttribute(cmd)
324
cmd.Env = append(cmd.Env, CommonGitCmdEnvs()...)
326
cmd.Stdout = opts.Stdout
327
cmd.Stderr = opts.Stderr
328
cmd.Stdin = opts.Stdin
329
if err := cmd.Start(); err != nil {
333
if opts.PipelineFunc != nil {
334
err := opts.PipelineFunc(ctx, cancel)
343
elapsed := time.Since(startTime)
344
if elapsed > time.Second {
345
log.Debug("slow git.Command.Run: %s (%s)", c, elapsed)
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" &&
354
cmd.ProcessState.ExitCode() == 1 &&
355
ctx.Err() == context.Canceled {
359
if err != nil && ctx.Err() != context.DeadlineExceeded {
366
type RunStdError interface {
372
type runStdError struct {
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")`
381
r.errMsg = ConcatenateError(r.err, r.stderr).Error()
386
func (r *runStdError) Unwrap() error {
390
func (r *runStdError) Stderr() string {
394
func IsErrorExitCode(err error, code int) bool {
395
var exitError *exec.ExitError
396
if errors.As(err, &exitError) {
397
return exitError.ExitCode() == code
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)
408
return stdout, stderr, &runStdError{err: err, stderr: stderr}
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
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) {
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")
423
stdoutBuf := &bytes.Buffer{}
424
stderrBuf := &bytes.Buffer{}
426
// We must not change the provided options as it could break future calls - therefore make a copy.
429
Timeout: opts.Timeout,
430
UseContextTimeout: opts.UseContextTimeout,
435
PipelineFunc: opts.PipelineFunc,
438
err := c.Run(newOpts)
439
stderr = stderrBuf.Bytes()
441
return nil, stderr, &runStdError{err: err, stderr: util.UnsafeBytesToString(stderr)}
443
// even if there is no err, there could still be some stderr output
444
return stdoutBuf.Bytes(), stderr, nil
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))
452
for _, arg := range globalCommandArgs {
453
if strings.Contains(string(arg), "lfs") {
456
filteredLFSGlobalArgs[j] = arg
460
return filteredLFSGlobalArgs[:j]