hook.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cmd
  5. import (
  6. "bufio"
  7. "bytes"
  8. "crypto/tls"
  9. "fmt"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "strings"
  14. "github.com/Unknwon/com"
  15. "github.com/urfave/cli"
  16. log "gopkg.in/clog.v1"
  17. "github.com/gogits/git-module"
  18. "github.com/gogits/gogs/models"
  19. "github.com/gogits/gogs/pkg/httplib"
  20. "github.com/gogits/gogs/pkg/setting"
  21. http "github.com/gogits/gogs/routers/repo"
  22. )
  23. var (
  24. Hook = cli.Command{
  25. Name: "hook",
  26. Usage: "Delegate commands to corresponding Git hooks",
  27. Description: "All sub-commands should only be called by Git",
  28. Flags: []cli.Flag{
  29. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  30. },
  31. Subcommands: []cli.Command{
  32. subcmdHookPreReceive,
  33. subcmdHookUpadte,
  34. subcmdHookPostReceive,
  35. },
  36. }
  37. subcmdHookPreReceive = cli.Command{
  38. Name: "pre-receive",
  39. Usage: "Delegate pre-receive Git hook",
  40. Description: "This command should only be called by Git",
  41. Action: runHookPreReceive,
  42. }
  43. subcmdHookUpadte = cli.Command{
  44. Name: "update",
  45. Usage: "Delegate update Git hook",
  46. Description: "This command should only be called by Git",
  47. Action: runHookUpdate,
  48. }
  49. subcmdHookPostReceive = cli.Command{
  50. Name: "post-receive",
  51. Usage: "Delegate post-receive Git hook",
  52. Description: "This command should only be called by Git",
  53. Action: runHookPostReceive,
  54. }
  55. )
  56. func runHookPreReceive(c *cli.Context) error {
  57. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  58. return nil
  59. }
  60. setup(c, "hooks/pre-receive.log", true)
  61. isWiki := strings.Contains(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/")
  62. buf := bytes.NewBuffer(nil)
  63. scanner := bufio.NewScanner(os.Stdin)
  64. for scanner.Scan() {
  65. buf.Write(scanner.Bytes())
  66. buf.WriteByte('\n')
  67. if isWiki {
  68. continue
  69. }
  70. fields := bytes.Fields(scanner.Bytes())
  71. if len(fields) != 3 {
  72. continue
  73. }
  74. oldCommitID := string(fields[0])
  75. newCommitID := string(fields[1])
  76. branchName := strings.TrimPrefix(string(fields[2]), git.BRANCH_PREFIX)
  77. // Branch protection
  78. repoID := com.StrTo(os.Getenv(http.ENV_REPO_ID)).MustInt64()
  79. protectBranch, err := models.GetProtectBranchOfRepoByName(repoID, branchName)
  80. if err != nil {
  81. if models.IsErrBranchNotExist(err) {
  82. continue
  83. }
  84. fail("Internal error", "GetProtectBranchOfRepoByName [repo_id: %d, branch: %s]: %v", repoID, branchName, err)
  85. }
  86. if !protectBranch.Protected {
  87. continue
  88. }
  89. // Whitelist users can bypass require pull request check
  90. bypassRequirePullRequest := false
  91. // Check if user is in whitelist when enabled
  92. userID := com.StrTo(os.Getenv(http.ENV_AUTH_USER_ID)).MustInt64()
  93. if protectBranch.EnableWhitelist {
  94. if !models.IsUserInProtectBranchWhitelist(repoID, userID, branchName) {
  95. fail(fmt.Sprintf("Branch '%s' is protected and you are not in the push whitelist", branchName), "")
  96. }
  97. bypassRequirePullRequest = true
  98. }
  99. // Check if branch allows direct push
  100. if !bypassRequirePullRequest && protectBranch.RequirePullRequest {
  101. fail(fmt.Sprintf("Branch '%s' is protected and commits must be merged through pull request", branchName), "")
  102. }
  103. // check and deletion
  104. if newCommitID == git.EMPTY_SHA {
  105. fail(fmt.Sprintf("Branch '%s' is protected from deletion", branchName), "")
  106. }
  107. // Check force push
  108. output, err := git.NewCommand("rev-list", oldCommitID, "^"+newCommitID).
  109. RunInDir(models.RepoPath(os.Getenv(http.ENV_REPO_OWNER_NAME), os.Getenv(http.ENV_REPO_NAME)))
  110. if err != nil {
  111. fail("Internal error", "Fail to detect force push: %v", err)
  112. } else if len(output) > 0 {
  113. fail(fmt.Sprintf("Branch '%s' is protected from force push", branchName), "")
  114. }
  115. }
  116. customHooksPath := filepath.Join(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), "pre-receive")
  117. if !com.IsFile(customHooksPath) {
  118. return nil
  119. }
  120. hookCmd := exec.Command(customHooksPath)
  121. hookCmd.Dir = models.RepoPath(os.Getenv(http.ENV_REPO_OWNER_NAME), os.Getenv(http.ENV_REPO_NAME))
  122. hookCmd.Stdout = os.Stdout
  123. hookCmd.Stdin = buf
  124. hookCmd.Stderr = os.Stderr
  125. if err := hookCmd.Run(); err != nil {
  126. fail("Internal error", "Fail to execute custom pre-receive hook: %v", err)
  127. }
  128. return nil
  129. }
  130. func runHookUpdate(c *cli.Context) error {
  131. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  132. return nil
  133. }
  134. setup(c, "hooks/update.log", false)
  135. args := c.Args()
  136. if len(args) != 3 {
  137. fail("Arguments received are not equal to three", "Arguments received are not equal to three")
  138. } else if len(args[0]) == 0 {
  139. fail("First argument 'refName' is empty", "First argument 'refName' is empty")
  140. }
  141. customHooksPath := filepath.Join(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), "update")
  142. if !com.IsFile(customHooksPath) {
  143. return nil
  144. }
  145. hookCmd := exec.Command(customHooksPath, args...)
  146. hookCmd.Dir = models.RepoPath(os.Getenv(http.ENV_REPO_OWNER_NAME), os.Getenv(http.ENV_REPO_NAME))
  147. hookCmd.Stdout = os.Stdout
  148. hookCmd.Stdin = os.Stdin
  149. hookCmd.Stderr = os.Stderr
  150. if err := hookCmd.Run(); err != nil {
  151. fail("Internal error", "Fail to execute custom pre-receive hook: %v", err)
  152. }
  153. return nil
  154. }
  155. func runHookPostReceive(c *cli.Context) error {
  156. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  157. return nil
  158. }
  159. setup(c, "hooks/post-receive.log", true)
  160. isWiki := strings.Contains(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/")
  161. buf := bytes.NewBuffer(nil)
  162. scanner := bufio.NewScanner(os.Stdin)
  163. for scanner.Scan() {
  164. buf.Write(scanner.Bytes())
  165. buf.WriteByte('\n')
  166. // TODO: support news feeds for wiki
  167. if isWiki {
  168. continue
  169. }
  170. fields := bytes.Fields(scanner.Bytes())
  171. if len(fields) != 3 {
  172. continue
  173. }
  174. options := models.PushUpdateOptions{
  175. OldCommitID: string(fields[0]),
  176. NewCommitID: string(fields[1]),
  177. RefFullName: string(fields[2]),
  178. PusherID: com.StrTo(os.Getenv(http.ENV_AUTH_USER_ID)).MustInt64(),
  179. PusherName: os.Getenv(http.ENV_AUTH_USER_NAME),
  180. RepoUserName: os.Getenv(http.ENV_REPO_OWNER_NAME),
  181. RepoName: os.Getenv(http.ENV_REPO_NAME),
  182. }
  183. if err := models.PushUpdate(options); err != nil {
  184. log.Error(2, "PushUpdate: %v", err)
  185. }
  186. // Ask for running deliver hook and test pull request tasks.
  187. reqURL := setting.LocalURL + options.RepoUserName + "/" + options.RepoName + "/tasks/trigger?branch=" +
  188. strings.TrimPrefix(options.RefFullName, git.BRANCH_PREFIX) +
  189. "&secret=" + os.Getenv(http.ENV_REPO_OWNER_SALT_MD5) +
  190. "&pusher=" + os.Getenv(http.ENV_AUTH_USER_ID)
  191. log.Trace("Trigger task: %s", reqURL)
  192. resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
  193. InsecureSkipVerify: true,
  194. }).Response()
  195. if err == nil {
  196. resp.Body.Close()
  197. if resp.StatusCode/100 != 2 {
  198. log.Error(2, "Fail to trigger task: not 2xx response code")
  199. }
  200. } else {
  201. log.Error(2, "Fail to trigger task: %v", err)
  202. }
  203. }
  204. customHooksPath := filepath.Join(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), "post-receive")
  205. if !com.IsFile(customHooksPath) {
  206. return nil
  207. }
  208. hookCmd := exec.Command(customHooksPath)
  209. hookCmd.Dir = models.RepoPath(os.Getenv(http.ENV_REPO_OWNER_NAME), os.Getenv(http.ENV_REPO_NAME))
  210. hookCmd.Stdout = os.Stdout
  211. hookCmd.Stdin = buf
  212. hookCmd.Stderr = os.Stderr
  213. if err := hookCmd.Run(); err != nil {
  214. fail("Internal error", "Fail to execute custom post-receive hook: %v", err)
  215. }
  216. return nil
  217. }