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.

git.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package git
  5. import (
  6. "context"
  7. "errors"
  8. "fmt"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "regexp"
  13. "runtime"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "github.com/hashicorp/go-version"
  19. )
  20. const RequiredVersion = "2.0.0" // the minimum Git version required
  21. type Features struct {
  22. gitVersion *version.Version
  23. UsingGogit bool
  24. SupportProcReceive bool // >= 2.29
  25. SupportHashSha256 bool // >= 2.42, SHA-256 repositories no longer an ‘experimental curiosity’
  26. SupportedObjectFormats []ObjectFormat // sha1, sha256
  27. }
  28. var (
  29. GitExecutable = "git" // the command name of git, will be updated to an absolute path during initialization
  30. DefaultContext context.Context // the default context to run git commands in, must be initialized by git.InitXxx
  31. defaultFeatures *Features
  32. )
  33. func (f *Features) CheckVersionAtLeast(atLeast string) bool {
  34. return f.gitVersion.Compare(version.Must(version.NewVersion(atLeast))) >= 0
  35. }
  36. // VersionInfo returns git version information
  37. func (f *Features) VersionInfo() string {
  38. return f.gitVersion.Original()
  39. }
  40. func DefaultFeatures() *Features {
  41. if defaultFeatures == nil {
  42. if !setting.IsProd || setting.IsInTesting {
  43. log.Warn("git.DefaultFeatures is called before git.InitXxx, initializing with default values")
  44. }
  45. if err := InitSimple(context.Background()); err != nil {
  46. log.Fatal("git.InitSimple failed: %v", err)
  47. }
  48. }
  49. return defaultFeatures
  50. }
  51. func loadGitVersionFeatures() (*Features, error) {
  52. stdout, _, runErr := NewCommand(DefaultContext, "version").RunStdString(nil)
  53. if runErr != nil {
  54. return nil, runErr
  55. }
  56. ver, err := parseGitVersionLine(strings.TrimSpace(stdout))
  57. if err != nil {
  58. return nil, err
  59. }
  60. features := &Features{gitVersion: ver, UsingGogit: isGogit}
  61. features.SupportProcReceive = features.CheckVersionAtLeast("2.29")
  62. features.SupportHashSha256 = features.CheckVersionAtLeast("2.42") && !isGogit
  63. features.SupportedObjectFormats = []ObjectFormat{Sha1ObjectFormat}
  64. if features.SupportHashSha256 {
  65. features.SupportedObjectFormats = append(features.SupportedObjectFormats, Sha256ObjectFormat)
  66. }
  67. return features, nil
  68. }
  69. func parseGitVersionLine(s string) (*version.Version, error) {
  70. fields := strings.Fields(s)
  71. if len(fields) < 3 {
  72. return nil, fmt.Errorf("invalid git version: %q", s)
  73. }
  74. // version string is like: "git version 2.29.3" or "git version 2.29.3.windows.1"
  75. versionString := fields[2]
  76. if pos := strings.Index(versionString, "windows"); pos >= 1 {
  77. versionString = versionString[:pos-1]
  78. }
  79. return version.NewVersion(versionString)
  80. }
  81. // SetExecutablePath changes the path of git executable and checks the file permission and version.
  82. func SetExecutablePath(path string) error {
  83. // If path is empty, we use the default value of GitExecutable "git" to search for the location of git.
  84. if path != "" {
  85. GitExecutable = path
  86. }
  87. absPath, err := exec.LookPath(GitExecutable)
  88. if err != nil {
  89. return fmt.Errorf("git not found: %w", err)
  90. }
  91. GitExecutable = absPath
  92. return nil
  93. }
  94. func ensureGitVersion() error {
  95. if !DefaultFeatures().CheckVersionAtLeast(RequiredVersion) {
  96. moreHint := "get git: https://git-scm.com/download/"
  97. if runtime.GOOS == "linux" {
  98. // there are a lot of CentOS/RHEL users using old git, so we add a special hint for them
  99. if _, err := os.Stat("/etc/redhat-release"); err == nil {
  100. // ius.io is the recommended official(git-scm.com) method to install git
  101. moreHint = "get git: https://git-scm.com/download/linux and https://ius.io"
  102. }
  103. }
  104. return fmt.Errorf("installed git version %q is not supported, Gitea requires git version >= %q, %s", DefaultFeatures().gitVersion.Original(), RequiredVersion, moreHint)
  105. }
  106. if err := checkGitVersionCompatibility(DefaultFeatures().gitVersion); err != nil {
  107. return fmt.Errorf("installed git version %s has a known compatibility issue with Gitea: %w, please upgrade (or downgrade) git", DefaultFeatures().gitVersion.String(), err)
  108. }
  109. return nil
  110. }
  111. // HomeDir is the home dir for git to store the global config file used by Gitea internally
  112. func HomeDir() string {
  113. if setting.Git.HomePath == "" {
  114. // strict check, make sure the git module is initialized correctly.
  115. // attention: when the git module is called in gitea sub-command (serv/hook), the log module might not obviously show messages to users/developers.
  116. // for example: if there is gitea git hook code calling git.NewCommand before git.InitXxx, the integration test won't show the real failure reasons.
  117. log.Fatal("Unable to init Git's HomeDir, incorrect initialization of the setting and git modules")
  118. return ""
  119. }
  120. return setting.Git.HomePath
  121. }
  122. // InitSimple initializes git module with a very simple step, no config changes, no global command arguments.
  123. // This method doesn't change anything to filesystem. At the moment, it is only used by some Gitea sub-commands.
  124. func InitSimple(ctx context.Context) error {
  125. if setting.Git.HomePath == "" {
  126. return errors.New("unable to init Git's HomeDir, incorrect initialization of the setting and git modules")
  127. }
  128. if DefaultContext != nil && (!setting.IsProd || setting.IsInTesting) {
  129. log.Warn("git module has been initialized already, duplicate init may work but it's better to fix it")
  130. }
  131. DefaultContext = ctx
  132. globalCommandArgs = nil
  133. if setting.Git.Timeout.Default > 0 {
  134. defaultCommandExecutionTimeout = time.Duration(setting.Git.Timeout.Default) * time.Second
  135. }
  136. if err := SetExecutablePath(setting.Git.Path); err != nil {
  137. return err
  138. }
  139. var err error
  140. defaultFeatures, err = loadGitVersionFeatures()
  141. if err != nil {
  142. return err
  143. }
  144. if err = ensureGitVersion(); err != nil {
  145. return err
  146. }
  147. // when git works with gnupg (commit signing), there should be a stable home for gnupg commands
  148. if _, ok := os.LookupEnv("GNUPGHOME"); !ok {
  149. _ = os.Setenv("GNUPGHOME", filepath.Join(HomeDir(), ".gnupg"))
  150. }
  151. return nil
  152. }
  153. // InitFull initializes git module with version check and change global variables, sync gitconfig.
  154. // It should only be called once at the beginning of the program initialization (TestMain/GlobalInitInstalled) as this code makes unsynchronized changes to variables.
  155. func InitFull(ctx context.Context) (err error) {
  156. if err = InitSimple(ctx); err != nil {
  157. return err
  158. }
  159. // Since git wire protocol has been released from git v2.18
  160. if setting.Git.EnableAutoGitWireProtocol && DefaultFeatures().CheckVersionAtLeast("2.18") {
  161. globalCommandArgs = append(globalCommandArgs, "-c", "protocol.version=2")
  162. }
  163. // Explicitly disable credential helper, otherwise Git credentials might leak
  164. if DefaultFeatures().CheckVersionAtLeast("2.9") {
  165. globalCommandArgs = append(globalCommandArgs, "-c", "credential.helper=")
  166. }
  167. if setting.LFS.StartServer {
  168. if !DefaultFeatures().CheckVersionAtLeast("2.1.2") {
  169. return errors.New("LFS server support requires Git >= 2.1.2")
  170. }
  171. globalCommandArgs = append(globalCommandArgs, "-c", "filter.lfs.required=", "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=")
  172. }
  173. return syncGitConfig()
  174. }
  175. // syncGitConfig only modifies gitconfig, won't change global variables (otherwise there will be data-race problem)
  176. func syncGitConfig() (err error) {
  177. if err = os.MkdirAll(HomeDir(), os.ModePerm); err != nil {
  178. return fmt.Errorf("unable to prepare git home directory %s, err: %w", HomeDir(), err)
  179. }
  180. // first, write user's git config options to git config file
  181. // user config options could be overwritten by builtin values later, because if a value is builtin, it must have some special purposes
  182. for k, v := range setting.GitConfig.Options {
  183. if err = configSet(strings.ToLower(k), v); err != nil {
  184. return err
  185. }
  186. }
  187. // Git requires setting user.name and user.email in order to commit changes - old comment: "if they're not set just add some defaults"
  188. // TODO: need to confirm whether users really need to change these values manually. It seems that these values are dummy only and not really used.
  189. // If these values are not really used, then they can be set (overwritten) directly without considering about existence.
  190. for configKey, defaultValue := range map[string]string{
  191. "user.name": "Gitea",
  192. "user.email": "gitea@fake.local",
  193. } {
  194. if err := configSetNonExist(configKey, defaultValue); err != nil {
  195. return err
  196. }
  197. }
  198. // Set git some configurations - these must be set to these values for gitea to work correctly
  199. if err := configSet("core.quotePath", "false"); err != nil {
  200. return err
  201. }
  202. if DefaultFeatures().CheckVersionAtLeast("2.10") {
  203. if err := configSet("receive.advertisePushOptions", "true"); err != nil {
  204. return err
  205. }
  206. }
  207. if DefaultFeatures().CheckVersionAtLeast("2.18") {
  208. if err := configSet("core.commitGraph", "true"); err != nil {
  209. return err
  210. }
  211. if err := configSet("gc.writeCommitGraph", "true"); err != nil {
  212. return err
  213. }
  214. if err := configSet("fetch.writeCommitGraph", "true"); err != nil {
  215. return err
  216. }
  217. }
  218. if DefaultFeatures().SupportProcReceive {
  219. // set support for AGit flow
  220. if err := configAddNonExist("receive.procReceiveRefs", "refs/for"); err != nil {
  221. return err
  222. }
  223. } else {
  224. if err := configUnsetAll("receive.procReceiveRefs", "refs/for"); err != nil {
  225. return err
  226. }
  227. }
  228. // Due to CVE-2022-24765, git now denies access to git directories which are not owned by current user.
  229. // However, some docker users and samba users find it difficult to configure their systems correctly,
  230. // so that Gitea's git repositories are owned by the Gitea user.
  231. // (Possibly Windows Service users - but ownership in this case should really be set correctly on the filesystem.)
  232. // See issue: https://github.com/go-gitea/gitea/issues/19455
  233. // As Gitea now always use its internal git config file, and access to the git repositories is managed through Gitea,
  234. // it is now safe to set "safe.directory=*" for internal usage only.
  235. // Although this setting is only supported by some new git versions, it is also tolerated by earlier versions
  236. if err := configAddNonExist("safe.directory", "*"); err != nil {
  237. return err
  238. }
  239. if runtime.GOOS == "windows" {
  240. if err := configSet("core.longpaths", "true"); err != nil {
  241. return err
  242. }
  243. if setting.Git.DisableCoreProtectNTFS {
  244. err = configSet("core.protectNTFS", "false")
  245. } else {
  246. err = configUnsetAll("core.protectNTFS", "false")
  247. }
  248. if err != nil {
  249. return err
  250. }
  251. }
  252. // By default partial clones are disabled, enable them from git v2.22
  253. if !setting.Git.DisablePartialClone && DefaultFeatures().CheckVersionAtLeast("2.22") {
  254. if err = configSet("uploadpack.allowfilter", "true"); err != nil {
  255. return err
  256. }
  257. err = configSet("uploadpack.allowAnySHA1InWant", "true")
  258. } else {
  259. if err = configUnsetAll("uploadpack.allowfilter", "true"); err != nil {
  260. return err
  261. }
  262. err = configUnsetAll("uploadpack.allowAnySHA1InWant", "true")
  263. }
  264. return err
  265. }
  266. func checkGitVersionCompatibility(gitVer *version.Version) error {
  267. badVersions := []struct {
  268. Version *version.Version
  269. Reason string
  270. }{
  271. {version.Must(version.NewVersion("2.43.1")), "regression bug of GIT_FLUSH"},
  272. }
  273. for _, bad := range badVersions {
  274. if gitVer.Equal(bad.Version) {
  275. return errors.New(bad.Reason)
  276. }
  277. }
  278. return nil
  279. }
  280. func configSet(key, value string) error {
  281. stdout, _, err := NewCommand(DefaultContext, "config", "--global", "--get").AddDynamicArguments(key).RunStdString(nil)
  282. if err != nil && !IsErrorExitCode(err, 1) {
  283. return fmt.Errorf("failed to get git config %s, err: %w", key, err)
  284. }
  285. currValue := strings.TrimSpace(stdout)
  286. if currValue == value {
  287. return nil
  288. }
  289. _, _, err = NewCommand(DefaultContext, "config", "--global").AddDynamicArguments(key, value).RunStdString(nil)
  290. if err != nil {
  291. return fmt.Errorf("failed to set git global config %s, err: %w", key, err)
  292. }
  293. return nil
  294. }
  295. func configSetNonExist(key, value string) error {
  296. _, _, err := NewCommand(DefaultContext, "config", "--global", "--get").AddDynamicArguments(key).RunStdString(nil)
  297. if err == nil {
  298. // already exist
  299. return nil
  300. }
  301. if IsErrorExitCode(err, 1) {
  302. // not exist, set new config
  303. _, _, err = NewCommand(DefaultContext, "config", "--global").AddDynamicArguments(key, value).RunStdString(nil)
  304. if err != nil {
  305. return fmt.Errorf("failed to set git global config %s, err: %w", key, err)
  306. }
  307. return nil
  308. }
  309. return fmt.Errorf("failed to get git config %s, err: %w", key, err)
  310. }
  311. func configAddNonExist(key, value string) error {
  312. _, _, err := NewCommand(DefaultContext, "config", "--global", "--get").AddDynamicArguments(key, regexp.QuoteMeta(value)).RunStdString(nil)
  313. if err == nil {
  314. // already exist
  315. return nil
  316. }
  317. if IsErrorExitCode(err, 1) {
  318. // not exist, add new config
  319. _, _, err = NewCommand(DefaultContext, "config", "--global", "--add").AddDynamicArguments(key, value).RunStdString(nil)
  320. if err != nil {
  321. return fmt.Errorf("failed to add git global config %s, err: %w", key, err)
  322. }
  323. return nil
  324. }
  325. return fmt.Errorf("failed to get git config %s, err: %w", key, err)
  326. }
  327. func configUnsetAll(key, value string) error {
  328. _, _, err := NewCommand(DefaultContext, "config", "--global", "--get").AddDynamicArguments(key).RunStdString(nil)
  329. if err == nil {
  330. // exist, need to remove
  331. _, _, err = NewCommand(DefaultContext, "config", "--global", "--unset-all").AddDynamicArguments(key, regexp.QuoteMeta(value)).RunStdString(nil)
  332. if err != nil {
  333. return fmt.Errorf("failed to unset git global config %s, err: %w", key, err)
  334. }
  335. return nil
  336. }
  337. if IsErrorExitCode(err, 1) {
  338. // not exist
  339. return nil
  340. }
  341. return fmt.Errorf("failed to get git config %s, err: %w", key, err)
  342. }
  343. // Fsck verifies the connectivity and validity of the objects in the database
  344. func Fsck(ctx context.Context, repoPath string, timeout time.Duration, args TrustedCmdArgs) error {
  345. return NewCommand(ctx, "fsck").AddArguments(args...).Run(&RunOpts{Timeout: timeout, Dir: repoPath})
  346. }