serve.go 6.1 KB

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