serve.go 6.0 KB

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