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.

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