http.go 11 KB

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