You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

290 lines
6.0 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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 main
  5. import (
  6. "bytes"
  7. "container/list"
  8. "fmt"
  9. "io"
  10. "os"
  11. "os/exec"
  12. "strconv"
  13. "strings"
  14. "github.com/codegangsta/cli"
  15. "github.com/gogits/gogs/modules/log"
  16. "github.com/gogits/git"
  17. "github.com/gogits/gogs/models"
  18. "github.com/gogits/gogs/modules/base"
  19. )
  20. var (
  21. COMMANDS_READONLY = map[string]int{
  22. "git-upload-pack": models.AU_WRITABLE,
  23. "git upload-pack": models.AU_WRITABLE,
  24. "git-upload-archive": models.AU_WRITABLE,
  25. }
  26. COMMANDS_WRITE = map[string]int{
  27. "git-receive-pack": models.AU_READABLE,
  28. "git receive-pack": models.AU_READABLE,
  29. }
  30. )
  31. var CmdServ = cli.Command{
  32. Name: "serv",
  33. Usage: "This command just should be called by ssh shell",
  34. Description: `
  35. gogs serv provide access auth for repositories`,
  36. Action: runServ,
  37. Flags: []cli.Flag{},
  38. }
  39. func parseCmd(cmd string) (string, string) {
  40. ss := strings.SplitN(cmd, " ", 2)
  41. if len(ss) != 2 {
  42. return "", ""
  43. }
  44. verb, args := ss[0], ss[1]
  45. if verb == "git" {
  46. ss = strings.SplitN(args, " ", 2)
  47. args = ss[1]
  48. verb = fmt.Sprintf("%s %s", verb, ss[0])
  49. }
  50. return verb, args
  51. }
  52. func In(b string, sl map[string]int) bool {
  53. _, e := sl[b]
  54. return e
  55. }
  56. func runServ(k *cli.Context) {
  57. base.NewConfigContext()
  58. models.LoadModelsConfig()
  59. models.NewEngine()
  60. keys := strings.Split(os.Args[2], "-")
  61. if len(keys) != 2 {
  62. fmt.Println("auth file format error")
  63. return
  64. }
  65. keyId, err := strconv.ParseInt(keys[1], 10, 64)
  66. if err != nil {
  67. fmt.Println("auth file format error")
  68. return
  69. }
  70. user, err := models.GetUserByKeyId(keyId)
  71. if err != nil {
  72. fmt.Println("You have no right to access")
  73. return
  74. }
  75. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  76. if cmd == "" {
  77. println("Hi", user.Name, "! You've successfully authenticated, but Gogs does not provide shell access.")
  78. return
  79. }
  80. verb, args := parseCmd(cmd)
  81. rRepo := strings.Trim(args, "'")
  82. rr := strings.SplitN(rRepo, "/", 2)
  83. if len(rr) != 2 {
  84. println("Unavilable repository", args)
  85. return
  86. }
  87. repoName := rr[1]
  88. if strings.HasSuffix(repoName, ".git") {
  89. repoName = repoName[:len(repoName)-4]
  90. }
  91. repo, err := models.GetRepositoryByName(user.Id, repoName)
  92. var isExist bool = true
  93. if err != nil {
  94. if err == models.ErrRepoNotExist {
  95. isExist = false
  96. } else {
  97. println("Unavilable repository", err)
  98. return
  99. }
  100. }
  101. isWrite := In(verb, COMMANDS_WRITE)
  102. isRead := In(verb, COMMANDS_READONLY)
  103. switch {
  104. case isWrite:
  105. has, err := models.HasAccess(user.Name, repoName, models.AU_WRITABLE)
  106. if err != nil {
  107. println("Inernel error:", err)
  108. return
  109. }
  110. if !has {
  111. println("You have no right to write this repository")
  112. return
  113. }
  114. case isRead:
  115. has, err := models.HasAccess(user.Name, repoName, models.AU_READABLE)
  116. if err != nil {
  117. println("Inernel error")
  118. return
  119. }
  120. if !has {
  121. has, err = models.HasAccess(user.Name, repoName, models.AU_WRITABLE)
  122. if err != nil {
  123. println("Inernel error")
  124. return
  125. }
  126. }
  127. if !has {
  128. println("You have no right to access this repository")
  129. return
  130. }
  131. default:
  132. println("Unknown command")
  133. return
  134. }
  135. if !isExist {
  136. if isRead {
  137. println("Repository", user.Name+"/"+repoName, "is not exist")
  138. return
  139. } else if isWrite {
  140. _, err := models.CreateRepository(user, repoName, "", "", "", false, true)
  141. if err != nil {
  142. println("Create repository failed")
  143. return
  144. }
  145. }
  146. }
  147. rep, err := git.OpenRepository(models.RepoPath(user.Name, repoName))
  148. if err != nil {
  149. println(err.Error())
  150. return
  151. }
  152. refs, err := rep.AllReferencesMap()
  153. if err != nil {
  154. println(err.Error())
  155. return
  156. }
  157. gitcmd := exec.Command(verb, rRepo)
  158. gitcmd.Dir = base.RepoRootPath
  159. var s string
  160. b := bytes.NewBufferString(s)
  161. gitcmd.Stdout = io.MultiWriter(os.Stdout, b)
  162. //gitcmd.Stdin = io.MultiReader(os.Stdin, b)
  163. gitcmd.Stdin = os.Stdin
  164. gitcmd.Stderr = os.Stderr
  165. if err = gitcmd.Run(); err != nil {
  166. println("execute command error:", err.Error())
  167. }
  168. if !strings.HasPrefix(cmd, "git-receive-pack") {
  169. return
  170. }
  171. // update
  172. //w, _ := os.Create("serve.log")
  173. //defer w.Close()
  174. //log.SetOutput(w)
  175. var t = "ok refs/heads/"
  176. var i int
  177. var refname string
  178. for {
  179. l, err := b.ReadString('\n')
  180. if err != nil {
  181. break
  182. }
  183. i = i + 1
  184. l = l[:len(l)-1]
  185. idx := strings.Index(l, t)
  186. if idx > 0 {
  187. refname = l[idx+len(t):]
  188. }
  189. }
  190. var ref *git.Reference
  191. var ok bool
  192. var l *list.List
  193. //log.Info("----", refname, "-----")
  194. if ref, ok = refs[refname]; !ok {
  195. refs, err = rep.AllReferencesMap()
  196. if err != nil {
  197. println(err.Error())
  198. return
  199. }
  200. if ref, ok = refs[refname]; !ok {
  201. println("unknow reference name -", refname, "-")
  202. return
  203. }
  204. l, err = ref.AllCommits()
  205. if err != nil {
  206. println(err.Error())
  207. return
  208. }
  209. } else {
  210. //log.Info("----", ref, "-----")
  211. var last *git.Commit
  212. //log.Info("00000", ref.Oid.String())
  213. last, err = ref.LastCommit()
  214. if err != nil {
  215. println(err.Error())
  216. return
  217. }
  218. ref2, err := rep.LookupReference(ref.Name)
  219. if err != nil {
  220. println(err.Error())
  221. return
  222. }
  223. //log.Info("11111", ref2.Oid.String())
  224. before, err := ref2.LastCommit()
  225. if err != nil {
  226. println(err.Error())
  227. return
  228. }
  229. //log.Info("----", before.Id(), "-----", last.Id())
  230. l = ref.CommitsBetween(before, last)
  231. }
  232. commits := make([][]string, 0)
  233. var maxCommits = 3
  234. for e := l.Front(); e != nil; e = e.Next() {
  235. commit := e.Value.(*git.Commit)
  236. commits = append(commits, []string{commit.Id().String(), commit.Message()})
  237. if len(commits) >= maxCommits {
  238. break
  239. }
  240. }
  241. if err = models.CommitRepoAction(user.Id, user.Name,
  242. repo.Id, repoName, refname, &base.PushCommits{l.Len(), commits}); err != nil {
  243. log.Error("runUpdate.models.CommitRepoAction: %v", err, commits)
  244. } else {
  245. //log.Info("refname", refname)
  246. //log.Info("Listen: %v", cmd)
  247. //fmt.Println("...", cmd)
  248. //runUpdate(k)
  249. c := exec.Command("git", "update-server-info")
  250. c.Dir = models.RepoPath(user.Name, repoName)
  251. err := c.Run()
  252. if err != nil {
  253. log.Error("update-server-info: %v", err)
  254. }
  255. }
  256. }