http.go 12 KB

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