serve.go 8.4 KB

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