http.go 11 KB

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