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