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.

http.go 12 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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 repo
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/go-martini/martini"
  19. "github.com/gogits/gogs/models"
  20. "github.com/gogits/gogs/modules/log"
  21. "github.com/gogits/gogs/modules/middleware"
  22. "github.com/gogits/gogs/modules/setting"
  23. )
  24. func Http(ctx *middleware.Context, params martini.Params) {
  25. username := params["username"]
  26. reponame := params["reponame"]
  27. if strings.HasSuffix(reponame, ".git") {
  28. reponame = reponame[:len(reponame)-4]
  29. }
  30. var isPull bool
  31. service := ctx.Query("service")
  32. if service == "git-receive-pack" ||
  33. strings.HasSuffix(ctx.Req.URL.Path, "git-receive-pack") {
  34. isPull = false
  35. } else if service == "git-upload-pack" ||
  36. strings.HasSuffix(ctx.Req.URL.Path, "git-upload-pack") {
  37. isPull = true
  38. } else {
  39. isPull = (ctx.Req.Method == "GET")
  40. }
  41. repoUser, err := models.GetUserByName(username)
  42. if err != nil {
  43. if err == models.ErrUserNotExist {
  44. ctx.Handle(404, "repo.Http(GetUserByName)", nil)
  45. } else {
  46. ctx.Handle(500, "repo.Http(GetUserByName)", nil)
  47. }
  48. return
  49. }
  50. repo, err := models.GetRepositoryByName(repoUser.Id, reponame)
  51. if err != nil {
  52. if err == models.ErrRepoNotExist {
  53. ctx.Handle(404, "repo.Http(GetRepositoryByName)", nil)
  54. } else {
  55. ctx.Handle(500, "repo.Http(GetRepositoryByName)", nil)
  56. }
  57. return
  58. }
  59. // only public pull don't need auth
  60. isPublicPull := !repo.IsPrivate && isPull
  61. var askAuth = !isPublicPull || setting.Service.RequireSignInView
  62. var authUser *models.User
  63. var authUsername, passwd string
  64. // check access
  65. if askAuth {
  66. baHead := ctx.Req.Header.Get("Authorization")
  67. if baHead == "" {
  68. // ask auth
  69. authRequired(ctx)
  70. return
  71. }
  72. auths := strings.Fields(baHead)
  73. // currently check basic auth
  74. // TODO: support digit auth
  75. if len(auths) != 2 || auths[0] != "Basic" {
  76. ctx.Handle(401, "no basic auth and digit auth", nil)
  77. return
  78. }
  79. authUsername, passwd, err = basicDecode(auths[1])
  80. if err != nil {
  81. ctx.Handle(401, "no basic auth and digit auth", nil)
  82. return
  83. }
  84. authUser, err = models.GetUserByName(authUsername)
  85. if err != nil {
  86. ctx.Handle(401, "no basic auth and digit auth", nil)
  87. return
  88. }
  89. newUser := &models.User{Passwd: passwd, Salt: authUser.Salt}
  90. newUser.EncodePasswd()
  91. if authUser.Passwd != newUser.Passwd {
  92. ctx.Handle(401, "no basic auth and digit auth", nil)
  93. return
  94. }
  95. if !isPublicPull {
  96. var tp = models.WRITABLE
  97. if isPull {
  98. tp = models.READABLE
  99. }
  100. has, err := models.HasAccess(authUsername, username+"/"+reponame, tp)
  101. if err != nil {
  102. ctx.Handle(401, "no basic auth and digit auth", nil)
  103. return
  104. } else if !has {
  105. if tp == models.READABLE {
  106. has, err = models.HasAccess(authUsername, username+"/"+reponame, models.WRITABLE)
  107. if err != nil || !has {
  108. ctx.Handle(401, "no basic auth and digit auth", nil)
  109. return
  110. }
  111. } else {
  112. ctx.Handle(401, "no basic auth and digit auth", nil)
  113. return
  114. }
  115. }
  116. }
  117. }
  118. config := Config{setting.RepoRootPath, "git", true, true, func(rpc string, input []byte) {
  119. if rpc == "receive-pack" {
  120. firstLine := bytes.IndexRune(input, '\000')
  121. if firstLine > -1 {
  122. fields := strings.Fields(string(input[:firstLine]))
  123. if len(fields) == 3 {
  124. oldCommitId := fields[0][4:]
  125. newCommitId := fields[1]
  126. refName := fields[2]
  127. if err = models.Update(refName, oldCommitId, newCommitId, authUsername, username, reponame, authUser.Id); err != nil {
  128. log.GitLogger.Error(err.Error())
  129. return
  130. }
  131. }
  132. }
  133. }
  134. }}
  135. handler := HttpBackend(&config)
  136. handler(ctx.ResponseWriter, ctx.Req)
  137. }
  138. type route struct {
  139. cr *regexp.Regexp
  140. method string
  141. handler func(handler)
  142. }
  143. type Config struct {
  144. ReposRoot string
  145. GitBinPath string
  146. UploadPack bool
  147. ReceivePack bool
  148. OnSucceed func(rpc string, input []byte)
  149. }
  150. type handler struct {
  151. *Config
  152. w http.ResponseWriter
  153. r *http.Request
  154. Dir string
  155. File string
  156. }
  157. var routes = []route{
  158. {regexp.MustCompile("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  159. {regexp.MustCompile("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  160. {regexp.MustCompile("(.*?)/info/refs$"), "GET", getInfoRefs},
  161. {regexp.MustCompile("(.*?)/HEAD$"), "GET", getTextFile},
  162. {regexp.MustCompile("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  163. {regexp.MustCompile("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  164. {regexp.MustCompile("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  165. {regexp.MustCompile("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  166. {regexp.MustCompile("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  167. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  168. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
  169. }
  170. // Request handling function
  171. func HttpBackend(config *Config) http.HandlerFunc {
  172. return func(w http.ResponseWriter, r *http.Request) {
  173. for _, route := range routes {
  174. if m := route.cr.FindStringSubmatch(r.URL.Path); m != nil {
  175. if route.method != r.Method {
  176. renderMethodNotAllowed(w, r)
  177. return
  178. }
  179. file := strings.Replace(r.URL.Path, m[1]+"/", "", 1)
  180. dir, err := getGitDir(config, m[1])
  181. if err != nil {
  182. log.GitLogger.Error(err.Error())
  183. renderNotFound(w)
  184. return
  185. }
  186. hr := handler{config, w, r, dir, file}
  187. route.handler(hr)
  188. return
  189. }
  190. }
  191. renderNotFound(w)
  192. return
  193. }
  194. }
  195. // Actual command handling functions
  196. func serviceUploadPack(hr handler) {
  197. serviceRpc("upload-pack", hr)
  198. }
  199. func serviceReceivePack(hr handler) {
  200. serviceRpc("receive-pack", hr)
  201. }
  202. func serviceRpc(rpc string, hr handler) {
  203. w, r, dir := hr.w, hr.r, hr.Dir
  204. access := hasAccess(r, hr.Config, dir, rpc, true)
  205. if access == false {
  206. renderNoAccess(w)
  207. return
  208. }
  209. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", rpc))
  210. w.WriteHeader(http.StatusOK)
  211. input, _ := ioutil.ReadAll(r.Body)
  212. br := bytes.NewReader(input)
  213. args := []string{rpc, "--stateless-rpc", dir}
  214. cmd := exec.Command(hr.Config.GitBinPath, args...)
  215. cmd.Dir = dir
  216. cmd.Stdout = w
  217. cmd.Stdin = br
  218. err := cmd.Run()
  219. if err != nil {
  220. log.GitLogger.Error(err.Error())
  221. return
  222. }
  223. if hr.Config.OnSucceed != nil {
  224. hr.Config.OnSucceed(rpc, input)
  225. }
  226. }
  227. func getInfoRefs(hr handler) {
  228. w, r, dir := hr.w, hr.r, hr.Dir
  229. serviceName := getServiceType(r)
  230. access := hasAccess(r, hr.Config, dir, serviceName, false)
  231. if access {
  232. args := []string{serviceName, "--stateless-rpc", "--advertise-refs", "."}
  233. refs := gitCommand(hr.Config.GitBinPath, dir, args...)
  234. hdrNocache(w)
  235. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", serviceName))
  236. w.WriteHeader(http.StatusOK)
  237. w.Write(packetWrite("# service=git-" + serviceName + "\n"))
  238. w.Write(packetFlush())
  239. w.Write(refs)
  240. } else {
  241. updateServerInfo(hr.Config.GitBinPath, dir)
  242. hdrNocache(w)
  243. sendFile("text/plain; charset=utf-8", hr)
  244. }
  245. }
  246. func getInfoPacks(hr handler) {
  247. hdrCacheForever(hr.w)
  248. sendFile("text/plain; charset=utf-8", hr)
  249. }
  250. func getLooseObject(hr handler) {
  251. hdrCacheForever(hr.w)
  252. sendFile("application/x-git-loose-object", hr)
  253. }
  254. func getPackFile(hr handler) {
  255. hdrCacheForever(hr.w)
  256. sendFile("application/x-git-packed-objects", hr)
  257. }
  258. func getIdxFile(hr handler) {
  259. hdrCacheForever(hr.w)
  260. sendFile("application/x-git-packed-objects-toc", hr)
  261. }
  262. func getTextFile(hr handler) {
  263. hdrNocache(hr.w)
  264. sendFile("text/plain", hr)
  265. }
  266. // Logic helping functions
  267. func sendFile(contentType string, hr handler) {
  268. w, r := hr.w, hr.r
  269. reqFile := path.Join(hr.Dir, hr.File)
  270. //fmt.Println("sendFile:", reqFile)
  271. f, err := os.Stat(reqFile)
  272. if os.IsNotExist(err) {
  273. renderNotFound(w)
  274. return
  275. }
  276. w.Header().Set("Content-Type", contentType)
  277. w.Header().Set("Content-Length", fmt.Sprintf("%d", f.Size()))
  278. w.Header().Set("Last-Modified", f.ModTime().Format(http.TimeFormat))
  279. http.ServeFile(w, r, reqFile)
  280. }
  281. func getGitDir(config *Config, fPath string) (string, error) {
  282. root := config.ReposRoot
  283. if root == "" {
  284. cwd, err := os.Getwd()
  285. if err != nil {
  286. log.GitLogger.Error(err.Error())
  287. return "", err
  288. }
  289. root = cwd
  290. }
  291. if !strings.HasSuffix(fPath, ".git") {
  292. fPath = fPath + ".git"
  293. }
  294. f := filepath.Join(root, fPath)
  295. if _, err := os.Stat(f); os.IsNotExist(err) {
  296. return "", err
  297. }
  298. return f, nil
  299. }
  300. func getServiceType(r *http.Request) string {
  301. serviceType := r.FormValue("service")
  302. if s := strings.HasPrefix(serviceType, "git-"); !s {
  303. return ""
  304. }
  305. return strings.Replace(serviceType, "git-", "", 1)
  306. }
  307. func hasAccess(r *http.Request, config *Config, dir string, rpc string, checkContentType bool) bool {
  308. if checkContentType {
  309. if r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", rpc) {
  310. return false
  311. }
  312. }
  313. if !(rpc == "upload-pack" || rpc == "receive-pack") {
  314. return false
  315. }
  316. if rpc == "receive-pack" {
  317. return config.ReceivePack
  318. }
  319. if rpc == "upload-pack" {
  320. return config.UploadPack
  321. }
  322. return getConfigSetting(config.GitBinPath, rpc, dir)
  323. }
  324. func getConfigSetting(gitBinPath, serviceName string, dir string) bool {
  325. serviceName = strings.Replace(serviceName, "-", "", -1)
  326. setting := getGitConfig(gitBinPath, "http."+serviceName, dir)
  327. if serviceName == "uploadpack" {
  328. return setting != "false"
  329. }
  330. return setting == "true"
  331. }
  332. func getGitConfig(gitBinPath, configName string, dir string) string {
  333. args := []string{"config", configName}
  334. out := string(gitCommand(gitBinPath, dir, args...))
  335. return out[0 : len(out)-1]
  336. }
  337. func updateServerInfo(gitBinPath, dir string) []byte {
  338. args := []string{"update-server-info"}
  339. return gitCommand(gitBinPath, dir, args...)
  340. }
  341. func gitCommand(gitBinPath, dir string, args ...string) []byte {
  342. command := exec.Command(gitBinPath, args...)
  343. command.Dir = dir
  344. out, err := command.Output()
  345. if err != nil {
  346. log.GitLogger.Error(err.Error())
  347. }
  348. return out
  349. }
  350. // HTTP error response handling functions
  351. func renderMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  352. if r.Proto == "HTTP/1.1" {
  353. w.WriteHeader(http.StatusMethodNotAllowed)
  354. w.Write([]byte("Method Not Allowed"))
  355. } else {
  356. w.WriteHeader(http.StatusBadRequest)
  357. w.Write([]byte("Bad Request"))
  358. }
  359. }
  360. func renderNotFound(w http.ResponseWriter) {
  361. w.WriteHeader(http.StatusNotFound)
  362. w.Write([]byte("Not Found"))
  363. }
  364. func renderNoAccess(w http.ResponseWriter) {
  365. w.WriteHeader(http.StatusForbidden)
  366. w.Write([]byte("Forbidden"))
  367. }
  368. // Packet-line handling function
  369. func packetFlush() []byte {
  370. return []byte("0000")
  371. }
  372. func packetWrite(str string) []byte {
  373. s := strconv.FormatInt(int64(len(str)+4), 16)
  374. if len(s)%4 != 0 {
  375. s = strings.Repeat("0", 4-len(s)%4) + s
  376. }
  377. return []byte(s + str)
  378. }
  379. // Header writing functions
  380. func hdrNocache(w http.ResponseWriter) {
  381. w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  382. w.Header().Set("Pragma", "no-cache")
  383. w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  384. }
  385. func hdrCacheForever(w http.ResponseWriter) {
  386. now := time.Now().Unix()
  387. expires := now + 31536000
  388. w.Header().Set("Date", fmt.Sprintf("%d", now))
  389. w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  390. w.Header().Set("Cache-Control", "public, max-age=31536000")
  391. }