serve.go 6.1 KB

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