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.

284 lines
7.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
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
9 years ago
9 years ago
9 years ago
9 years ago
9 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
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 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
9 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. allowedCommands = 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. if !setting.ProdMode {
  65. fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
  66. }
  67. log.GitLogger.Fatal(3, logMessage, args...)
  68. return
  69. }
  70. log.GitLogger.Close()
  71. os.Exit(1)
  72. }
  73. func handleUpdateTask(uuid string, user *models.User, username, reponame string, isWiki bool) {
  74. task, err := models.GetUpdateTaskByUUID(uuid)
  75. if err != nil {
  76. if models.IsErrUpdateTaskNotExist(err) {
  77. log.GitLogger.Trace("No update task is presented: %s", uuid)
  78. return
  79. }
  80. log.GitLogger.Fatal(2, "GetUpdateTaskByUUID: %v", err)
  81. } else if err = models.DeleteUpdateTaskByUUID(uuid); err != nil {
  82. log.GitLogger.Fatal(2, "DeleteUpdateTaskByUUID: %v", err)
  83. }
  84. if isWiki {
  85. return
  86. }
  87. if err = models.Update(task.RefName, task.OldCommitID, task.NewCommitID,
  88. user.Name, username, reponame, user.Id); err != nil {
  89. log.GitLogger.Error(2, "Update: %v", err)
  90. }
  91. // Ask for running deliver hook and test pull request tasks.
  92. reqURL := setting.AppUrl + username + "/" + reponame + "/tasks/trigger?branch=" +
  93. strings.TrimPrefix(task.RefName, "refs/heads/")
  94. log.GitLogger.Trace("Trigger task: %s", reqURL)
  95. resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
  96. InsecureSkipVerify: true,
  97. }).Response()
  98. if err == nil {
  99. resp.Body.Close()
  100. if resp.StatusCode/100 != 2 {
  101. log.GitLogger.Error(2, "Fail to trigger task: not 2xx response code")
  102. }
  103. } else {
  104. log.GitLogger.Error(2, "Fail to trigger task: %v", err)
  105. }
  106. }
  107. func runServ(c *cli.Context) {
  108. if c.IsSet("config") {
  109. setting.CustomConf = c.String("config")
  110. }
  111. setup("serv.log")
  112. if len(c.Args()) < 1 {
  113. fail("Not enough arguments", "Not enough arguments")
  114. }
  115. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  116. if len(cmd) == 0 {
  117. println("Hi there, You've successfully authenticated, but Gogs does not provide shell access.")
  118. println("If this is unexpected, please log in with password and setup Gogs under another user.")
  119. return
  120. }
  121. verb, args := parseCmd(cmd)
  122. repoPath := strings.ToLower(strings.Trim(args, "'"))
  123. rr := strings.SplitN(repoPath, "/", 2)
  124. if len(rr) != 2 {
  125. fail("Invalid repository path", "Invalid repository path: %v", args)
  126. }
  127. username := strings.ToLower(rr[0])
  128. reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))
  129. isWiki := false
  130. if strings.HasSuffix(reponame, ".wiki") {
  131. isWiki = true
  132. reponame = reponame[:len(reponame)-5]
  133. }
  134. repoUser, err := models.GetUserByName(username)
  135. if err != nil {
  136. if models.IsErrUserNotExist(err) {
  137. fail("Repository owner does not exist", "Unregistered owner: %s", username)
  138. }
  139. fail("Internal error", "Failed to get repository owner(%s): %v", username, err)
  140. }
  141. repo, err := models.GetRepositoryByName(repoUser.Id, reponame)
  142. if err != nil {
  143. if models.IsErrRepoNotExist(err) {
  144. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", repoUser.Name, reponame)
  145. }
  146. fail("Internal error", "Failed to get repository: %v", err)
  147. }
  148. requestedMode, has := allowedCommands[verb]
  149. if !has {
  150. fail("Unknown git command", "Unknown git command %s", verb)
  151. }
  152. // Prohibit push to mirror repositories.
  153. if requestedMode > models.ACCESS_MODE_READ && repo.IsMirror {
  154. fail("mirror repository is read-only", "")
  155. }
  156. // Allow anonymous clone for public repositories.
  157. var (
  158. keyID int64
  159. user *models.User
  160. )
  161. if requestedMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
  162. keys := strings.Split(c.Args()[0], "-")
  163. if len(keys) != 2 {
  164. fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
  165. }
  166. key, err := models.GetPublicKeyByID(com.StrTo(keys[1]).MustInt64())
  167. if err != nil {
  168. fail("Invalid key ID", "Invalid key ID[%s]: %v", c.Args()[0], err)
  169. }
  170. keyID = key.ID
  171. // Check deploy key or user key.
  172. if key.Type == models.KEY_TYPE_DEPLOY {
  173. if key.Mode < requestedMode {
  174. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  175. }
  176. // Check if this deploy key belongs to current repository.
  177. if !models.HasDeployKey(key.ID, repo.ID) {
  178. fail("Key access denied", "Key access denied: %d-%d", key.ID, repo.ID)
  179. }
  180. // Update deploy key activity.
  181. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  182. if err != nil {
  183. fail("Internal error", "GetDeployKey: %v", err)
  184. }
  185. deployKey.Updated = time.Now()
  186. if err = models.UpdateDeployKey(deployKey); err != nil {
  187. fail("Internal error", "UpdateDeployKey: %v", err)
  188. }
  189. } else {
  190. user, err = models.GetUserByKeyID(key.ID)
  191. if err != nil {
  192. fail("internal error", "Failed to get user by key ID(%d): %v", keyID, err)
  193. }
  194. mode, err := models.AccessLevel(user, repo)
  195. if err != nil {
  196. fail("Internal error", "Fail to check access: %v", err)
  197. } else if mode < requestedMode {
  198. clientMessage := _ACCESS_DENIED_MESSAGE
  199. if mode >= models.ACCESS_MODE_READ {
  200. clientMessage = "You do not have sufficient authorization for this action"
  201. }
  202. fail(clientMessage,
  203. "User %s does not have level %v access to repository %s",
  204. user.Name, requestedMode, repoPath)
  205. }
  206. }
  207. }
  208. uuid := uuid.NewV4().String()
  209. os.Setenv("uuid", uuid)
  210. // Special handle for Windows.
  211. if setting.IsWindows {
  212. verb = strings.Replace(verb, "-", " ", 1)
  213. }
  214. var gitcmd *exec.Cmd
  215. verbs := strings.Split(verb, " ")
  216. if len(verbs) == 2 {
  217. gitcmd = exec.Command(verbs[0], verbs[1], repoPath)
  218. } else {
  219. gitcmd = exec.Command(verb, repoPath)
  220. }
  221. gitcmd.Dir = setting.RepoRootPath
  222. gitcmd.Stdout = os.Stdout
  223. gitcmd.Stdin = os.Stdin
  224. gitcmd.Stderr = os.Stderr
  225. if err = gitcmd.Run(); err != nil {
  226. fail("Internal error", "Failed to execute git command: %v", err)
  227. }
  228. if requestedMode == models.ACCESS_MODE_WRITE {
  229. handleUpdateTask(uuid, user, username, reponame, isWiki)
  230. }
  231. // Update user key activity.
  232. if keyID > 0 {
  233. key, err := models.GetPublicKeyByID(keyID)
  234. if err != nil {
  235. fail("Internal error", "GetPublicKeyById: %v", err)
  236. }
  237. key.Updated = time.Now()
  238. if err = models.UpdatePublicKey(key); err != nil {
  239. fail("Internal error", "UpdatePublicKey: %v", err)
  240. }
  241. }
  242. }