gitea源码

command.go 15KB

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