serv.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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/gogits/git-module"
  15. gouuid "github.com/satori/go.uuid"
  16. "github.com/urfave/cli"
  17. log "gopkg.in/clog.v1"
  18. "github.com/gogits/gogs/models"
  19. "github.com/gogits/gogs/modules/base"
  20. "github.com/gogits/gogs/modules/httplib"
  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. _ENV_UPDATE_TASK_UUID = "UPDATE_TASK_UUID"
  26. _ENV_REPO_CUSTOM_HOOKS_PATH = "REPO_CUSTOM_HOOKS_PATH"
  27. )
  28. var Serv = cli.Command{
  29. Name: "serv",
  30. Usage: "This command should only be called by SSH shell",
  31. Description: `Serv provide access auth for repositories`,
  32. Action: runServ,
  33. Flags: []cli.Flag{
  34. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  35. },
  36. }
  37. func setup(c *cli.Context, logPath string) {
  38. if c.IsSet("config") {
  39. setting.CustomConf = c.String("config")
  40. } else if c.GlobalIsSet("config") {
  41. setting.CustomConf = c.GlobalString("config")
  42. }
  43. setting.NewContext()
  44. setting.NewService()
  45. log.New(log.FILE, log.FileConfig{
  46. Filename: filepath.Join(setting.LogRootPath, logPath),
  47. FileRotationConfig: log.FileRotationConfig{
  48. Rotate: true,
  49. Daily: true,
  50. MaxDays: 3,
  51. },
  52. })
  53. log.Delete(log.CONSOLE) // Remove primary logger
  54. models.LoadConfigs()
  55. if setting.UseSQLite3 {
  56. workDir, _ := setting.WorkDir()
  57. os.Chdir(workDir)
  58. }
  59. models.SetEngine()
  60. }
  61. func parseSSHCmd(cmd string) (string, string) {
  62. ss := strings.SplitN(cmd, " ", 2)
  63. if len(ss) != 2 {
  64. return "", ""
  65. }
  66. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  67. }
  68. func checkDeployKey(key *models.PublicKey, repo *models.Repository) {
  69. // Check if this deploy key belongs to current repository.
  70. if !models.HasDeployKey(key.ID, repo.ID) {
  71. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  72. }
  73. // Update deploy key activity.
  74. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  75. if err != nil {
  76. fail("Internal error", "GetDeployKey: %v", err)
  77. }
  78. deployKey.Updated = time.Now()
  79. if err = models.UpdateDeployKey(deployKey); err != nil {
  80. fail("Internal error", "UpdateDeployKey: %v", err)
  81. }
  82. }
  83. var (
  84. allowedCommands = map[string]models.AccessMode{
  85. "git-upload-pack": models.ACCESS_MODE_READ,
  86. "git-upload-archive": models.ACCESS_MODE_READ,
  87. "git-receive-pack": models.ACCESS_MODE_WRITE,
  88. }
  89. )
  90. func fail(userMessage, logMessage string, args ...interface{}) {
  91. fmt.Fprintln(os.Stderr, "Gogs:", userMessage)
  92. if len(logMessage) > 0 {
  93. if !setting.ProdMode {
  94. fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
  95. }
  96. log.Fatal(3, logMessage, args...)
  97. }
  98. log.Shutdown()
  99. os.Exit(1)
  100. }
  101. func handleUpdateTask(uuid string, user, repoUser *models.User, reponame string, isWiki bool) {
  102. task, err := models.GetUpdateTaskByUUID(uuid)
  103. if err != nil {
  104. if models.IsErrUpdateTaskNotExist(err) {
  105. log.Trace("No update task is presented: %s", uuid)
  106. return
  107. }
  108. log.Fatal(2, "GetUpdateTaskByUUID: %v", err)
  109. } else if err = models.DeleteUpdateTaskByUUID(uuid); err != nil {
  110. log.Fatal(2, "DeleteUpdateTaskByUUID: %v", err)
  111. }
  112. if isWiki {
  113. return
  114. }
  115. if err = models.PushUpdate(models.PushUpdateOptions{
  116. RefFullName: task.RefName,
  117. OldCommitID: task.OldCommitID,
  118. NewCommitID: task.NewCommitID,
  119. PusherID: user.ID,
  120. PusherName: user.Name,
  121. RepoUserName: repoUser.Name,
  122. RepoName: reponame,
  123. }); err != nil {
  124. log.Error(2, "Update: %v", err)
  125. }
  126. // Ask for running deliver hook and test pull request tasks.
  127. reqURL := setting.LocalURL + repoUser.Name + "/" + reponame + "/tasks/trigger?branch=" +
  128. strings.TrimPrefix(task.RefName, git.BRANCH_PREFIX) + "&secret=" + base.EncodeMD5(repoUser.Salt) + "&pusher=" + com.ToStr(user.ID)
  129. log.Trace("Trigger task: %s", reqURL)
  130. resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
  131. InsecureSkipVerify: true,
  132. }).Response()
  133. if err == nil {
  134. resp.Body.Close()
  135. if resp.StatusCode/100 != 2 {
  136. log.Error(2, "Fail to trigger task: not 2xx response code")
  137. }
  138. } else {
  139. log.Error(2, "Fail to trigger task: %v", err)
  140. }
  141. }
  142. func runServ(c *cli.Context) error {
  143. setup(c, "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. sshCmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  152. if len(sshCmd) == 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 := parseSSHCmd(sshCmd)
  158. repoFullName := strings.ToLower(strings.Trim(args, "'"))
  159. repoFields := strings.SplitN(repoFullName, "/", 2)
  160. if len(repoFields) != 2 {
  161. fail("Invalid repository path", "Invalid repository path: %v", args)
  162. }
  163. username := strings.ToLower(repoFields[0])
  164. reponame := strings.ToLower(strings.TrimSuffix(repoFields[1], ".git"))
  165. isWiki := false
  166. if strings.HasSuffix(reponame, ".wiki") {
  167. isWiki = true
  168. reponame = reponame[:len(reponame)-5]
  169. }
  170. repoOwner, 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", "Fail to get repository owner '%s': %v", username, err)
  176. }
  177. repo, err := models.GetRepositoryByName(repoOwner.ID, reponame)
  178. if err != nil {
  179. if models.IsErrRepoNotExist(err) {
  180. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", repoOwner.Name, reponame)
  181. }
  182. fail("Internal error", "Fail to get repository: %v", err)
  183. }
  184. repo.Owner = repoOwner
  185. requestMode, ok := allowedCommands[verb]
  186. if !ok {
  187. fail("Unknown git command", "Unknown git command '%s'", verb)
  188. }
  189. // Prohibit push to mirror repositories.
  190. if requestMode > models.ACCESS_MODE_READ && repo.IsMirror {
  191. fail("mirror repository is read-only", "")
  192. }
  193. // Allow anonymous (user is nil) clone for public repositories.
  194. var user *models.User
  195. key, err := models.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
  196. if err != nil {
  197. fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
  198. }
  199. if requestMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
  200. // Check deploy key or user key.
  201. if key.IsDeployKey() {
  202. if key.Mode < requestMode {
  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", "Fail to get user by key ID '%d': %v", key.ID, err)
  210. }
  211. mode, err := models.AccessLevel(user, repo)
  212. if err != nil {
  213. fail("Internal error", "Fail to check access: %v", err)
  214. }
  215. if mode < requestMode {
  216. clientMessage := _ACCESS_DENIED_MESSAGE
  217. if mode >= models.ACCESS_MODE_READ {
  218. clientMessage = "You do not have sufficient authorization for this action"
  219. }
  220. fail(clientMessage,
  221. "User '%s' does not have level '%v' access to repository '%s'",
  222. user.Name, requestMode, repoFullName)
  223. }
  224. }
  225. } else {
  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.IsDeployKey() && setting.Service.RequireSignInView {
  231. checkDeployKey(key, repo)
  232. }
  233. }
  234. uuid := gouuid.NewV4().String()
  235. os.Setenv(_ENV_UPDATE_TASK_UUID, uuid)
  236. os.Setenv(_ENV_REPO_CUSTOM_HOOKS_PATH, filepath.Join(repo.RepoPath(), "custom_hooks"))
  237. // Special handle for Windows.
  238. if setting.IsWindows {
  239. verb = strings.Replace(verb, "-", " ", 1)
  240. }
  241. var gitCmd *exec.Cmd
  242. verbs := strings.Split(verb, " ")
  243. if len(verbs) == 2 {
  244. gitCmd = exec.Command(verbs[0], verbs[1], repoFullName)
  245. } else {
  246. gitCmd = exec.Command(verb, repoFullName)
  247. }
  248. gitCmd.Dir = setting.RepoRootPath
  249. gitCmd.Stdout = os.Stdout
  250. gitCmd.Stdin = os.Stdin
  251. gitCmd.Stderr = os.Stderr
  252. if err = gitCmd.Run(); err != nil {
  253. fail("Internal error", "Fail to execute git command: %v", err)
  254. }
  255. if requestMode == models.ACCESS_MODE_WRITE {
  256. handleUpdateTask(uuid, user, repoOwner, reponame, isWiki)
  257. }
  258. // Update user key activity.
  259. if key.ID > 0 {
  260. key, err := models.GetPublicKeyByID(key.ID)
  261. if err != nil {
  262. fail("Internal error", "GetPublicKeyByID: %v", err)
  263. }
  264. key.Updated = time.Now()
  265. if err = models.UpdatePublicKey(key); err != nil {
  266. fail("Internal error", "UpdatePublicKey: %v", err)
  267. }
  268. }
  269. return nil
  270. }