You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

hooks.go 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Copyright 2020 The Gitea 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 repository
  5. import (
  6. "context"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "github.com/unknwon/com"
  15. "xorm.io/builder"
  16. )
  17. const (
  18. SIZE_LIMIT_SCRIPT_NAME = "size_limit"
  19. )
  20. func getHookTemplates() (hookNames, hookTpls, giteaHookTpls, sizeLimitTpls []string) {
  21. hookNames = []string{"pre-receive", "update", "post-receive"}
  22. hookTpls = []string{
  23. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" && test -f \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  24. fmt.Sprintf("#!/usr/bin/env %s\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" && test -f \"${hook}\" || continue\n\"${hook}\" $1 $2 $3\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  25. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" && test -f \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  26. }
  27. giteaHookTpls = []string{
  28. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  29. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  30. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  31. }
  32. sizeLimitTpls = []string{
  33. fmt.Sprintf("#!/usr/bin/env %s\n\n\nset -o pipefail\n\nreadonly DEFAULT_FILE_MAXSIZE_MB=\"30\" \nreadonly CONFIG_NAME=\"hooks.maxfilesize\"\nreadonly NULLSHA=\"0000000000000000000000000000000000000000\"\nreadonly EXIT_SUCCESS=0\nreadonly EXIT_FAILURE=1\nreadonly DEFAULT_REPO_MAXSIZE_MB=\"1024\" \nreadonly CHECK_FLAG_ON=1\n\n\nstatus=\"$EXIT_SUCCESS\"\n\n# skip this hook entirely if shell check is not open\ncheck_flag=${PUSH_SIZE_CHECK_FLAG}\nif [[ $check_flag != $CHECK_FLAG_ON ]]; then\nexit $EXIT_SUCCESS\nfi\n\n\n#######################################\n# check the file max size limit\n#######################################\n\n# get maximum filesize (from repository-specific config)\nmaxsize_mb=\"${REPO_MAX_FILE_SIZE}\"\n\nif [[ \"$?\" != $EXIT_SUCCESS ]]; then\necho \"failed to get ${CONFIG_NAME} from config\"\nexit \"$EXIT_FAILURE\"\nfi\n\npush_size=\"0\"\n# read lines from stdin (format: \"<oldref> <newref> <refname>\\n\")\nwhile read oldref newref refname; do\n# skip branch deletions\nif [[ \"$newref\" == \"$NULLSHA\" ]]; then\n continue\nfi\n\n# find large objects\n# check all objects from $oldref (possible $NULLSHA) to $newref, but\n# skip all objects that have already been accepted (i.e. are referenced by\n# another branch or tag).\n\nnew_branch_flag=0\nif [[ \"$oldref\" == \"$NULLSHA\" ]]; then\n target=\"$newref\"\n new_branch_flag=1\n echo \"You are creating a new remote branch,openI will check all files in commit history to find oversize files\"\nelse\n target=\"${oldref}..${newref}\"\nfi\nmaxsize=`expr $maxsize_mb \\* 1048576` \n\n# find objects in this push_size\n# print like:\n# 08da8e2ab9ae4095bf94dd71ac913132b880b463 commit 214\n# 43e993b768ede5740e8c65de2ed6edec25053ea1 tree 185\n# 4476971d76569039df7569af1b8d03c288f6b193 blob 20167318 b0417e6593a1.zip\nfiles=\"$(git rev-list --objects \"$target\" | \\\n git cat-file $'--batch-check=%%(objectname) %%(objecttype) %%(objectsize) %%(rest)' | \\\n awk -F ' ' -v maxbytes=\"$maxsize\" 'BEGIN {totalIn=0} {if( $3 > maxbytes && $2 == \"blob\") { totalIn+=$3; print $4} else { totalIn+=$3}} END { printf (\"totalIn=\\t%%s\",totalIn)}' )\"\n \nif [[ \"$?\" != $EXIT_SUCCESS ]]; then\n echo \"failed to check for large files in ref ${refname}\"\n continue\nfi\n\nIFS=$'\\n'\n# rewrite IFS to seperate line in $files\nfor file in $files; do\n # if don't unset IFS,temp_array=(${file}) will get error answer\n \n if [[ ${file} == totalIn=* ]]; then\n\tIFS=$'\\t'\n\ttemp_array=(${file})\n\tpush_size=${temp_array[1]}\n\tcontinue\n fi\n\tunset IFS\n if [[ \"$status\" == $EXIT_SUCCESS ]]; then\n\t\techo -e \"Error: Your push was rejected because it contains files larger than $(numfmt --to=iec \"$maxsize_mb\") Mb\"\n\t\techo \"help document -- https://openi.pcl.ac.cn/zeizei/OpenI_Learning/src/branch/master/docs/git/repository_capacity_help.md\"\n\t\techo \"oversize files:\"\n\t\tstatus=\"$EXIT_FAILURE\"\t\n fi\n echo -e \"\\033[31m- ${file}\\033[0m \"\ndone\n\nif [[ \"$status\" != $EXIT_SUCCESS ]]; then\n\texit \"$status\"\nfi\n\ndone\n\n#######################################\n# check the repo max size limit\n#######################################\nif [[ $push_size -eq \"0\" ]]; then\n\texit $EXIT_SUCCESS\nfi\n\n# if create new branch or tag,use count-objects -v to get pack size\nif [[ $new_branch_flag -eq 1 ]]; then\n size_kb=`git count-objects -v | grep 'size-pack' | sed 's/.*\\(size-pack:\\).//'`\n size_pack_kb=`git count-objects -v | grep 'size:' | sed 's/.*\\(size:\\).//'`\n\ttotal_kb=`expr $size_kb + $size_pack_kb`\n\tlet push_size=$total_kb*1024\nfi\n\nsizelimit_mb=\"${REPO_MAX_SIZE}\"\nlet sizelimit_b=$sizelimit_mb*1024*1024\n\n# repo size at here means the size of repo directory in server \nreposize_b=${REPO_CURRENT_SIZE}\n\ntotal=`expr $push_size + $reposize_b`\n\nif [ $total -gt $sizelimit_b ]; then\n echo \"Error: Your push was rejected because the repository size is large than $sizelimit_mb Mb\"\n echo \"see the help document--https://openi.pcl.ac.cn/zeizei/OpenI_Learning/src/branch/master/docs/git/repository_capacity_help.md\"\n exit $EXIT_FAILURE\nfi\n\n\nexit $EXIT_SUCCESS", setting.ScriptType),
  34. fmt.Sprintf(""),
  35. fmt.Sprintf(""),
  36. }
  37. return
  38. }
  39. // CreateDelegateHooks creates all the hooks scripts for the repo
  40. func CreateDelegateHooks(repoPath string) error {
  41. return createDelegateHooks(repoPath)
  42. }
  43. // createDelegateHooks creates all the hooks scripts for the repo
  44. func createDelegateHooks(repoPath string) (err error) {
  45. hookNames, hookTpls, giteaHookTpls, sizeLimitTpls := getHookTemplates()
  46. hookDir := filepath.Join(repoPath, "hooks")
  47. for i, hookName := range hookNames {
  48. oldHookPath := filepath.Join(hookDir, hookName)
  49. newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
  50. if err := os.MkdirAll(filepath.Join(hookDir, hookName+".d"), os.ModePerm); err != nil {
  51. return fmt.Errorf("create hooks dir '%s': %v", filepath.Join(hookDir, hookName+".d"), err)
  52. }
  53. // WARNING: This will override all old server-side hooks
  54. if err = os.Remove(oldHookPath); err != nil && !os.IsNotExist(err) {
  55. return fmt.Errorf("unable to pre-remove old hook file '%s' prior to rewriting: %v ", oldHookPath, err)
  56. }
  57. if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil {
  58. return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
  59. }
  60. if err = ensureExecutable(oldHookPath); err != nil {
  61. return fmt.Errorf("Unable to set %s executable. Error %v", oldHookPath, err)
  62. }
  63. if err = os.Remove(newHookPath); err != nil && !os.IsNotExist(err) {
  64. return fmt.Errorf("unable to pre-remove new hook file '%s' prior to rewriting: %v", newHookPath, err)
  65. }
  66. if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
  67. return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
  68. }
  69. if err = ensureExecutable(newHookPath); err != nil {
  70. return fmt.Errorf("Unable to set %s executable. Error %v", oldHookPath, err)
  71. }
  72. if err = writeHookTpl(generateHookScriptPath(hookDir, hookName, SIZE_LIMIT_SCRIPT_NAME), sizeLimitTpls[i]); err != nil {
  73. return err
  74. }
  75. }
  76. return nil
  77. }
  78. func writeHookTpl(hookPath, content string) error {
  79. if content == "" {
  80. return nil
  81. }
  82. if err := ioutil.WriteFile(hookPath, []byte(content), 0777); err != nil {
  83. return fmt.Errorf("write new hook file '%s': %v", hookPath, err)
  84. }
  85. if err := ensureExecutable(hookPath); err != nil {
  86. return fmt.Errorf("Unable to set %s executable. Error %v", hookPath, err)
  87. }
  88. return nil
  89. }
  90. func checkExecutable(filename string) bool {
  91. fileInfo, err := os.Stat(filename)
  92. if err != nil {
  93. return false
  94. }
  95. return (fileInfo.Mode() & 0100) > 0
  96. }
  97. func ensureExecutable(filename string) error {
  98. fileInfo, err := os.Stat(filename)
  99. if err != nil {
  100. return err
  101. }
  102. if (fileInfo.Mode() & 0100) > 0 {
  103. return nil
  104. }
  105. mode := fileInfo.Mode() | 0100
  106. return os.Chmod(filename, mode)
  107. }
  108. // CheckDelegateHooks checks the hooks scripts for the repo
  109. func CheckDelegateHooks(repoPath string) ([]string, error) {
  110. hookNames, hookTpls, giteaHookTpls, sizeLimitTpls := getHookTemplates()
  111. hookDir := filepath.Join(repoPath, "hooks")
  112. results := make([]string, 0, 10)
  113. for i, hookName := range hookNames {
  114. oldHookPath := filepath.Join(hookDir, hookName)
  115. newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
  116. cont := false
  117. if !com.IsExist(oldHookPath) {
  118. results = append(results, fmt.Sprintf("old hook file %s does not exist", oldHookPath))
  119. cont = true
  120. }
  121. if !com.IsExist(oldHookPath + ".d") {
  122. results = append(results, fmt.Sprintf("hooks directory %s does not exist", oldHookPath+".d"))
  123. cont = true
  124. }
  125. if !com.IsExist(newHookPath) {
  126. results = append(results, fmt.Sprintf("new hook file %s does not exist", newHookPath))
  127. cont = true
  128. }
  129. if cont {
  130. continue
  131. }
  132. contents, err := ioutil.ReadFile(oldHookPath)
  133. if err != nil {
  134. return results, err
  135. }
  136. if string(contents) != hookTpls[i] {
  137. results = append(results, fmt.Sprintf("old hook file %s is out of date", oldHookPath))
  138. }
  139. if !checkExecutable(oldHookPath) {
  140. results = append(results, fmt.Sprintf("old hook file %s is not executable", oldHookPath))
  141. }
  142. contents, err = ioutil.ReadFile(newHookPath)
  143. if err != nil {
  144. return results, err
  145. }
  146. if string(contents) != giteaHookTpls[i] {
  147. results = append(results, fmt.Sprintf("new hook file %s is out of date", newHookPath))
  148. }
  149. if !checkExecutable(newHookPath) {
  150. results = append(results, fmt.Sprintf("new hook file %s is not executable", newHookPath))
  151. }
  152. if err = checkHookFile(generateHookScriptPath(hookDir, hookName, SIZE_LIMIT_SCRIPT_NAME), sizeLimitTpls[i], results); err != nil {
  153. return results, err
  154. }
  155. }
  156. return results, nil
  157. }
  158. func generateHookScriptPath(hookDir, hookName, fileName string) string {
  159. return filepath.Join(hookDir, hookName+".d", fileName)
  160. }
  161. func checkHookFile(filePath, tpl string, results []string) error {
  162. if tpl == "" {
  163. return nil
  164. }
  165. contents, err := ioutil.ReadFile(filePath)
  166. if err != nil {
  167. return err
  168. }
  169. if string(contents) != tpl {
  170. results = append(results, fmt.Sprintf("old hook file %s is out of date", filePath))
  171. }
  172. if !checkExecutable(filePath) {
  173. results = append(results, fmt.Sprintf("old hook file %s is not executable", filePath))
  174. }
  175. return nil
  176. }
  177. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  178. // to make sure the binary and custom conf path are up-to-date.
  179. func SyncRepositoryHooks(ctx context.Context) error {
  180. log.Trace("Doing: SyncRepositoryHooks")
  181. if err := models.Iterate(
  182. models.DefaultDBContext(),
  183. new(models.Repository),
  184. builder.Gt{"id": 0},
  185. func(idx int, bean interface{}) error {
  186. repo := bean.(*models.Repository)
  187. select {
  188. case <-ctx.Done():
  189. return models.ErrCancelledf("before sync repository hooks for %s", repo.FullName())
  190. default:
  191. }
  192. if err := createDelegateHooks(repo.RepoPath()); err != nil {
  193. return fmt.Errorf("SyncRepositoryHook: %v", err)
  194. }
  195. if repo.HasWiki() {
  196. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  197. return fmt.Errorf("SyncRepositoryHook: %v", err)
  198. }
  199. }
  200. return nil
  201. },
  202. ); err != nil {
  203. return err
  204. }
  205. log.Trace("Finished: SyncRepositoryHooks")
  206. return nil
  207. }