hook.go 8.3 KB

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