hook.go 7.7 KB

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