serve.go 7.9 KB

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