serve.go 7.6 KB

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