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