serve.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. "fmt"
  7. "os"
  8. "os/exec"
  9. "path"
  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/log"
  17. "github.com/gogits/gogs/modules/setting"
  18. "github.com/gogits/gogs/modules/uuid"
  19. )
  20. var CmdServ = cli.Command{
  21. Name: "serv",
  22. Usage: "This command should only be called by SSH shell",
  23. Description: `Serv provide access auth for repositories`,
  24. Action: runServ,
  25. Flags: []cli.Flag{
  26. cli.StringFlag{"config, c", "custom/conf/app.ini", "Custom configuration file path", ""},
  27. },
  28. }
  29. func setup(logPath string) {
  30. setting.NewConfigContext()
  31. log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
  32. if setting.DisableSSH {
  33. println("Gogs: SSH has been disabled")
  34. os.Exit(1)
  35. }
  36. models.LoadModelsConfig()
  37. if models.UseSQLite3 {
  38. workDir, _ := setting.WorkDir()
  39. os.Chdir(workDir)
  40. }
  41. models.SetEngine()
  42. }
  43. func parseCmd(cmd string) (string, string) {
  44. ss := strings.SplitN(cmd, " ", 2)
  45. if len(ss) != 2 {
  46. return "", ""
  47. }
  48. verb, args := ss[0], ss[1]
  49. if verb == "git" {
  50. ss = strings.SplitN(args, " ", 2)
  51. args = ss[1]
  52. verb = fmt.Sprintf("%s %s", verb, ss[0])
  53. }
  54. return verb, strings.Replace(args, "'/", "'", 1)
  55. }
  56. var (
  57. COMMANDS_READONLY = map[string]models.AccessType{
  58. "git-upload-pack": models.WRITABLE,
  59. "git upload-pack": models.WRITABLE,
  60. "git-upload-archive": models.WRITABLE,
  61. }
  62. COMMANDS_WRITE = map[string]models.AccessType{
  63. "git-receive-pack": models.READABLE,
  64. "git receive-pack": models.READABLE,
  65. }
  66. )
  67. func In(b string, sl map[string]models.AccessType) bool {
  68. _, e := sl[b]
  69. return e
  70. }
  71. func runServ(k *cli.Context) {
  72. if k.IsSet("config") {
  73. setting.CustomConf = k.String("config")
  74. }
  75. setup("serv.log")
  76. if len(k.Args()) < 1 {
  77. log.GitLogger.Fatal(2, "Not enough arguments")
  78. }
  79. keys := strings.Split(k.Args()[0], "-")
  80. if len(keys) != 2 {
  81. println("Gogs: auth file format error")
  82. log.GitLogger.Fatal(2, "Invalid auth file format: %s", os.Args[2])
  83. }
  84. keyId, err := com.StrTo(keys[1]).Int64()
  85. if err != nil {
  86. println("Gogs: auth file format error")
  87. log.GitLogger.Fatal(2, "Invalid auth file format: %v", err)
  88. }
  89. user, err := models.GetUserByKeyId(keyId)
  90. if err != nil {
  91. if err == models.ErrUserNotKeyOwner {
  92. println("Gogs: you are not the owner of SSH key")
  93. log.GitLogger.Fatal(2, "Invalid owner of SSH key: %d", keyId)
  94. }
  95. println("Gogs: internal error:", err.Error())
  96. log.GitLogger.Fatal(2, "Fail to get user by key ID(%d): %v", keyId, err)
  97. }
  98. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  99. if cmd == "" {
  100. println("Hi", user.Name, "! You've successfully authenticated, but Gogs does not provide shell access.")
  101. return
  102. }
  103. verb, args := parseCmd(cmd)
  104. repoPath := strings.Trim(args, "'")
  105. rr := strings.SplitN(repoPath, "/", 2)
  106. if len(rr) != 2 {
  107. println("Gogs: unavailable repository", args)
  108. log.GitLogger.Fatal(2, "Unavailable repository: %v", args)
  109. }
  110. repoUserName := rr[0]
  111. repoName := strings.TrimSuffix(rr[1], ".git")
  112. isWrite := In(verb, COMMANDS_WRITE)
  113. isRead := In(verb, COMMANDS_READONLY)
  114. repoUser, err := models.GetUserByName(repoUserName)
  115. if err != nil {
  116. if err == models.ErrUserNotExist {
  117. println("Gogs: given repository owner are not registered")
  118. log.GitLogger.Fatal(2, "Unregistered owner: %s", repoUserName)
  119. }
  120. println("Gogs: internal error:", err.Error())
  121. log.GitLogger.Fatal(2, "Fail to get repository owner(%s): %v", repoUserName, err)
  122. }
  123. // Access check.
  124. switch {
  125. case isWrite:
  126. has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.WRITABLE)
  127. if err != nil {
  128. println("Gogs: internal error:", err.Error())
  129. log.GitLogger.Fatal(2, "Fail to check write access:", err)
  130. } else if !has {
  131. println("You have no right to write this repository")
  132. log.GitLogger.Fatal(2, "User %s has no right to write repository %s", user.Name, repoPath)
  133. }
  134. case isRead:
  135. repo, err := models.GetRepositoryByName(repoUser.Id, repoName)
  136. if err != nil {
  137. if err == models.ErrRepoNotExist {
  138. println("Gogs: given repository does not exist")
  139. log.GitLogger.Fatal(2, "Repository does not exist: %s/%s", repoUser.Name, repoName)
  140. }
  141. println("Gogs: internal error:", err.Error())
  142. log.GitLogger.Fatal(2, "Fail to get repository: %v", err)
  143. }
  144. if !repo.IsPrivate {
  145. break
  146. }
  147. has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.READABLE)
  148. if err != nil {
  149. println("Gogs: internal error:", err.Error())
  150. log.GitLogger.Fatal(2, "Fail to check read access:", err)
  151. } else if !has {
  152. println("You have no right to access this repository")
  153. log.GitLogger.Fatal(2, "User %s has no right to read repository %s", user.Name, repoPath)
  154. }
  155. default:
  156. println("Unknown command: " + cmd)
  157. return
  158. }
  159. uuid := uuid.NewV4().String()
  160. os.Setenv("uuid", uuid)
  161. var gitcmd *exec.Cmd
  162. verbs := strings.Split(verb, " ")
  163. if len(verbs) == 2 {
  164. gitcmd = exec.Command(verbs[0], verbs[1], repoPath)
  165. } else {
  166. gitcmd = exec.Command(verb, repoPath)
  167. }
  168. gitcmd.Dir = setting.RepoRootPath
  169. gitcmd.Stdout = os.Stdout
  170. gitcmd.Stdin = os.Stdin
  171. gitcmd.Stderr = os.Stderr
  172. if err = gitcmd.Run(); err != nil {
  173. println("Gogs: internal error:", err.Error())
  174. log.GitLogger.Fatal(2, "Fail to execute git command: %v", err)
  175. }
  176. if isWrite {
  177. tasks, err := models.GetUpdateTasksByUuid(uuid)
  178. if err != nil {
  179. log.GitLogger.Fatal(2, "GetUpdateTasksByUuid: %v", err)
  180. }
  181. for _, task := range tasks {
  182. err = models.Update(task.RefName, task.OldCommitId, task.NewCommitId,
  183. user.Name, repoUserName, repoName, user.Id)
  184. if err != nil {
  185. log.GitLogger.Error(2, "Fail to update: %v", err)
  186. }
  187. }
  188. if err = models.DelUpdateTasksByUuid(uuid); err != nil {
  189. log.GitLogger.Fatal(2, "DelUpdateTasksByUuid: %v", err)
  190. }
  191. }
  192. // Update key activity.
  193. key, err := models.GetPublicKeyById(keyId)
  194. if err != nil {
  195. log.GitLogger.Fatal(2, "GetPublicKeyById: %v", err)
  196. }
  197. key.Updated = time.Now()
  198. if err = models.UpdatePublicKey(key); err != nil {
  199. log.GitLogger.Fatal(2, "UpdatePublicKey: %v", err)
  200. }
  201. }