http.go 12 KB

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