http.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. // Copyright 2017 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. "compress/gzip"
  8. "fmt"
  9. "net/http"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/Unknwon/com"
  18. log "gopkg.in/clog.v1"
  19. "gopkg.in/macaron.v1"
  20. "github.com/gogits/gogs/models"
  21. "github.com/gogits/gogs/models/errors"
  22. "github.com/gogits/gogs/pkg/base"
  23. "github.com/gogits/gogs/pkg/context"
  24. "github.com/gogits/gogs/pkg/setting"
  25. )
  26. const (
  27. ENV_AUTH_USER_ID = "GOGS_AUTH_USER_ID"
  28. ENV_AUTH_USER_NAME = "GOGS_AUTH_USER_NAME"
  29. ENV_AUTH_USER_EMAIL = "GOGS_AUTH_USER_EMAIL"
  30. ENV_REPO_OWNER_NAME = "GOGS_REPO_OWNER_NAME"
  31. ENV_REPO_OWNER_SALT_MD5 = "GOGS_REPO_OWNER_SALT_MD5"
  32. ENV_REPO_ID = "GOGS_REPO_ID"
  33. ENV_REPO_NAME = "GOGS_REPO_NAME"
  34. ENV_REPO_CUSTOM_HOOKS_PATH = "GOGS_REPO_CUSTOM_HOOKS_PATH"
  35. )
  36. type HTTPContext struct {
  37. *context.Context
  38. OwnerName string
  39. OwnerSalt string
  40. RepoID int64
  41. RepoName string
  42. AuthUser *models.User
  43. }
  44. // askCredentials responses HTTP header and status which informs client to provide credentials.
  45. func askCredentials(c *context.Context, status int, text string) {
  46. c.Resp.Header().Set("WWW-Authenticate", "Basic realm=\".\"")
  47. c.HandleText(status, text)
  48. }
  49. func HTTPContexter() macaron.Handler {
  50. return func(c *context.Context) {
  51. ownerName := c.Params(":username")
  52. repoName := strings.TrimSuffix(c.Params(":reponame"), ".git")
  53. repoName = strings.TrimSuffix(repoName, ".wiki")
  54. isPull := c.Query("service") == "git-upload-pack" ||
  55. strings.HasSuffix(c.Req.URL.Path, "git-upload-pack") ||
  56. c.Req.Method == "GET"
  57. owner, err := models.GetUserByName(ownerName)
  58. if err != nil {
  59. c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  60. return
  61. }
  62. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  63. if err != nil {
  64. c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
  65. return
  66. }
  67. // Authentication is not required for pulling from public repositories.
  68. if isPull && !repo.IsPrivate && !setting.Service.RequireSignInView {
  69. c.Map(&HTTPContext{
  70. Context: c,
  71. })
  72. return
  73. }
  74. // In case user requested a wrong URL and not intended to access Git objects.
  75. action := c.Params("*")
  76. if !strings.Contains(action, "git-") &&
  77. !strings.Contains(action, "info/") &&
  78. !strings.Contains(action, "HEAD") &&
  79. !strings.Contains(action, "objects/") {
  80. c.NotFound()
  81. return
  82. }
  83. // Handle HTTP Basic Authentication
  84. authHead := c.Req.Header.Get("Authorization")
  85. if len(authHead) == 0 {
  86. askCredentials(c, http.StatusUnauthorized, "")
  87. return
  88. }
  89. auths := strings.Fields(authHead)
  90. if len(auths) != 2 || auths[0] != "Basic" {
  91. askCredentials(c, http.StatusUnauthorized, "")
  92. return
  93. }
  94. authUsername, authPassword, err := base.BasicAuthDecode(auths[1])
  95. if err != nil {
  96. askCredentials(c, http.StatusUnauthorized, "")
  97. return
  98. }
  99. authUser, err := models.UserSignIn(authUsername, authPassword)
  100. if err != nil && !errors.IsUserNotExist(err) {
  101. c.Handle(http.StatusInternalServerError, "UserSignIn", err)
  102. return
  103. }
  104. // If username and password combination failed, try again using username as a token.
  105. if authUser == nil {
  106. token, err := models.GetAccessTokenBySHA(authUsername)
  107. if err != nil {
  108. if models.IsErrAccessTokenEmpty(err) || models.IsErrAccessTokenNotExist(err) {
  109. askCredentials(c, http.StatusUnauthorized, "")
  110. } else {
  111. c.Handle(http.StatusInternalServerError, "GetAccessTokenBySHA", err)
  112. }
  113. return
  114. }
  115. token.Updated = time.Now()
  116. authUser, err = models.GetUserByID(token.UID)
  117. if err != nil {
  118. // Once we found token, we're supposed to find its related user,
  119. // thus any error is unexpected.
  120. c.Handle(http.StatusInternalServerError, "GetUserByID", err)
  121. return
  122. }
  123. }
  124. log.Trace("HTTPGit - Authenticated user: %s", authUser.Name)
  125. mode := models.ACCESS_MODE_WRITE
  126. if isPull {
  127. mode = models.ACCESS_MODE_READ
  128. }
  129. has, err := models.HasAccess(authUser.ID, repo, mode)
  130. if err != nil {
  131. c.Handle(http.StatusInternalServerError, "HasAccess", err)
  132. return
  133. } else if !has {
  134. askCredentials(c, http.StatusUnauthorized, "User permission denied")
  135. return
  136. }
  137. if !isPull && repo.IsMirror {
  138. c.HandleText(http.StatusForbidden, "Mirror repository is read-only")
  139. return
  140. }
  141. c.Map(&HTTPContext{
  142. Context: c,
  143. OwnerName: ownerName,
  144. OwnerSalt: owner.Salt,
  145. RepoID: repo.ID,
  146. RepoName: repoName,
  147. AuthUser: authUser,
  148. })
  149. }
  150. }
  151. type serviceHandler struct {
  152. w http.ResponseWriter
  153. r *http.Request
  154. dir string
  155. file string
  156. authUser *models.User
  157. ownerName string
  158. ownerSalt string
  159. repoID int64
  160. repoName string
  161. }
  162. func (h *serviceHandler) setHeaderNoCache() {
  163. h.w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  164. h.w.Header().Set("Pragma", "no-cache")
  165. h.w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  166. }
  167. func (h *serviceHandler) setHeaderCacheForever() {
  168. now := time.Now().Unix()
  169. expires := now + 31536000
  170. h.w.Header().Set("Date", fmt.Sprintf("%d", now))
  171. h.w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  172. h.w.Header().Set("Cache-Control", "public, max-age=31536000")
  173. }
  174. func (h *serviceHandler) sendFile(contentType string) {
  175. reqFile := path.Join(h.dir, h.file)
  176. fi, err := os.Stat(reqFile)
  177. if os.IsNotExist(err) {
  178. h.w.WriteHeader(http.StatusNotFound)
  179. return
  180. }
  181. h.w.Header().Set("Content-Type", contentType)
  182. h.w.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size()))
  183. h.w.Header().Set("Last-Modified", fi.ModTime().Format(http.TimeFormat))
  184. http.ServeFile(h.w, h.r, reqFile)
  185. }
  186. type ComposeHookEnvsOptions struct {
  187. AuthUser *models.User
  188. OwnerName string
  189. OwnerSalt string
  190. RepoID int64
  191. RepoName string
  192. RepoPath string
  193. }
  194. func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
  195. envs := []string{
  196. "SSH_ORIGINAL_COMMAND=1",
  197. ENV_AUTH_USER_ID + "=" + com.ToStr(opts.AuthUser.ID),
  198. ENV_AUTH_USER_NAME + "=" + opts.AuthUser.Name,
  199. ENV_AUTH_USER_EMAIL + "=" + opts.AuthUser.Email,
  200. ENV_REPO_OWNER_NAME + "=" + opts.OwnerName,
  201. ENV_REPO_OWNER_SALT_MD5 + "=" + base.EncodeMD5(opts.OwnerSalt),
  202. ENV_REPO_ID + "=" + com.ToStr(opts.RepoID),
  203. ENV_REPO_NAME + "=" + opts.RepoName,
  204. ENV_REPO_CUSTOM_HOOKS_PATH + "=" + path.Join(opts.RepoPath, "custom_hooks"),
  205. }
  206. return envs
  207. }
  208. func serviceRPC(h serviceHandler, service string) {
  209. defer h.r.Body.Close()
  210. if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) {
  211. h.w.WriteHeader(http.StatusUnauthorized)
  212. return
  213. }
  214. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service))
  215. var (
  216. reqBody = h.r.Body
  217. err error
  218. )
  219. // Handle GZIP
  220. if h.r.Header.Get("Content-Encoding") == "gzip" {
  221. reqBody, err = gzip.NewReader(reqBody)
  222. if err != nil {
  223. log.Error(2, "HTTP.Get: fail to create gzip reader: %v", err)
  224. h.w.WriteHeader(http.StatusInternalServerError)
  225. return
  226. }
  227. }
  228. var stderr bytes.Buffer
  229. cmd := exec.Command("git", service, "--stateless-rpc", h.dir)
  230. if service == "receive-pack" {
  231. cmd.Env = append(os.Environ(), ComposeHookEnvs(ComposeHookEnvsOptions{
  232. AuthUser: h.authUser,
  233. OwnerName: h.ownerName,
  234. OwnerSalt: h.ownerSalt,
  235. RepoID: h.repoID,
  236. RepoName: h.repoName,
  237. RepoPath: h.dir,
  238. })...)
  239. }
  240. cmd.Dir = h.dir
  241. cmd.Stdout = h.w
  242. cmd.Stderr = &stderr
  243. cmd.Stdin = reqBody
  244. if err = cmd.Run(); err != nil {
  245. log.Error(2, "HTTP.serviceRPC: fail to serve RPC '%s': %v - %s", service, err, stderr)
  246. h.w.WriteHeader(http.StatusInternalServerError)
  247. return
  248. }
  249. }
  250. func serviceUploadPack(h serviceHandler) {
  251. serviceRPC(h, "upload-pack")
  252. }
  253. func serviceReceivePack(h serviceHandler) {
  254. serviceRPC(h, "receive-pack")
  255. }
  256. func getServiceType(r *http.Request) string {
  257. serviceType := r.FormValue("service")
  258. if !strings.HasPrefix(serviceType, "git-") {
  259. return ""
  260. }
  261. return strings.TrimPrefix(serviceType, "git-")
  262. }
  263. // FIXME: use process module
  264. func gitCommand(dir string, args ...string) []byte {
  265. cmd := exec.Command("git", args...)
  266. cmd.Dir = dir
  267. out, err := cmd.Output()
  268. if err != nil {
  269. log.Error(2, fmt.Sprintf("Git: %v - %s", err, out))
  270. }
  271. return out
  272. }
  273. func updateServerInfo(dir string) []byte {
  274. return gitCommand(dir, "update-server-info")
  275. }
  276. func packetWrite(str string) []byte {
  277. s := strconv.FormatInt(int64(len(str)+4), 16)
  278. if len(s)%4 != 0 {
  279. s = strings.Repeat("0", 4-len(s)%4) + s
  280. }
  281. return []byte(s + str)
  282. }
  283. func getInfoRefs(h serviceHandler) {
  284. h.setHeaderNoCache()
  285. service := getServiceType(h.r)
  286. if service != "upload-pack" && service != "receive-pack" {
  287. updateServerInfo(h.dir)
  288. h.sendFile("text/plain; charset=utf-8")
  289. return
  290. }
  291. refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".")
  292. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
  293. h.w.WriteHeader(http.StatusOK)
  294. h.w.Write(packetWrite("# service=git-" + service + "\n"))
  295. h.w.Write([]byte("0000"))
  296. h.w.Write(refs)
  297. }
  298. func getTextFile(h serviceHandler) {
  299. h.setHeaderNoCache()
  300. h.sendFile("text/plain")
  301. }
  302. func getInfoPacks(h serviceHandler) {
  303. h.setHeaderCacheForever()
  304. h.sendFile("text/plain; charset=utf-8")
  305. }
  306. func getLooseObject(h serviceHandler) {
  307. h.setHeaderCacheForever()
  308. h.sendFile("application/x-git-loose-object")
  309. }
  310. func getPackFile(h serviceHandler) {
  311. h.setHeaderCacheForever()
  312. h.sendFile("application/x-git-packed-objects")
  313. }
  314. func getIdxFile(h serviceHandler) {
  315. h.setHeaderCacheForever()
  316. h.sendFile("application/x-git-packed-objects-toc")
  317. }
  318. var routes = []struct {
  319. reg *regexp.Regexp
  320. method string
  321. handler func(serviceHandler)
  322. }{
  323. {regexp.MustCompile("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  324. {regexp.MustCompile("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  325. {regexp.MustCompile("(.*?)/info/refs$"), "GET", getInfoRefs},
  326. {regexp.MustCompile("(.*?)/HEAD$"), "GET", getTextFile},
  327. {regexp.MustCompile("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  328. {regexp.MustCompile("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  329. {regexp.MustCompile("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  330. {regexp.MustCompile("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  331. {regexp.MustCompile("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  332. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  333. {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
  334. }
  335. func getGitRepoPath(dir string) (string, error) {
  336. if !strings.HasSuffix(dir, ".git") {
  337. dir += ".git"
  338. }
  339. filename := path.Join(setting.RepoRootPath, dir)
  340. if _, err := os.Stat(filename); os.IsNotExist(err) {
  341. return "", err
  342. }
  343. return filename, nil
  344. }
  345. func HTTP(ctx *HTTPContext) {
  346. for _, route := range routes {
  347. reqPath := strings.ToLower(ctx.Req.URL.Path)
  348. m := route.reg.FindStringSubmatch(reqPath)
  349. if m == nil {
  350. continue
  351. }
  352. // We perform check here because routes matched in cmd/web.go is wider than needed,
  353. // but we only want to output this message only if user is really trying to access
  354. // Git HTTP endpoints.
  355. if setting.Repository.DisableHTTPGit {
  356. ctx.HandleText(http.StatusForbidden, "Interacting with repositories by HTTP protocol is not disabled")
  357. return
  358. }
  359. if route.method != ctx.Req.Method {
  360. ctx.NotFound()
  361. return
  362. }
  363. file := strings.TrimPrefix(reqPath, m[1]+"/")
  364. dir, err := getGitRepoPath(m[1])
  365. if err != nil {
  366. log.Warn("HTTP.getGitRepoPath: %v", err)
  367. ctx.NotFound()
  368. return
  369. }
  370. route.handler(serviceHandler{
  371. w: ctx.Resp,
  372. r: ctx.Req.Request,
  373. dir: dir,
  374. file: file,
  375. authUser: ctx.AuthUser,
  376. ownerName: ctx.OwnerName,
  377. ownerSalt: ctx.OwnerSalt,
  378. repoID: ctx.RepoID,
  379. repoName: ctx.RepoName,
  380. })
  381. return
  382. }
  383. ctx.NotFound()
  384. }