hook.go 8.3 KB

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