http.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. "log"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "regexp"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "github.com/go-martini/martini"
  21. "github.com/gogits/gogs/models"
  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. ctx.Handle(500, "repo.GetUserByName", nil)
  45. return
  46. }
  47. repo, err := models.GetRepositoryByName(repoUser.Id, reponame)
  48. if err != nil {
  49. ctx.Handle(500, "repo.GetRepositoryByName", nil)
  50. return
  51. }
  52. // only public pull don't need auth
  53. isPublicPull := !repo.IsPrivate && isPull
  54. var askAuth = !isPublicPull || setting.Service.RequireSignInView
  55. var authUser *models.User
  56. var authUsername, passwd string
  57. // check access
  58. if askAuth {
  59. baHead := ctx.Req.Header.Get("Authorization")
  60. if baHead == "" {
  61. // ask auth
  62. authRequired(ctx)
  63. return
  64. }
  65. auths := strings.Fields(baHead)
  66. // currently check basic auth
  67. // TODO: support digit auth
  68. if len(auths) != 2 || auths[0] != "Basic" {
  69. ctx.Handle(401, "no basic auth and digit auth", nil)
  70. return
  71. }
  72. authUsername, passwd, err = basicDecode(auths[1])
  73. if err != nil {
  74. ctx.Handle(401, "no basic auth and digit auth", nil)
  75. return
  76. }
  77. authUser, err = models.GetUserByName(authUsername)
  78. if err != nil {
  79. ctx.Handle(401, "no basic auth and digit auth", nil)
  80. return
  81. }
  82. newUser := &models.User{Passwd: passwd, Salt: authUser.Salt}
  83. newUser.EncodePasswd()
  84. if authUser.Passwd != newUser.Passwd {
  85. ctx.Handle(401, "no basic auth and digit auth", nil)
  86. return
  87. }
  88. if !isPublicPull {
  89. var tp = models.AU_WRITABLE
  90. if isPull {
  91. tp = models.AU_READABLE
  92. }
  93. has, err := models.HasAccess(authUsername, username+"/"+reponame, tp)
  94. if err != nil {
  95. ctx.Handle(401, "no basic auth and digit auth", nil)
  96. return
  97. } else if !has {
  98. if tp == models.AU_READABLE {
  99. has, err = models.HasAccess(authUsername, username+"/"+reponame, models.AU_WRITABLE)
  100. if err != nil || !has {
  101. ctx.Handle(401, "no basic auth and digit auth", nil)
  102. return
  103. }
  104. } else {
  105. ctx.Handle(401, "no basic auth and digit auth", nil)
  106. return
  107. }
  108. }
  109. }
  110. }
  111. config := Config{setting.RepoRootPath, "git", true, true, func(rpc string, input []byte) {
  112. if rpc == "receive-pack" {
  113. firstLine := bytes.IndexRune(input, '\000')
  114. if firstLine > -1 {
  115. fields := strings.Fields(string(input[:firstLine]))
  116. if len(fields) == 3 {
  117. oldCommitId := fields[0][4:]
  118. newCommitId := fields[1]
  119. refName := fields[2]
  120. models.Update(refName, oldCommitId, newCommitId, authUsername, username, reponame, authUser.Id)
  121. }
  122. }
  123. }
  124. }}
  125. handler := HttpBackend(&config)
  126. handler(ctx.ResponseWriter, ctx.Req)
  127. }
  128. type route struct {
  129. cr *regexp.Regexp
  130. method string
  131. handler func(handler)
  132. }
  133. type Config struct {
  134. ReposRoot string
  135. GitBinPath string
  136. UploadPack bool
  137. ReceivePack bool
  138. OnSucceed func(rpc string, input []byte)
  139. }
  140. type handler struct {
  141. *Config
  142. w http.ResponseWriter
  143. r *http.Request
  144. Dir string
  145. File string
  146. }
  147. var routes = []route{
  148. {regexp.MustCompile("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  149. {regexp.MustCompile("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  150. {regexp.MustCompile("(.*?)/info/refs$"), "GET", getInfoRefs},
  151. {regexp.MustCompile("(.*?)/HEAD$"), "GET", getTextFile},
  152. {regexp.MustCompile("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  153. {regexp.MustCompile("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  154. {regexp.MustCompile("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  155. {regexp.MustCompile("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  156. {regexp.MustCompile("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  157. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  158. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
  159. }
  160. // Request handling function
  161. func HttpBackend(config *Config) http.HandlerFunc {
  162. return func(w http.ResponseWriter, r *http.Request) {
  163. //log.Printf("%s %s %s %s", r.RemoteAddr, r.Method, r.URL.Path, r.Proto)
  164. for _, route := range routes {
  165. if m := route.cr.FindStringSubmatch(r.URL.Path); m != nil {
  166. if route.method != r.Method {
  167. renderMethodNotAllowed(w, r)
  168. return
  169. }
  170. file := strings.Replace(r.URL.Path, m[1]+"/", "", 1)
  171. dir, err := getGitDir(config, m[1])
  172. if err != nil {
  173. log.Print(err)
  174. renderNotFound(w)
  175. return
  176. }
  177. hr := handler{config, w, r, dir, file}
  178. route.handler(hr)
  179. return
  180. }
  181. }
  182. renderNotFound(w)
  183. return
  184. }
  185. }
  186. // Actual command handling functions
  187. func serviceUploadPack(hr handler) {
  188. serviceRpc("upload-pack", hr)
  189. }
  190. func serviceReceivePack(hr handler) {
  191. serviceRpc("receive-pack", hr)
  192. }
  193. func serviceRpc(rpc string, hr handler) {
  194. w, r, dir := hr.w, hr.r, hr.Dir
  195. access := hasAccess(r, hr.Config, dir, rpc, true)
  196. if access == false {
  197. renderNoAccess(w)
  198. return
  199. }
  200. input, _ := ioutil.ReadAll(r.Body)
  201. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", rpc))
  202. w.WriteHeader(http.StatusOK)
  203. args := []string{rpc, "--stateless-rpc", dir}
  204. cmd := exec.Command(hr.Config.GitBinPath, args...)
  205. cmd.Dir = dir
  206. in, err := cmd.StdinPipe()
  207. if err != nil {
  208. log.Print(err)
  209. return
  210. }
  211. stdout, err := cmd.StdoutPipe()
  212. if err != nil {
  213. log.Print(err)
  214. return
  215. }
  216. err = cmd.Start()
  217. if err != nil {
  218. log.Print(err)
  219. return
  220. }
  221. in.Write(input)
  222. io.Copy(w, stdout)
  223. cmd.Wait()
  224. if hr.Config.OnSucceed != nil {
  225. hr.Config.OnSucceed(rpc, input)
  226. }
  227. }
  228. func getInfoRefs(hr handler) {
  229. w, r, dir := hr.w, hr.r, hr.Dir
  230. serviceName := getServiceType(r)
  231. access := hasAccess(r, hr.Config, dir, serviceName, false)
  232. if access {
  233. args := []string{serviceName, "--stateless-rpc", "--advertise-refs", "."}
  234. refs := gitCommand(hr.Config.GitBinPath, dir, args...)
  235. hdrNocache(w)
  236. w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", serviceName))
  237. w.WriteHeader(http.StatusOK)
  238. w.Write(packetWrite("# service=git-" + serviceName + "\n"))
  239. w.Write(packetFlush())
  240. w.Write(refs)
  241. } else {
  242. updateServerInfo(hr.Config.GitBinPath, dir)
  243. hdrNocache(w)
  244. sendFile("text/plain; charset=utf-8", hr)
  245. }
  246. }
  247. func getInfoPacks(hr handler) {
  248. hdrCacheForever(hr.w)
  249. sendFile("text/plain; charset=utf-8", hr)
  250. }
  251. func getLooseObject(hr handler) {
  252. hdrCacheForever(hr.w)
  253. sendFile("application/x-git-loose-object", hr)
  254. }
  255. func getPackFile(hr handler) {
  256. hdrCacheForever(hr.w)
  257. sendFile("application/x-git-packed-objects", hr)
  258. }
  259. func getIdxFile(hr handler) {
  260. hdrCacheForever(hr.w)
  261. sendFile("application/x-git-packed-objects-toc", hr)
  262. }
  263. func getTextFile(hr handler) {
  264. hdrNocache(hr.w)
  265. sendFile("text/plain", hr)
  266. }
  267. // Logic helping functions
  268. func sendFile(contentType string, hr handler) {
  269. w, r := hr.w, hr.r
  270. reqFile := path.Join(hr.Dir, hr.File)
  271. //fmt.Println("sendFile:", reqFile)
  272. f, err := os.Stat(reqFile)
  273. if os.IsNotExist(err) {
  274. renderNotFound(w)
  275. return
  276. }
  277. w.Header().Set("Content-Type", contentType)
  278. w.Header().Set("Content-Length", fmt.Sprintf("%d", f.Size()))
  279. w.Header().Set("Last-Modified", f.ModTime().Format(http.TimeFormat))
  280. http.ServeFile(w, r, reqFile)
  281. }
  282. func getGitDir(config *Config, fPath string) (string, error) {
  283. root := config.ReposRoot
  284. if root == "" {
  285. cwd, err := os.Getwd()
  286. if err != nil {
  287. log.Print(err)
  288. return "", err
  289. }
  290. root = cwd
  291. }
  292. if !strings.HasSuffix(fPath, ".git") {
  293. fPath = fPath + ".git"
  294. }
  295. f := filepath.Join(root, fPath)
  296. if _, err := os.Stat(f); os.IsNotExist(err) {
  297. return "", err
  298. }
  299. return f, nil
  300. }
  301. func getServiceType(r *http.Request) string {
  302. serviceType := r.FormValue("service")
  303. if s := strings.HasPrefix(serviceType, "git-"); !s {
  304. return ""
  305. }
  306. return strings.Replace(serviceType, "git-", "", 1)
  307. }
  308. func hasAccess(r *http.Request, config *Config, dir string, rpc string, checkContentType bool) bool {
  309. if checkContentType {
  310. if r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", rpc) {
  311. return false
  312. }
  313. }
  314. if !(rpc == "upload-pack" || rpc == "receive-pack") {
  315. return false
  316. }
  317. if rpc == "receive-pack" {
  318. return config.ReceivePack
  319. }
  320. if rpc == "upload-pack" {
  321. return config.UploadPack
  322. }
  323. return getConfigSetting(config.GitBinPath, rpc, dir)
  324. }
  325. func getConfigSetting(gitBinPath, serviceName string, dir string) bool {
  326. serviceName = strings.Replace(serviceName, "-", "", -1)
  327. setting := getGitConfig(gitBinPath, "http."+serviceName, dir)
  328. if serviceName == "uploadpack" {
  329. return setting != "false"
  330. }
  331. return setting == "true"
  332. }
  333. func getGitConfig(gitBinPath, configName string, dir string) string {
  334. args := []string{"config", configName}
  335. out := string(gitCommand(gitBinPath, dir, args...))
  336. return out[0 : len(out)-1]
  337. }
  338. func updateServerInfo(gitBinPath, dir string) []byte {
  339. args := []string{"update-server-info"}
  340. return gitCommand(gitBinPath, dir, args...)
  341. }
  342. func gitCommand(gitBinPath, dir string, args ...string) []byte {
  343. command := exec.Command(gitBinPath, args...)
  344. command.Dir = dir
  345. out, err := command.Output()
  346. if err != nil {
  347. log.Print(err)
  348. }
  349. return out
  350. }
  351. // HTTP error response handling functions
  352. func renderMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  353. if r.Proto == "HTTP/1.1" {
  354. w.WriteHeader(http.StatusMethodNotAllowed)
  355. w.Write([]byte("Method Not Allowed"))
  356. } else {
  357. w.WriteHeader(http.StatusBadRequest)
  358. w.Write([]byte("Bad Request"))
  359. }
  360. }
  361. func renderNotFound(w http.ResponseWriter) {
  362. w.WriteHeader(http.StatusNotFound)
  363. w.Write([]byte("Not Found"))
  364. }
  365. func renderNoAccess(w http.ResponseWriter) {
  366. w.WriteHeader(http.StatusForbidden)
  367. w.Write([]byte("Forbidden"))
  368. }
  369. // Packet-line handling function
  370. func packetFlush() []byte {
  371. return []byte("0000")
  372. }
  373. func packetWrite(str string) []byte {
  374. s := strconv.FormatInt(int64(len(str)+4), 16)
  375. if len(s)%4 != 0 {
  376. s = strings.Repeat("0", 4-len(s)%4) + s
  377. }
  378. return []byte(s + str)
  379. }
  380. // Header writing functions
  381. func hdrNocache(w http.ResponseWriter) {
  382. w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  383. w.Header().Set("Pragma", "no-cache")
  384. w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  385. }
  386. func hdrCacheForever(w http.ResponseWriter) {
  387. now := time.Now().Unix()
  388. expires := now + 31536000
  389. w.Header().Set("Date", fmt.Sprintf("%d", now))
  390. w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  391. w.Header().Set("Cache-Control", "public, max-age=31536000")
  392. }