您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. "fmt"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "github.com/Unknwon/com"
  14. "github.com/codegangsta/cli"
  15. "github.com/gogits/gogs/models"
  16. "github.com/gogits/gogs/modules/log"
  17. "github.com/gogits/gogs/modules/setting"
  18. "github.com/gogits/gogs/modules/uuid"
  19. )
  20. var CmdServ = cli.Command{
  21. Name: "serv",
  22. Usage: "This command should only be called by SSH shell",
  23. Description: `Serv provide access auth for repositories`,
  24. Action: runServ,
  25. Flags: []cli.Flag{
  26. cli.StringFlag{"config, c", "custom/conf/app.ini", "Custom configuration file path", ""},
  27. },
  28. }
  29. func setup(logPath string) {
  30. setting.NewConfigContext()
  31. log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
  32. if setting.DisableSSH {
  33. println("Gogs: SSH has been disabled")
  34. os.Exit(1)
  35. }
  36. models.LoadModelsConfig()
  37. if models.UseSQLite3 {
  38. workDir, _ := setting.WorkDir()
  39. os.Chdir(workDir)
  40. }
  41. models.SetEngine()
  42. }
  43. func parseCmd(cmd string) (string, string) {
  44. ss := strings.SplitN(cmd, " ", 2)
  45. if len(ss) != 2 {
  46. return "", ""
  47. }
  48. verb, args := ss[0], ss[1]
  49. if verb == "git" {
  50. ss = strings.SplitN(args, " ", 2)
  51. args = ss[1]
  52. verb = fmt.Sprintf("%s %s", verb, ss[0])
  53. }
  54. return verb, strings.Replace(args, "'/", "'", 1)
  55. }
  56. var (
  57. COMMANDS_READONLY = map[string]models.AccessType{
  58. "git-upload-pack": models.WRITABLE,
  59. "git upload-pack": models.WRITABLE,
  60. "git-upload-archive": models.WRITABLE,
  61. }
  62. COMMANDS_WRITE = map[string]models.AccessType{
  63. "git-receive-pack": models.READABLE,
  64. "git receive-pack": models.READABLE,
  65. }
  66. )
  67. func In(b string, sl map[string]models.AccessType) bool {
  68. _, e := sl[b]
  69. return e
  70. }
  71. func runServ(k *cli.Context) {
  72. if k.IsSet("config") {
  73. setting.CustomConf = k.String("config")
  74. }
  75. setup("serv.log")
  76. keys := strings.Split(os.Args[2], "-")
  77. if len(keys) != 2 {
  78. println("Gogs: auth file format error")
  79. log.GitLogger.Fatal(2, "Invalid auth file format: %s", os.Args[2])
  80. }
  81. keyId, err := com.StrTo(keys[1]).Int64()
  82. if err != nil {
  83. println("Gogs: auth file format error")
  84. log.GitLogger.Fatal(2, "Invalid auth file format: %v", err)
  85. }
  86. user, err := models.GetUserByKeyId(keyId)
  87. if err != nil {
  88. if err == models.ErrUserNotKeyOwner {
  89. println("Gogs: you are not the owner of SSH key")
  90. log.GitLogger.Fatal(2, "Invalid owner of SSH key: %d", keyId)
  91. }
  92. println("Gogs: internal error:", err.Error())
  93. log.GitLogger.Fatal(2, "Fail to get user by key ID(%d): %v", keyId, err)
  94. }
  95. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  96. if cmd == "" {
  97. println("Hi", user.Name, "! You've successfully authenticated, but Gogs does not provide shell access.")
  98. return
  99. }
  100. verb, args := parseCmd(cmd)
  101. repoPath := strings.Trim(args, "'")
  102. rr := strings.SplitN(repoPath, "/", 2)
  103. if len(rr) != 2 {
  104. println("Gogs: unavailable repository", args)
  105. log.GitLogger.Fatal(2, "Unavailable repository: %v", args)
  106. }
  107. repoUserName := rr[0]
  108. repoName := strings.TrimSuffix(rr[1], ".git")
  109. isWrite := In(verb, COMMANDS_WRITE)
  110. isRead := In(verb, COMMANDS_READONLY)
  111. repoUser, err := models.GetUserByName(repoUserName)
  112. if err != nil {
  113. if err == models.ErrUserNotExist {
  114. println("Gogs: given repository owner are not registered")
  115. log.GitLogger.Fatal(2, "Unregistered owner: %s", repoUserName)
  116. }
  117. println("Gogs: internal error:", err.Error())
  118. log.GitLogger.Fatal(2, "Fail to get repository owner(%s): %v", repoUserName, err)
  119. }
  120. // Access check.
  121. switch {
  122. case isWrite:
  123. has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.WRITABLE)
  124. if err != nil {
  125. println("Gogs: internal error:", err.Error())
  126. log.GitLogger.Fatal(2, "Fail to check write access:", err)
  127. } else if !has {
  128. println("You have no right to write this repository")
  129. log.GitLogger.Fatal(2, "User %s has no right to write repository %s", user.Name, repoPath)
  130. }
  131. case isRead:
  132. repo, err := models.GetRepositoryByName(repoUser.Id, repoName)
  133. if err != nil {
  134. if err == models.ErrRepoNotExist {
  135. println("Gogs: given repository does not exist")
  136. log.GitLogger.Fatal(2, "Repository does not exist: %s/%s", repoUser.Name, repoName)
  137. }
  138. println("Gogs: internal error:", err.Error())
  139. log.GitLogger.Fatal(2, "Fail to get repository: %v", err)
  140. }
  141. if !repo.IsPrivate {
  142. break
  143. }
  144. has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.READABLE)
  145. if err != nil {
  146. println("Gogs: internal error:", err.Error())
  147. log.GitLogger.Fatal(2, "Fail to check read access:", err)
  148. } else if !has {
  149. println("You have no right to access this repository")
  150. log.GitLogger.Fatal(2, "User %s has no right to read repository %s", user.Name, repoPath)
  151. }
  152. default:
  153. println("Unknown command: " + cmd)
  154. return
  155. }
  156. uuid := uuid.NewV4().String()
  157. os.Setenv("uuid", uuid)
  158. var gitcmd *exec.Cmd
  159. verbs := strings.Split(verb, " ")
  160. if len(verbs) == 2 {
  161. gitcmd = exec.Command(verbs[0], verbs[1], repoPath)
  162. } else {
  163. gitcmd = exec.Command(verb, repoPath)
  164. }
  165. gitcmd.Dir = setting.RepoRootPath
  166. gitcmd.Stdout = os.Stdout
  167. gitcmd.Stdin = os.Stdin
  168. gitcmd.Stderr = os.Stderr
  169. if err = gitcmd.Run(); err != nil {
  170. println("Gogs: internal error:", err.Error())
  171. log.GitLogger.Fatal(2, "Fail to execute git command: %v", err)
  172. }
  173. if isWrite {
  174. tasks, err := models.GetUpdateTasksByUuid(uuid)
  175. if err != nil {
  176. log.GitLogger.Fatal(2, "GetUpdateTasksByUuid: %v", err)
  177. }
  178. for _, task := range tasks {
  179. err = models.Update(task.RefName, task.OldCommitId, task.NewCommitId,
  180. user.Name, repoUserName, repoName, user.Id)
  181. if err != nil {
  182. log.GitLogger.Error(2, "Fail to update: %v", err)
  183. }
  184. }
  185. if err = models.DelUpdateTasksByUuid(uuid); err != nil {
  186. log.GitLogger.Fatal(2, "DelUpdateTasksByUuid: %v", err)
  187. }
  188. }
  189. // Update key activity.
  190. key, err := models.GetPublicKeyById(keyId)
  191. if err != nil {
  192. log.GitLogger.Fatal(2, "GetPublicKeyById: %v", err)
  193. }
  194. key.Updated = time.Now()
  195. if err = models.UpdatePublicKey(key); err != nil {
  196. log.GitLogger.Fatal(2, "UpdatePublicKey: %v", err)
  197. }
  198. }