serve.go 6.1 KB

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