http.go 11 KB

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