http.go 11 KB

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