You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

command.go 15KB

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