http.go 11 KB

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