serve.go 6.1 KB

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