http.go 11 KB

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