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.

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