http.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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.UserSignIn(authUsername, authPasswd)
  97. if err != nil {
  98. if err != models.ErrUserNotExist {
  99. ctx.Handle(500, "UserSignIn error: %v", 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. }
  119. if !isPublicPull {
  120. var tp = models.ACCESS_MODE_WRITE
  121. if isPull {
  122. tp = models.ACCESS_MODE_READ
  123. }
  124. has, err := models.HasAccess(authUser, repo, tp)
  125. if err != nil {
  126. ctx.Handle(401, "no basic auth and digit auth", nil)
  127. return
  128. } else if !has {
  129. if tp == models.ACCESS_MODE_READ {
  130. has, err = models.HasAccess(authUser, repo, models.ACCESS_MODE_WRITE)
  131. if err != nil || !has {
  132. ctx.Handle(401, "no basic auth and digit auth", nil)
  133. return
  134. }
  135. } else {
  136. ctx.Handle(401, "no basic auth and digit auth", nil)
  137. return
  138. }
  139. }
  140. if !isPull && repo.IsMirror {
  141. ctx.Handle(401, "can't push to mirror", nil)
  142. return
  143. }
  144. }
  145. }
  146. var f = func(rpc string, input []byte) {
  147. if rpc == "receive-pack" {
  148. var lastLine int64 = 0
  149. for {
  150. head := input[lastLine : lastLine+2]
  151. if head[0] == '0' && head[1] == '0' {
  152. size, err := strconv.ParseInt(string(input[lastLine+2:lastLine+4]), 16, 32)
  153. if err != nil {
  154. log.Error(4, "%v", err)
  155. return
  156. }
  157. if size == 0 {
  158. //fmt.Println(string(input[lastLine:]))
  159. break
  160. }
  161. line := input[lastLine : lastLine+size]
  162. idx := bytes.IndexRune(line, '\000')
  163. if idx > -1 {
  164. line = line[:idx]
  165. }
  166. fields := strings.Fields(string(line))
  167. if len(fields) >= 3 {
  168. oldCommitId := fields[0][4:]
  169. newCommitId := fields[1]
  170. refName := fields[2]
  171. models.Update(refName, oldCommitId, newCommitId, authUsername, username, reponame, authUser.Id)
  172. }
  173. lastLine = lastLine + size
  174. } else {
  175. break
  176. }
  177. }
  178. }
  179. }
  180. config := Config{setting.RepoRootPath, "git", true, true, f}
  181. handler := HttpBackend(&config)
  182. handler(ctx.Resp, ctx.Req.Request)
  183. runtime.GC()
  184. }
  185. type route struct {
  186. cr *regexp.Regexp
  187. method string
  188. handler func(handler)
  189. }
  190. type Config struct {
  191. ReposRoot string
  192. GitBinPath string
  193. UploadPack bool
  194. ReceivePack bool
  195. OnSucceed func(rpc string, input []byte)
  196. }
  197. type handler struct {
  198. *Config
  199. w http.ResponseWriter
  200. r *http.Request
  201. Dir string
  202. File string
  203. }
  204. var routes = []route{
  205. {regexp.MustCompile("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  206. {regexp.MustCompile("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  207. {regexp.MustCompile("(.*?)/info/refs$"), "GET", getInfoRefs},
  208. {regexp.MustCompile("(.*?)/HEAD$"), "GET", getTextFile},
  209. {regexp.MustCompile("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  210. {regexp.MustCompile("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  211. {regexp.MustCompile("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  212. {regexp.MustCompile("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  213. {regexp.MustCompile("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  214. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  215. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
  216. }
  217. // Request handling function
  218. func HttpBackend(config *Config) http.HandlerFunc {
  219. return func(w http.ResponseWriter, r *http.Request) {
  220. for _, route := range routes {
  221. r.URL.Path = strings.ToLower(r.URL.Path) // blue: In case some repo name has upper case name
  222. if m := route.cr.FindStringSubmatch(r.URL.Path); m != nil {
  223. if route.method != r.Method {
  224. renderMethodNotAllowed(w, r)
  225. return
  226. }
  227. file := strings.Replace(r.URL.Path, m[1]+"/", "", 1)
  228. dir, err := getGitDir(config, m[1])
  229. if err != nil {
  230. log.GitLogger.Error(4, err.Error())
  231. renderNotFound(w)
  232. return
  233. }
  234. hr := handler{config, w, r, dir, file}
  235. route.handler(hr)
  236. return
  237. }
  238. }
  239. renderNotFound(w)
  240. return
  241. }
  242. }
  243. // Actual command handling functions
  244. func serviceUploadPack(hr handler) {
  245. serviceRpc("upload-pack", hr)
  246. }
  247. func serviceReceivePack(hr handler) {
  248. serviceRpc("receive-pack", hr)
  249. }
  250. func serviceRpc(rpc string, hr handler) {
  251. w, r, dir := hr.w, hr.r, hr.Dir
  252. access := hasAccess(r, hr.Config, dir, rpc, true)
  253. if access == false {
  254. renderNoAccess(w)
  255. return
  256. }
  257. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", rpc))
  258. var (
  259. reqBody = r.Body
  260. input []byte
  261. br io.Reader
  262. err error
  263. )
  264. // Handle GZIP.
  265. if r.Header.Get("Content-Encoding") == "gzip" {
  266. reqBody, err = gzip.NewReader(reqBody)
  267. if err != nil {
  268. log.GitLogger.Error(2, "fail to create gzip reader: %v", err)
  269. w.WriteHeader(http.StatusInternalServerError)
  270. return
  271. }
  272. }
  273. if hr.Config.OnSucceed != nil {
  274. input, err = ioutil.ReadAll(reqBody)
  275. if err != nil {
  276. log.GitLogger.Error(2, "fail to read request body: %v", err)
  277. w.WriteHeader(http.StatusInternalServerError)
  278. return
  279. }
  280. br = bytes.NewReader(input)
  281. } else {
  282. br = reqBody
  283. }
  284. args := []string{rpc, "--stateless-rpc", dir}
  285. cmd := exec.Command(hr.Config.GitBinPath, args...)
  286. cmd.Dir = dir
  287. cmd.Stdout = w
  288. cmd.Stdin = br
  289. if err := cmd.Run(); err != nil {
  290. log.GitLogger.Error(2, "fail to serve RPC(%s): %v", rpc, err)
  291. w.WriteHeader(http.StatusInternalServerError)
  292. return
  293. }
  294. if hr.Config.OnSucceed != nil {
  295. hr.Config.OnSucceed(rpc, input)
  296. }
  297. w.WriteHeader(http.StatusOK)
  298. }
  299. func getInfoRefs(hr handler) {
  300. w, r, dir := hr.w, hr.r, hr.Dir
  301. serviceName := getServiceType(r)
  302. access := hasAccess(r, hr.Config, dir, serviceName, false)
  303. if access {
  304. args := []string{serviceName, "--stateless-rpc", "--advertise-refs", "."}
  305. refs := gitCommand(hr.Config.GitBinPath, dir, args...)
  306. hdrNocache(w)
  307. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", serviceName))
  308. w.WriteHeader(http.StatusOK)
  309. w.Write(packetWrite("# service=git-" + serviceName + "\n"))
  310. w.Write(packetFlush())
  311. w.Write(refs)
  312. } else {
  313. updateServerInfo(hr.Config.GitBinPath, dir)
  314. hdrNocache(w)
  315. sendFile("text/plain; charset=utf-8", hr)
  316. }
  317. }
  318. func getInfoPacks(hr handler) {
  319. hdrCacheForever(hr.w)
  320. sendFile("text/plain; charset=utf-8", hr)
  321. }
  322. func getLooseObject(hr handler) {
  323. hdrCacheForever(hr.w)
  324. sendFile("application/x-git-loose-object", hr)
  325. }
  326. func getPackFile(hr handler) {
  327. hdrCacheForever(hr.w)
  328. sendFile("application/x-git-packed-objects", hr)
  329. }
  330. func getIdxFile(hr handler) {
  331. hdrCacheForever(hr.w)
  332. sendFile("application/x-git-packed-objects-toc", hr)
  333. }
  334. func getTextFile(hr handler) {
  335. hdrNocache(hr.w)
  336. sendFile("text/plain", hr)
  337. }
  338. // Logic helping functions
  339. func sendFile(contentType string, hr handler) {
  340. w, r := hr.w, hr.r
  341. reqFile := path.Join(hr.Dir, hr.File)
  342. // fmt.Println("sendFile:", reqFile)
  343. f, err := os.Stat(reqFile)
  344. if os.IsNotExist(err) {
  345. renderNotFound(w)
  346. return
  347. }
  348. w.Header().Set("Content-Type", contentType)
  349. w.Header().Set("Content-Length", fmt.Sprintf("%d", f.Size()))
  350. w.Header().Set("Last-Modified", f.ModTime().Format(http.TimeFormat))
  351. http.ServeFile(w, r, reqFile)
  352. }
  353. func getGitDir(config *Config, fPath string) (string, error) {
  354. root := config.ReposRoot
  355. if root == "" {
  356. cwd, err := os.Getwd()
  357. if err != nil {
  358. log.GitLogger.Error(4, err.Error())
  359. return "", err
  360. }
  361. root = cwd
  362. }
  363. if !strings.HasSuffix(fPath, ".git") {
  364. fPath = fPath + ".git"
  365. }
  366. f := filepath.Join(root, fPath)
  367. if _, err := os.Stat(f); os.IsNotExist(err) {
  368. return "", err
  369. }
  370. return f, nil
  371. }
  372. func getServiceType(r *http.Request) string {
  373. serviceType := r.FormValue("service")
  374. if s := strings.HasPrefix(serviceType, "git-"); !s {
  375. return ""
  376. }
  377. return strings.Replace(serviceType, "git-", "", 1)
  378. }
  379. func hasAccess(r *http.Request, config *Config, dir string, rpc string, checkContentType bool) bool {
  380. if checkContentType {
  381. if r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", rpc) {
  382. return false
  383. }
  384. }
  385. if !(rpc == "upload-pack" || rpc == "receive-pack") {
  386. return false
  387. }
  388. if rpc == "receive-pack" {
  389. return config.ReceivePack
  390. }
  391. if rpc == "upload-pack" {
  392. return config.UploadPack
  393. }
  394. return getConfigSetting(config.GitBinPath, rpc, dir)
  395. }
  396. func getConfigSetting(gitBinPath, serviceName string, dir string) bool {
  397. serviceName = strings.Replace(serviceName, "-", "", -1)
  398. setting := getGitConfig(gitBinPath, "http."+serviceName, dir)
  399. if serviceName == "uploadpack" {
  400. return setting != "false"
  401. }
  402. return setting == "true"
  403. }
  404. func getGitConfig(gitBinPath, configName string, dir string) string {
  405. args := []string{"config", configName}
  406. out := string(gitCommand(gitBinPath, dir, args...))
  407. return out[0 : len(out)-1]
  408. }
  409. func updateServerInfo(gitBinPath, dir string) []byte {
  410. args := []string{"update-server-info"}
  411. return gitCommand(gitBinPath, dir, args...)
  412. }
  413. func gitCommand(gitBinPath, dir string, args ...string) []byte {
  414. command := exec.Command(gitBinPath, args...)
  415. command.Dir = dir
  416. out, err := command.Output()
  417. if err != nil {
  418. log.GitLogger.Error(4, err.Error())
  419. }
  420. return out
  421. }
  422. // HTTP error response handling functions
  423. func renderMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  424. if r.Proto == "HTTP/1.1" {
  425. w.WriteHeader(http.StatusMethodNotAllowed)
  426. w.Write([]byte("Method Not Allowed"))
  427. } else {
  428. w.WriteHeader(http.StatusBadRequest)
  429. w.Write([]byte("Bad Request"))
  430. }
  431. }
  432. func renderNotFound(w http.ResponseWriter) {
  433. w.WriteHeader(http.StatusNotFound)
  434. w.Write([]byte("Not Found"))
  435. }
  436. func renderNoAccess(w http.ResponseWriter) {
  437. w.WriteHeader(http.StatusForbidden)
  438. w.Write([]byte("Forbidden"))
  439. }
  440. // Packet-line handling function
  441. func packetFlush() []byte {
  442. return []byte("0000")
  443. }
  444. func packetWrite(str string) []byte {
  445. s := strconv.FormatInt(int64(len(str)+4), 16)
  446. if len(s)%4 != 0 {
  447. s = strings.Repeat("0", 4-len(s)%4) + s
  448. }
  449. return []byte(s + str)
  450. }
  451. // Header writing functions
  452. func hdrNocache(w http.ResponseWriter) {
  453. w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  454. w.Header().Set("Pragma", "no-cache")
  455. w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  456. }
  457. func hdrCacheForever(w http.ResponseWriter) {
  458. now := time.Now().Unix()
  459. expires := now + 31536000
  460. w.Header().Set("Date", fmt.Sprintf("%d", now))
  461. w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  462. w.Header().Set("Cache-Control", "public, max-age=31536000")
  463. }