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

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