http.go 11 KB

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