http.go 11 KB

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