You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

http.go 11KB

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