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