You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

serve.go 6.3 kB

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