http.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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.AU_WRITABLE
  97. if isPull {
  98. tp = models.AU_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.AU_READABLE {
  106. has, err = models.HasAccess(authUsername, username+"/"+reponame, models.AU_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. models.Update(refName, oldCommitId, newCommitId, authUsername, username, reponame, authUser.Id)
  128. }
  129. }
  130. }
  131. }}
  132. handler := HttpBackend(&config)
  133. handler(ctx.ResponseWriter, ctx.Req)
  134. }
  135. type route struct {
  136. cr *regexp.Regexp
  137. method string
  138. handler func(handler)
  139. }
  140. type Config struct {
  141. ReposRoot string
  142. GitBinPath string
  143. UploadPack bool
  144. ReceivePack bool
  145. OnSucceed func(rpc string, input []byte)
  146. }
  147. type handler struct {
  148. *Config
  149. w http.ResponseWriter
  150. r *http.Request
  151. Dir string
  152. File string
  153. }
  154. var routes = []route{
  155. {regexp.MustCompile("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  156. {regexp.MustCompile("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  157. {regexp.MustCompile("(.*?)/info/refs$"), "GET", getInfoRefs},
  158. {regexp.MustCompile("(.*?)/HEAD$"), "GET", getTextFile},
  159. {regexp.MustCompile("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  160. {regexp.MustCompile("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  161. {regexp.MustCompile("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  162. {regexp.MustCompile("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  163. {regexp.MustCompile("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  164. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  165. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
  166. }
  167. // Request handling function
  168. func HttpBackend(config *Config) http.HandlerFunc {
  169. return func(w http.ResponseWriter, r *http.Request) {
  170. for _, route := range routes {
  171. if m := route.cr.FindStringSubmatch(r.URL.Path); m != nil {
  172. if route.method != r.Method {
  173. renderMethodNotAllowed(w, r)
  174. return
  175. }
  176. file := strings.Replace(r.URL.Path, m[1]+"/", "", 1)
  177. dir, err := getGitDir(config, m[1])
  178. if err != nil {
  179. log.GitLogger.Error(err.Error())
  180. renderNotFound(w)
  181. return
  182. }
  183. hr := handler{config, w, r, dir, file}
  184. route.handler(hr)
  185. return
  186. }
  187. }
  188. renderNotFound(w)
  189. return
  190. }
  191. }
  192. // Actual command handling functions
  193. func serviceUploadPack(hr handler) {
  194. serviceRpc("upload-pack", hr)
  195. }
  196. func serviceReceivePack(hr handler) {
  197. serviceRpc("receive-pack", hr)
  198. }
  199. func serviceRpc(rpc string, hr handler) {
  200. w, r, dir := hr.w, hr.r, hr.Dir
  201. access := hasAccess(r, hr.Config, dir, rpc, true)
  202. if access == false {
  203. renderNoAccess(w)
  204. return
  205. }
  206. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", rpc))
  207. w.WriteHeader(http.StatusOK)
  208. input, _ := ioutil.ReadAll(r.Body)
  209. br := bytes.NewReader(input)
  210. args := []string{rpc, "--stateless-rpc", dir}
  211. cmd := exec.Command(hr.Config.GitBinPath, args...)
  212. cmd.Dir = dir
  213. cmd.Stdout = w
  214. cmd.Stdin = br
  215. err := cmd.Run()
  216. if err != nil {
  217. log.GitLogger.Error(err.Error())
  218. return
  219. }
  220. if hr.Config.OnSucceed != nil {
  221. hr.Config.OnSucceed(rpc, input)
  222. }
  223. }
  224. func getInfoRefs(hr handler) {
  225. w, r, dir := hr.w, hr.r, hr.Dir
  226. serviceName := getServiceType(r)
  227. access := hasAccess(r, hr.Config, dir, serviceName, false)
  228. if access {
  229. args := []string{serviceName, "--stateless-rpc", "--advertise-refs", "."}
  230. refs := gitCommand(hr.Config.GitBinPath, dir, args...)
  231. hdrNocache(w)
  232. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", serviceName))
  233. w.WriteHeader(http.StatusOK)
  234. w.Write(packetWrite("# service=git-" + serviceName + "\n"))
  235. w.Write(packetFlush())
  236. w.Write(refs)
  237. } else {
  238. updateServerInfo(hr.Config.GitBinPath, dir)
  239. hdrNocache(w)
  240. sendFile("text/plain; charset=utf-8", hr)
  241. }
  242. }
  243. func getInfoPacks(hr handler) {
  244. hdrCacheForever(hr.w)
  245. sendFile("text/plain; charset=utf-8", hr)
  246. }
  247. func getLooseObject(hr handler) {
  248. hdrCacheForever(hr.w)
  249. sendFile("application/x-git-loose-object", hr)
  250. }
  251. func getPackFile(hr handler) {
  252. hdrCacheForever(hr.w)
  253. sendFile("application/x-git-packed-objects", hr)
  254. }
  255. func getIdxFile(hr handler) {
  256. hdrCacheForever(hr.w)
  257. sendFile("application/x-git-packed-objects-toc", hr)
  258. }
  259. func getTextFile(hr handler) {
  260. hdrNocache(hr.w)
  261. sendFile("text/plain", hr)
  262. }
  263. // Logic helping functions
  264. func sendFile(contentType string, hr handler) {
  265. w, r := hr.w, hr.r
  266. reqFile := path.Join(hr.Dir, hr.File)
  267. //fmt.Println("sendFile:", reqFile)
  268. f, err := os.Stat(reqFile)
  269. if os.IsNotExist(err) {
  270. renderNotFound(w)
  271. return
  272. }
  273. w.Header().Set("Content-Type", contentType)
  274. w.Header().Set("Content-Length", fmt.Sprintf("%d", f.Size()))
  275. w.Header().Set("Last-Modified", f.ModTime().Format(http.TimeFormat))
  276. http.ServeFile(w, r, reqFile)
  277. }
  278. func getGitDir(config *Config, fPath string) (string, error) {
  279. root := config.ReposRoot
  280. if root == "" {
  281. cwd, err := os.Getwd()
  282. if err != nil {
  283. log.GitLogger.Error(err.Error())
  284. return "", err
  285. }
  286. root = cwd
  287. }
  288. if !strings.HasSuffix(fPath, ".git") {
  289. fPath = fPath + ".git"
  290. }
  291. f := filepath.Join(root, fPath)
  292. if _, err := os.Stat(f); os.IsNotExist(err) {
  293. return "", err
  294. }
  295. return f, nil
  296. }
  297. func getServiceType(r *http.Request) string {
  298. serviceType := r.FormValue("service")
  299. if s := strings.HasPrefix(serviceType, "git-"); !s {
  300. return ""
  301. }
  302. return strings.Replace(serviceType, "git-", "", 1)
  303. }
  304. func hasAccess(r *http.Request, config *Config, dir string, rpc string, checkContentType bool) bool {
  305. if checkContentType {
  306. if r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", rpc) {
  307. return false
  308. }
  309. }
  310. if !(rpc == "upload-pack" || rpc == "receive-pack") {
  311. return false
  312. }
  313. if rpc == "receive-pack" {
  314. return config.ReceivePack
  315. }
  316. if rpc == "upload-pack" {
  317. return config.UploadPack
  318. }
  319. return getConfigSetting(config.GitBinPath, rpc, dir)
  320. }
  321. func getConfigSetting(gitBinPath, serviceName string, dir string) bool {
  322. serviceName = strings.Replace(serviceName, "-", "", -1)
  323. setting := getGitConfig(gitBinPath, "http."+serviceName, dir)
  324. if serviceName == "uploadpack" {
  325. return setting != "false"
  326. }
  327. return setting == "true"
  328. }
  329. func getGitConfig(gitBinPath, configName string, dir string) string {
  330. args := []string{"config", configName}
  331. out := string(gitCommand(gitBinPath, dir, args...))
  332. return out[0 : len(out)-1]
  333. }
  334. func updateServerInfo(gitBinPath, dir string) []byte {
  335. args := []string{"update-server-info"}
  336. return gitCommand(gitBinPath, dir, args...)
  337. }
  338. func gitCommand(gitBinPath, dir string, args ...string) []byte {
  339. command := exec.Command(gitBinPath, args...)
  340. command.Dir = dir
  341. out, err := command.Output()
  342. if err != nil {
  343. log.GitLogger.Error(err.Error())
  344. }
  345. return out
  346. }
  347. // HTTP error response handling functions
  348. func renderMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  349. if r.Proto == "HTTP/1.1" {
  350. w.WriteHeader(http.StatusMethodNotAllowed)
  351. w.Write([]byte("Method Not Allowed"))
  352. } else {
  353. w.WriteHeader(http.StatusBadRequest)
  354. w.Write([]byte("Bad Request"))
  355. }
  356. }
  357. func renderNotFound(w http.ResponseWriter) {
  358. w.WriteHeader(http.StatusNotFound)
  359. w.Write([]byte("Not Found"))
  360. }
  361. func renderNoAccess(w http.ResponseWriter) {
  362. w.WriteHeader(http.StatusForbidden)
  363. w.Write([]byte("Forbidden"))
  364. }
  365. // Packet-line handling function
  366. func packetFlush() []byte {
  367. return []byte("0000")
  368. }
  369. func packetWrite(str string) []byte {
  370. s := strconv.FormatInt(int64(len(str)+4), 16)
  371. if len(s)%4 != 0 {
  372. s = strings.Repeat("0", 4-len(s)%4) + s
  373. }
  374. return []byte(s + str)
  375. }
  376. // Header writing functions
  377. func hdrNocache(w http.ResponseWriter) {
  378. w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  379. w.Header().Set("Pragma", "no-cache")
  380. w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  381. }
  382. func hdrCacheForever(w http.ResponseWriter) {
  383. now := time.Now().Unix()
  384. expires := now + 31536000
  385. w.Header().Set("Date", fmt.Sprintf("%d", now))
  386. w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  387. w.Header().Set("Cache-Control", "public, max-age=31536000")
  388. }