serve.go 6.8 KB

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