serve.go 7.7 KB

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