http.go 13 KB

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