serve.go 6.5 KB

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