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.0 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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/qiniu/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. keys := strings.Split(os.Args[2], "-")
  61. if len(keys) != 2 {
  62. fmt.Println("auth file format error")
  63. return
  64. }
  65. keyId, err := strconv.ParseInt(keys[1], 10, 64)
  66. if err != nil {
  67. fmt.Println("auth file format error")
  68. return
  69. }
  70. user, err := models.GetUserByKeyId(keyId)
  71. if err != nil {
  72. fmt.Println("You have no right to access")
  73. return
  74. }
  75. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  76. if cmd == "" {
  77. println("Hi", user.Name, "! You've successfully authenticated, but Gogs does not provide shell access.")
  78. return
  79. }
  80. verb, args := parseCmd(cmd)
  81. rRepo := strings.Trim(args, "'")
  82. rr := strings.SplitN(rRepo, "/", 2)
  83. if len(rr) != 2 {
  84. println("Unavilable repository", args)
  85. return
  86. }
  87. repoName := rr[1]
  88. if strings.HasSuffix(repoName, ".git") {
  89. repoName = repoName[:len(repoName)-4]
  90. }
  91. //os.Setenv("userName", user.Name)
  92. //os.Setenv("userId", strconv.Itoa(int(user.Id)))
  93. repo, err := models.GetRepositoryByName(user, repoName)
  94. var isExist bool = true
  95. if err != nil {
  96. if err == models.ErrRepoNotExist {
  97. isExist = false
  98. } else {
  99. println("Unavilable repository", err)
  100. return
  101. }
  102. }
  103. //os.Setenv("repoId", strconv.Itoa(int(repo.Id)))
  104. //os.Setenv("repoName", repoName)
  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.Stderr = os.Stderr
  168. if err = gitcmd.Run(); err != nil {
  169. println("execute command error:", err.Error())
  170. }
  171. // update
  172. w, _ := os.Create("serve.log")
  173. defer w.Close()
  174. log.SetOutput(w)
  175. var t = "ok refs/heads/"
  176. var i int
  177. var refname string
  178. for {
  179. l, err := b.ReadString('\n')
  180. if err != nil {
  181. break
  182. }
  183. i = i + 1
  184. l = l[:len(l)-1]
  185. idx := strings.Index(l, t)
  186. if idx > 0 {
  187. refname = l[idx+len(t):]
  188. }
  189. }
  190. var ref *git.Reference
  191. var ok bool
  192. var l *list.List
  193. //log.Info("----", refname, "-----")
  194. if ref, ok = refs[refname]; !ok {
  195. refs, err = rep.AllReferencesMap()
  196. if err != nil {
  197. println(err.Error())
  198. return
  199. }
  200. if ref, ok = refs[refname]; !ok {
  201. println("unknow reference name", refname)
  202. return
  203. }
  204. l, err = ref.AllCommits()
  205. if err != nil {
  206. println(err.Error())
  207. return
  208. }
  209. } else {
  210. //log.Info("----", ref, "-----")
  211. var last *git.Commit
  212. //log.Info("00000", ref.Oid.String())
  213. last, err = ref.LastCommit()
  214. if err != nil {
  215. println(err.Error())
  216. return
  217. }
  218. ref2, err := rep.LookupReference(ref.Name)
  219. if err != nil {
  220. println(err.Error())
  221. return
  222. }
  223. //log.Info("11111", ref2.Oid.String())
  224. before, err := ref2.LastCommit()
  225. if err != nil {
  226. println(err.Error())
  227. return
  228. }
  229. //log.Info("----", before.Id(), "-----", last.Id())
  230. l = ref.CommitsBetween(before, last)
  231. }
  232. commits := make([][]string, 0)
  233. for e := l.Back(); e != nil; e = e.Prev() {
  234. commit := e.Value.(*git.Commit)
  235. commits = append(commits, []string{commit.Id().String(), commit.Message()})
  236. }
  237. if err = models.CommitRepoAction(user.Id, user.Name,
  238. repo.Id, ref.BranchName(), commits); err != nil {
  239. log.Error("runUpdate.models.CommitRepoAction: %v", err, commits)
  240. } else {
  241. //log.Info("refname", refname)
  242. //log.Info("Listen: %v", cmd)
  243. //fmt.Println("...", cmd)
  244. //runUpdate(k)
  245. c := exec.Command("exec", "git", "update-server-info")
  246. c.Run()
  247. }
  248. }