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

212 lines
5.6 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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/filepath"
  10. "strings"
  11. "time"
  12. "github.com/Unknwon/com"
  13. "github.com/codegangsta/cli"
  14. "github.com/gogits/gogs/models"
  15. "github.com/gogits/gogs/modules/httplib"
  16. "github.com/gogits/gogs/modules/log"
  17. "github.com/gogits/gogs/modules/setting"
  18. "github.com/gogits/gogs/modules/uuid"
  19. )
  20. const (
  21. _ACCESS_DENIED_MESSAGE = "Repository does not exist or you do not have access"
  22. )
  23. var CmdServ = cli.Command{
  24. Name: "serv",
  25. Usage: "This command should only be called by SSH shell",
  26. Description: `Serv provide access auth for repositories`,
  27. Action: runServ,
  28. Flags: []cli.Flag{
  29. cli.StringFlag{"config, c", "custom/conf/app.ini", "Custom configuration file path", ""},
  30. },
  31. }
  32. func setup(logPath string) {
  33. setting.NewConfigContext()
  34. log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
  35. if setting.DisableSSH {
  36. println("Gogs: SSH has been disabled")
  37. os.Exit(1)
  38. }
  39. models.LoadModelsConfig()
  40. if setting.UseSQLite3 {
  41. workDir, _ := setting.WorkDir()
  42. os.Chdir(workDir)
  43. }
  44. models.SetEngine()
  45. }
  46. func parseCmd(cmd string) (string, string) {
  47. ss := strings.SplitN(cmd, " ", 2)
  48. if len(ss) != 2 {
  49. return "", ""
  50. }
  51. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  52. }
  53. var (
  54. COMMANDS = map[string]models.AccessMode{
  55. "git-upload-pack": models.ACCESS_MODE_READ,
  56. "git-upload-archive": models.ACCESS_MODE_READ,
  57. "git-receive-pack": models.ACCESS_MODE_WRITE,
  58. }
  59. )
  60. func runServ(c *cli.Context) {
  61. if c.IsSet("config") {
  62. setting.CustomConf = c.String("config")
  63. }
  64. setup("serv.log")
  65. fail := func(userMessage, logMessage string, args ...interface{}) {
  66. fmt.Fprintln(os.Stderr, "Gogs: ", userMessage)
  67. log.GitLogger.Fatal(2, logMessage, args...)
  68. }
  69. if len(c.Args()) < 1 {
  70. fail("Not enough arguments", "Not enough arguments")
  71. }
  72. keys := strings.Split(c.Args()[0], "-")
  73. if len(keys) != 2 {
  74. fail("key-id format error", "Invalid key id: %s", c.Args()[0])
  75. }
  76. keyId, err := com.StrTo(keys[1]).Int64()
  77. if err != nil {
  78. fail("key-id format error", "Invalid key id: %s", err)
  79. }
  80. user, err := models.GetUserByKeyId(keyId)
  81. if err != nil {
  82. fail("internal error", "Failed to get user by key ID(%d): %v", keyId, err)
  83. }
  84. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  85. if cmd == "" {
  86. fmt.Printf("Hi, %s! You've successfully authenticated, but Gogs does not provide shell access.\n", user.Name)
  87. if user.IsAdmin {
  88. println("If this is unexpected, please log in with password and setup Gogs under another user.")
  89. }
  90. return
  91. }
  92. verb, args := parseCmd(cmd)
  93. repoPath := strings.Trim(args, "'")
  94. rr := strings.SplitN(repoPath, "/", 2)
  95. if len(rr) != 2 {
  96. fail("Invalid repository path", "Invalid repository path: %v", args)
  97. }
  98. repoUserName := rr[0]
  99. repoName := strings.TrimSuffix(rr[1], ".git")
  100. repoUser, err := models.GetUserByName(repoUserName)
  101. if err != nil {
  102. if err == models.ErrUserNotExist {
  103. fail("Repository owner does not exist", "Unregistered owner: %s", repoUserName)
  104. }
  105. fail("Internal error", "Failed to get repository owner(%s): %v", repoUserName, err)
  106. }
  107. repo, err := models.GetRepositoryByName(repoUser.Id, repoName)
  108. if err != nil {
  109. if models.IsErrRepoNotExist(err) {
  110. if user.Id == repoUser.Id || repoUser.IsOwnedBy(user.Id) {
  111. fail("Repository does not exist", "Repository does not exist: %s/%s", repoUser.Name, repoName)
  112. } else {
  113. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", repoUser.Name, repoName)
  114. }
  115. }
  116. fail("Internal error", "Failed to get repository: %v", err)
  117. }
  118. requestedMode, has := COMMANDS[verb]
  119. if !has {
  120. fail("Unknown git command", "Unknown git command %s", verb)
  121. }
  122. mode, err := models.AccessLevel(user, repo)
  123. if err != nil {
  124. fail("Internal error", "Fail to check access: %v", err)
  125. } else if mode < requestedMode {
  126. clientMessage := _ACCESS_DENIED_MESSAGE
  127. if mode >= models.ACCESS_MODE_READ {
  128. clientMessage = "You do not have sufficient authorization for this action"
  129. }
  130. fail(clientMessage,
  131. "User %s does not have level %v access to repository %s",
  132. user.Name, requestedMode, repoPath)
  133. }
  134. uuid := uuid.NewV4().String()
  135. os.Setenv("uuid", uuid)
  136. var gitcmd *exec.Cmd
  137. verbs := strings.Split(verb, " ")
  138. if len(verbs) == 2 {
  139. gitcmd = exec.Command(verbs[0], verbs[1], repoPath)
  140. } else {
  141. gitcmd = exec.Command(verb, repoPath)
  142. }
  143. gitcmd.Dir = setting.RepoRootPath
  144. gitcmd.Stdout = os.Stdout
  145. gitcmd.Stdin = os.Stdin
  146. gitcmd.Stderr = os.Stderr
  147. if err = gitcmd.Run(); err != nil {
  148. fail("Internal error", "Failed to execute git command: %v", err)
  149. }
  150. if requestedMode == models.ACCESS_MODE_WRITE {
  151. tasks, err := models.GetUpdateTasksByUuid(uuid)
  152. if err != nil {
  153. log.GitLogger.Fatal(2, "GetUpdateTasksByUuid: %v", err)
  154. }
  155. for _, task := range tasks {
  156. err = models.Update(task.RefName, task.OldCommitId, task.NewCommitId,
  157. user.Name, repoUserName, repoName, user.Id)
  158. if err != nil {
  159. log.GitLogger.Error(2, "Failed to update: %v", err)
  160. }
  161. }
  162. if err = models.DelUpdateTasksByUuid(uuid); err != nil {
  163. log.GitLogger.Fatal(2, "DelUpdateTasksByUuid: %v", err)
  164. }
  165. }
  166. // Send deliver hook request.
  167. resp, err := httplib.Head(setting.AppUrl + setting.AppSubUrl + repoUserName + "/" + repoName + "/hooks/trigger").Response()
  168. if err == nil {
  169. resp.Body.Close()
  170. }
  171. // Update key activity.
  172. key, err := models.GetPublicKeyById(keyId)
  173. if err != nil {
  174. fail("Internal error", "GetPublicKeyById: %v", err)
  175. }
  176. key.Updated = time.Now()
  177. if err = models.UpdatePublicKey(key); err != nil {
  178. fail("Internal error", "UpdatePublicKey: %v", err)
  179. }
  180. }