serve.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 fail(userMessage, logMessage string, args ...interface{}) {
  61. fmt.Fprintln(os.Stderr, "Gogs:", userMessage)
  62. log.GitLogger.Fatal(3, logMessage, args...)
  63. }
  64. func runServ(c *cli.Context) {
  65. if c.IsSet("config") {
  66. setting.CustomConf = c.String("config")
  67. }
  68. setup("serv.log")
  69. if len(c.Args()) < 1 {
  70. fail("Not enough arguments", "Not enough arguments")
  71. }
  72. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  73. if len(cmd) == 0 {
  74. println("Hi there, You've successfully authenticated, but Gogs does not provide shell access.")
  75. println("If this is unexpected, please log in with password and setup Gogs under another user.")
  76. return
  77. }
  78. verb, args := parseCmd(cmd)
  79. repoPath := strings.Trim(args, "'")
  80. rr := strings.SplitN(repoPath, "/", 2)
  81. if len(rr) != 2 {
  82. fail("Invalid repository path", "Invalid repository path: %v", args)
  83. }
  84. repoUserName := rr[0]
  85. repoName := strings.TrimSuffix(rr[1], ".git")
  86. repoUser, err := models.GetUserByName(repoUserName)
  87. if err != nil {
  88. if models.IsErrUserNotExist(err) {
  89. fail("Repository owner does not exist", "Unregistered owner: %s", repoUserName)
  90. }
  91. fail("Internal error", "Failed to get repository owner(%s): %v", repoUserName, err)
  92. }
  93. repo, err := models.GetRepositoryByName(repoUser.Id, repoName)
  94. if err != nil {
  95. if models.IsErrRepoNotExist(err) {
  96. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", repoUser.Name, repoName)
  97. }
  98. fail("Internal error", "Failed to get repository: %v", err)
  99. }
  100. requestedMode, has := COMMANDS[verb]
  101. if !has {
  102. fail("Unknown git command", "Unknown git command %s", verb)
  103. }
  104. // Allow anonymous clone for public repositories.
  105. var (
  106. keyID int64
  107. user *models.User
  108. )
  109. if requestedMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
  110. keys := strings.Split(c.Args()[0], "-")
  111. if len(keys) != 2 {
  112. fail("Key ID format error", "Invalid key ID: %s", c.Args()[0])
  113. }
  114. key, err := models.GetPublicKeyByID(com.StrTo(keys[1]).MustInt64())
  115. if err != nil {
  116. fail("Key ID format error", "Invalid key ID[%s]: %v", c.Args()[0], err)
  117. }
  118. keyID = key.ID
  119. // Check deploy key or user key.
  120. if key.Type == models.KEY_TYPE_DEPLOY {
  121. if key.Mode < requestedMode {
  122. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  123. }
  124. // Check if this deploy key belongs to current repository.
  125. if !models.HasDeployKey(key.ID, repo.ID) {
  126. fail("Key access denied", "Key access denied: %d-%d", key.ID, repo.ID)
  127. }
  128. // Update deploy key activity.
  129. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  130. if err != nil {
  131. fail("Internal error", "GetDeployKey: %v", err)
  132. }
  133. deployKey.Updated = time.Now()
  134. if err = models.UpdateDeployKey(deployKey); err != nil {
  135. fail("Internal error", "UpdateDeployKey: %v", err)
  136. }
  137. } else {
  138. user, err = models.GetUserByKeyId(key.ID)
  139. if err != nil {
  140. fail("internal error", "Failed to get user by key ID(%d): %v", keyID, err)
  141. }
  142. mode, err := models.AccessLevel(user, repo)
  143. if err != nil {
  144. fail("Internal error", "Fail to check access: %v", err)
  145. } else if mode < requestedMode {
  146. clientMessage := _ACCESS_DENIED_MESSAGE
  147. if mode >= models.ACCESS_MODE_READ {
  148. clientMessage = "You do not have sufficient authorization for this action"
  149. }
  150. fail(clientMessage,
  151. "User %s does not have level %v access to repository %s",
  152. user.Name, requestedMode, repoPath)
  153. }
  154. }
  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. fail("Internal error", "Failed to execute git command: %v", err)
  171. }
  172. if requestedMode == models.ACCESS_MODE_WRITE {
  173. tasks, err := models.GetUpdateTasksByUuid(uuid)
  174. if err != nil {
  175. log.GitLogger.Fatal(2, "GetUpdateTasksByUuid: %v", err)
  176. }
  177. for _, task := range tasks {
  178. err = models.Update(task.RefName, task.OldCommitId, task.NewCommitId,
  179. user.Name, repoUserName, repoName, user.Id)
  180. if err != nil {
  181. log.GitLogger.Error(2, "Failed to update: %v", err)
  182. }
  183. }
  184. if err = models.DelUpdateTasksByUuid(uuid); err != nil {
  185. log.GitLogger.Fatal(2, "DelUpdateTasksByUuid: %v", err)
  186. }
  187. }
  188. // Send deliver hook request.
  189. resp, err := httplib.Head(setting.AppUrl + setting.AppSubUrl + repoUserName + "/" + repoName + "/hooks/trigger").Response()
  190. if err == nil {
  191. resp.Body.Close()
  192. }
  193. // Update user key activity.
  194. if keyID > 0 {
  195. key, err := models.GetPublicKeyByID(keyID)
  196. if err != nil {
  197. fail("Internal error", "GetPublicKeyById: %v", err)
  198. }
  199. key.Updated = time.Now()
  200. if err = models.UpdatePublicKey(key); err != nil {
  201. fail("Internal error", "UpdatePublicKey: %v", err)
  202. }
  203. }
  204. }