serve.go 7.9 KB

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