http.go 13 KB

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