serve.go 8.7 KB

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