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.

268 lines
7.3 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
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 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. "crypto/tls"
  7. "fmt"
  8. "os"
  9. "os/exec"
  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/httplib"
  17. "github.com/gogits/gogs/modules/log"
  18. "github.com/gogits/gogs/modules/setting"
  19. "github.com/gogits/gogs/modules/uuid"
  20. )
  21. const (
  22. _ACCESS_DENIED_MESSAGE = "Repository does not exist or you do not have access"
  23. )
  24. var CmdServ = cli.Command{
  25. Name: "serv",
  26. Usage: "This command should only be called by SSH shell",
  27. Description: `Serv provide access auth for repositories`,
  28. Action: runServ,
  29. Flags: []cli.Flag{
  30. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  31. },
  32. }
  33. func setup(logPath string) {
  34. setting.NewContext()
  35. log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
  36. if setting.DisableSSH {
  37. println("Gogs: SSH has been disabled")
  38. os.Exit(1)
  39. }
  40. models.LoadConfigs()
  41. if setting.UseSQLite3 || setting.UseTiDB {
  42. workDir, _ := setting.WorkDir()
  43. os.Chdir(workDir)
  44. }
  45. models.SetEngine()
  46. }
  47. func parseCmd(cmd string) (string, string) {
  48. ss := strings.SplitN(cmd, " ", 2)
  49. if len(ss) != 2 {
  50. return "", ""
  51. }
  52. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  53. }
  54. var (
  55. COMMANDS = map[string]models.AccessMode{
  56. "git-upload-pack": models.ACCESS_MODE_READ,
  57. "git-upload-archive": models.ACCESS_MODE_READ,
  58. "git-receive-pack": models.ACCESS_MODE_WRITE,
  59. }
  60. )
  61. func fail(userMessage, logMessage string, args ...interface{}) {
  62. fmt.Fprintln(os.Stderr, "Gogs:", userMessage)
  63. if len(logMessage) > 0 {
  64. log.GitLogger.Fatal(3, logMessage, args...)
  65. return
  66. }
  67. log.GitLogger.Close()
  68. os.Exit(1)
  69. }
  70. func handleUpdateTask(uuid string, user *models.User, repoUserName, repoName string) {
  71. task, err := models.GetUpdateTaskByUUID(uuid)
  72. if err != nil {
  73. if models.IsErrUpdateTaskNotExist(err) {
  74. log.GitLogger.Trace("No update task is presented: %s", uuid)
  75. return
  76. }
  77. log.GitLogger.Fatal(2, "GetUpdateTaskByUUID: %v", err)
  78. }
  79. if err = models.Update(task.RefName, task.OldCommitID, task.NewCommitID,
  80. user.Name, repoUserName, repoName, user.Id); err != nil {
  81. log.GitLogger.Error(2, "Update: %v", err)
  82. }
  83. if err = models.DeleteUpdateTaskByUUID(uuid); err != nil {
  84. log.GitLogger.Fatal(2, "DeleteUpdateTaskByUUID: %v", err)
  85. }
  86. // Ask for running deliver hook and test pull request tasks.
  87. reqURL := setting.AppUrl + repoUserName + "/" + repoName + "/tasks/trigger?branch=" +
  88. strings.TrimPrefix(task.RefName, "refs/heads/")
  89. log.GitLogger.Trace("Trigger task: %s", reqURL)
  90. resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
  91. InsecureSkipVerify: true,
  92. }).Response()
  93. if err == nil {
  94. resp.Body.Close()
  95. if resp.StatusCode/100 != 2 {
  96. log.GitLogger.Error(2, "Fail to trigger task: not 2xx response code")
  97. }
  98. } else {
  99. log.GitLogger.Error(2, "Fail to trigger task: %v", err)
  100. }
  101. }
  102. func runServ(c *cli.Context) {
  103. if c.IsSet("config") {
  104. setting.CustomConf = c.String("config")
  105. }
  106. setup("serv.log")
  107. if len(c.Args()) < 1 {
  108. fail("Not enough arguments", "Not enough arguments")
  109. }
  110. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  111. if len(cmd) == 0 {
  112. println("Hi there, You've successfully authenticated, but Gogs does not provide shell access.")
  113. println("If this is unexpected, please log in with password and setup Gogs under another user.")
  114. return
  115. }
  116. verb, args := parseCmd(cmd)
  117. repoPath := strings.ToLower(strings.Trim(args, "'"))
  118. rr := strings.SplitN(repoPath, "/", 2)
  119. if len(rr) != 2 {
  120. fail("Invalid repository path", "Invalid repository path: %v", args)
  121. }
  122. repoUserName := strings.ToLower(rr[0])
  123. repoName := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))
  124. repoUser, err := models.GetUserByName(repoUserName)
  125. if err != nil {
  126. if models.IsErrUserNotExist(err) {
  127. fail("Repository owner does not exist", "Unregistered owner: %s", repoUserName)
  128. }
  129. fail("Internal error", "Failed to get repository owner(%s): %v", repoUserName, err)
  130. }
  131. repo, err := models.GetRepositoryByName(repoUser.Id, repoName)
  132. if err != nil {
  133. if models.IsErrRepoNotExist(err) {
  134. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", repoUser.Name, repoName)
  135. }
  136. fail("Internal error", "Failed to get repository: %v", err)
  137. }
  138. requestedMode, has := COMMANDS[verb]
  139. if !has {
  140. fail("Unknown git command", "Unknown git command %s", verb)
  141. }
  142. // Prohibit push to mirror repositories.
  143. if requestedMode > models.ACCESS_MODE_READ && repo.IsMirror {
  144. fail("mirror repository is read-only", "")
  145. }
  146. // Allow anonymous clone for public repositories.
  147. var (
  148. keyID int64
  149. user *models.User
  150. )
  151. if requestedMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
  152. keys := strings.Split(c.Args()[0], "-")
  153. if len(keys) != 2 {
  154. fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
  155. }
  156. key, err := models.GetPublicKeyByID(com.StrTo(keys[1]).MustInt64())
  157. if err != nil {
  158. fail("Invalid key ID", "Invalid key ID[%s]: %v", c.Args()[0], err)
  159. }
  160. keyID = key.ID
  161. // Check deploy key or user key.
  162. if key.Type == models.KEY_TYPE_DEPLOY {
  163. if key.Mode < requestedMode {
  164. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  165. }
  166. // Check if this deploy key belongs to current repository.
  167. if !models.HasDeployKey(key.ID, repo.ID) {
  168. fail("Key access denied", "Key access denied: %d-%d", key.ID, repo.ID)
  169. }
  170. // Update deploy key activity.
  171. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  172. if err != nil {
  173. fail("Internal error", "GetDeployKey: %v", err)
  174. }
  175. deployKey.Updated = time.Now()
  176. if err = models.UpdateDeployKey(deployKey); err != nil {
  177. fail("Internal error", "UpdateDeployKey: %v", err)
  178. }
  179. } else {
  180. user, err = models.GetUserByKeyID(key.ID)
  181. if err != nil {
  182. fail("internal error", "Failed to get user by key ID(%d): %v", keyID, err)
  183. }
  184. mode, err := models.AccessLevel(user, repo)
  185. if err != nil {
  186. fail("Internal error", "Fail to check access: %v", err)
  187. } else if mode < requestedMode {
  188. clientMessage := _ACCESS_DENIED_MESSAGE
  189. if mode >= models.ACCESS_MODE_READ {
  190. clientMessage = "You do not have sufficient authorization for this action"
  191. }
  192. fail(clientMessage,
  193. "User %s does not have level %v access to repository %s",
  194. user.Name, requestedMode, repoPath)
  195. }
  196. }
  197. }
  198. uuid := uuid.NewV4().String()
  199. os.Setenv("uuid", uuid)
  200. var gitcmd *exec.Cmd
  201. verbs := strings.Split(verb, " ")
  202. if len(verbs) == 2 {
  203. gitcmd = exec.Command(verbs[0], verbs[1], repoPath)
  204. } else {
  205. gitcmd = exec.Command(verb, repoPath)
  206. }
  207. gitcmd.Dir = setting.RepoRootPath
  208. gitcmd.Stdout = os.Stdout
  209. gitcmd.Stdin = os.Stdin
  210. gitcmd.Stderr = os.Stderr
  211. if err = gitcmd.Run(); err != nil {
  212. fail("Internal error", "Failed to execute git command: %v", err)
  213. }
  214. if requestedMode == models.ACCESS_MODE_WRITE {
  215. handleUpdateTask(uuid, user, repoUserName, repoName)
  216. }
  217. // Update user key activity.
  218. if keyID > 0 {
  219. key, err := models.GetPublicKeyByID(keyID)
  220. if err != nil {
  221. fail("Internal error", "GetPublicKeyById: %v", err)
  222. }
  223. key.Updated = time.Now()
  224. if err = models.UpdatePublicKey(key); err != nil {
  225. fail("Internal error", "UpdatePublicKey: %v", err)
  226. }
  227. }
  228. }