hook.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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/modules/httplib"
  20. "github.com/gogits/gogs/modules/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. // Check if whitelist is enabled
  90. userID := com.StrTo(os.Getenv(http.ENV_AUTH_USER_ID)).MustInt64()
  91. if protectBranch.EnableWhitelist && !models.IsUserInProtectBranchWhitelist(repoID, userID, branchName) {
  92. fail(fmt.Sprintf("Branch '%s' is protected and you are not in the push whitelist", branchName), "")
  93. }
  94. // Check if branch allows direct push
  95. if protectBranch.RequirePullRequest {
  96. fail(fmt.Sprintf("Branch '%s' is protected and commits must be merged through pull request", branchName), "")
  97. }
  98. // check and deletion
  99. if newCommitID == git.EMPTY_SHA {
  100. fail(fmt.Sprintf("Branch '%s' is protected from deletion", branchName), "")
  101. }
  102. // Check force push
  103. output, err := git.NewCommand("rev-list", oldCommitID, "^"+newCommitID).
  104. RunInDir(models.RepoPath(os.Getenv(http.ENV_REPO_OWNER_NAME), os.Getenv(http.ENV_REPO_NAME)))
  105. if err != nil {
  106. fail("Internal error", "Fail to detect force push: %v", err)
  107. } else if len(output) > 0 {
  108. fail(fmt.Sprintf("Branch '%s' is protected from force push", branchName), "")
  109. }
  110. }
  111. customHooksPath := filepath.Join(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), "pre-receive")
  112. if !com.IsFile(customHooksPath) {
  113. return nil
  114. }
  115. hookCmd := exec.Command(customHooksPath)
  116. hookCmd.Dir = models.RepoPath(os.Getenv(http.ENV_REPO_OWNER_NAME), os.Getenv(http.ENV_REPO_NAME))
  117. hookCmd.Stdout = os.Stdout
  118. hookCmd.Stdin = buf
  119. hookCmd.Stderr = os.Stderr
  120. if err := hookCmd.Run(); err != nil {
  121. fail("Internal error", "Fail to execute custom pre-receive hook: %v", err)
  122. }
  123. return nil
  124. }
  125. func runHookUpdate(c *cli.Context) error {
  126. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  127. return nil
  128. }
  129. setup(c, "hooks/update.log", false)
  130. args := c.Args()
  131. if len(args) != 3 {
  132. fail("Arguments received are not equal to three", "Arguments received are not equal to three")
  133. } else if len(args[0]) == 0 {
  134. fail("First argument 'refName' is empty", "First argument 'refName' is empty")
  135. }
  136. customHooksPath := filepath.Join(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), "update")
  137. if !com.IsFile(customHooksPath) {
  138. return nil
  139. }
  140. hookCmd := exec.Command(customHooksPath, args...)
  141. hookCmd.Dir = models.RepoPath(os.Getenv(http.ENV_REPO_OWNER_NAME), os.Getenv(http.ENV_REPO_NAME))
  142. hookCmd.Stdout = os.Stdout
  143. hookCmd.Stdin = os.Stdin
  144. hookCmd.Stderr = os.Stderr
  145. if err := hookCmd.Run(); err != nil {
  146. fail("Internal error", "Fail to execute custom pre-receive hook: %v", err)
  147. }
  148. return nil
  149. }
  150. func runHookPostReceive(c *cli.Context) error {
  151. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  152. return nil
  153. }
  154. setup(c, "hooks/post-receive.log", true)
  155. isWiki := strings.Contains(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/")
  156. buf := bytes.NewBuffer(nil)
  157. scanner := bufio.NewScanner(os.Stdin)
  158. for scanner.Scan() {
  159. buf.Write(scanner.Bytes())
  160. buf.WriteByte('\n')
  161. // TODO: support news feeds for wiki
  162. if isWiki {
  163. continue
  164. }
  165. fields := bytes.Fields(scanner.Bytes())
  166. if len(fields) != 3 {
  167. continue
  168. }
  169. options := models.PushUpdateOptions{
  170. OldCommitID: string(fields[0]),
  171. NewCommitID: string(fields[1]),
  172. RefFullName: string(fields[2]),
  173. PusherID: com.StrTo(os.Getenv(http.ENV_AUTH_USER_ID)).MustInt64(),
  174. PusherName: os.Getenv(http.ENV_AUTH_USER_NAME),
  175. RepoUserName: os.Getenv(http.ENV_REPO_OWNER_NAME),
  176. RepoName: os.Getenv(http.ENV_REPO_NAME),
  177. }
  178. if err := models.PushUpdate(options); err != nil {
  179. log.Error(2, "PushUpdate: %v", err)
  180. }
  181. // Ask for running deliver hook and test pull request tasks.
  182. reqURL := setting.LocalURL + options.RepoUserName + "/" + options.RepoName + "/tasks/trigger?branch=" +
  183. strings.TrimPrefix(options.RefFullName, git.BRANCH_PREFIX) +
  184. "&secret=" + os.Getenv(http.ENV_REPO_OWNER_SALT_MD5) +
  185. "&pusher=" + os.Getenv(http.ENV_AUTH_USER_ID)
  186. log.Trace("Trigger task: %s", reqURL)
  187. resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
  188. InsecureSkipVerify: true,
  189. }).Response()
  190. if err == nil {
  191. resp.Body.Close()
  192. if resp.StatusCode/100 != 2 {
  193. log.Error(2, "Fail to trigger task: not 2xx response code")
  194. }
  195. } else {
  196. log.Error(2, "Fail to trigger task: %v", err)
  197. }
  198. }
  199. customHooksPath := filepath.Join(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), "post-receive")
  200. if !com.IsFile(customHooksPath) {
  201. return nil
  202. }
  203. hookCmd := exec.Command(customHooksPath)
  204. hookCmd.Dir = models.RepoPath(os.Getenv(http.ENV_REPO_OWNER_NAME), os.Getenv(http.ENV_REPO_NAME))
  205. hookCmd.Stdout = os.Stdout
  206. hookCmd.Stdin = buf
  207. hookCmd.Stderr = os.Stderr
  208. if err := hookCmd.Run(); err != nil {
  209. fail("Internal error", "Fail to execute custom post-receive hook: %v", err)
  210. }
  211. return nil
  212. }