http.go 12 KB

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