http.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "gopkg.in/macaron.v1"
  18. log "unknwon.dev/clog/v2"
  19. "gogs.io/gogs/internal/conf"
  20. "gogs.io/gogs/internal/context"
  21. "gogs.io/gogs/internal/db"
  22. "gogs.io/gogs/internal/lazyregexp"
  23. "gogs.io/gogs/internal/tool"
  24. )
  25. type HTTPContext struct {
  26. *context.Context
  27. OwnerName string
  28. OwnerSalt string
  29. RepoID int64
  30. RepoName string
  31. AuthUser *db.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.PlainText(status, text)
  37. }
  38. func HTTPContexter() macaron.Handler {
  39. return func(c *context.Context) {
  40. if len(conf.HTTP.AccessControlAllowOrigin) > 0 {
  41. // Set CORS headers for browser-based git clients
  42. c.Resp.Header().Set("Access-Control-Allow-Origin", conf.HTTP.AccessControlAllowOrigin)
  43. c.Resp.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, User-Agent")
  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 := db.GetUserByName(ownerName)
  57. if err != nil {
  58. c.NotFoundOrError(err, "get user by name")
  59. return
  60. }
  61. repo, err := db.GetRepositoryByName(owner.ID, repoName)
  62. if err != nil {
  63. c.NotFoundOrError(err, "get repository by name")
  64. return
  65. }
  66. // Authentication is not required for pulling from public repositories.
  67. if isPull && !repo.IsPrivate && !conf.Auth.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 := db.Users.Authenticate(authUsername, authPassword, -1)
  99. if err != nil && !db.IsErrUserNotExist(err) {
  100. c.Error(err, "authenticate user")
  101. return
  102. }
  103. // If username and password combination failed, try again using username as a token.
  104. if authUser == nil {
  105. token, err := db.AccessTokens.GetBySHA(authUsername)
  106. if err != nil {
  107. if db.IsErrAccessTokenNotExist(err) {
  108. askCredentials(c, http.StatusUnauthorized, "")
  109. } else {
  110. c.Error(err, "get access token by SHA")
  111. }
  112. return
  113. }
  114. token.Updated = time.Now()
  115. if err = db.AccessTokens.Save(token); err != nil {
  116. log.Error("Failed to update access token: %v", err)
  117. }
  118. authUser, err = db.GetUserByID(token.UserID)
  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.Error(err, "get user by ID")
  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 := db.AccessModeWrite
  132. if isPull {
  133. mode = db.AccessModeRead
  134. }
  135. has, err := db.HasAccess(authUser.ID, repo, mode)
  136. if err != nil {
  137. c.Error(err, "check access")
  138. return
  139. } else if !has {
  140. askCredentials(c, http.StatusForbidden, "User permission denied")
  141. return
  142. }
  143. if !isPull && repo.IsMirror {
  144. c.PlainText(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 *db.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. log.Error("HTTP.Get: fail to create gzip reader: %v", err)
  208. h.w.WriteHeader(http.StatusInternalServerError)
  209. return
  210. }
  211. }
  212. var stderr bytes.Buffer
  213. cmd := exec.Command("git", service, "--stateless-rpc", h.dir)
  214. if service == "receive-pack" {
  215. cmd.Env = append(os.Environ(), db.ComposeHookEnvs(db.ComposeHookEnvsOptions{
  216. AuthUser: h.authUser,
  217. OwnerName: h.ownerName,
  218. OwnerSalt: h.ownerSalt,
  219. RepoID: h.repoID,
  220. RepoName: h.repoName,
  221. RepoPath: h.dir,
  222. })...)
  223. }
  224. cmd.Dir = h.dir
  225. cmd.Stdout = h.w
  226. cmd.Stderr = &stderr
  227. cmd.Stdin = reqBody
  228. if err = cmd.Run(); err != nil {
  229. log.Error("HTTP.serviceRPC: fail to serve RPC '%s': %v - %s", service, err, stderr.String())
  230. h.w.WriteHeader(http.StatusInternalServerError)
  231. return
  232. }
  233. }
  234. func serviceUploadPack(h serviceHandler) {
  235. serviceRPC(h, "upload-pack")
  236. }
  237. func serviceReceivePack(h serviceHandler) {
  238. serviceRPC(h, "receive-pack")
  239. }
  240. func getServiceType(r *http.Request) string {
  241. serviceType := r.FormValue("service")
  242. if !strings.HasPrefix(serviceType, "git-") {
  243. return ""
  244. }
  245. return strings.TrimPrefix(serviceType, "git-")
  246. }
  247. // FIXME: use process module
  248. func gitCommand(dir string, args ...string) []byte {
  249. cmd := exec.Command("git", args...)
  250. cmd.Dir = dir
  251. out, err := cmd.Output()
  252. if err != nil {
  253. log.Error(fmt.Sprintf("Git: %v - %s", err, out))
  254. }
  255. return out
  256. }
  257. func updateServerInfo(dir string) []byte {
  258. return gitCommand(dir, "update-server-info")
  259. }
  260. func packetWrite(str string) []byte {
  261. s := strconv.FormatInt(int64(len(str)+4), 16)
  262. if len(s)%4 != 0 {
  263. s = strings.Repeat("0", 4-len(s)%4) + s
  264. }
  265. return []byte(s + str)
  266. }
  267. func getInfoRefs(h serviceHandler) {
  268. h.setHeaderNoCache()
  269. service := getServiceType(h.r)
  270. if service != "upload-pack" && service != "receive-pack" {
  271. updateServerInfo(h.dir)
  272. h.sendFile("text/plain; charset=utf-8")
  273. return
  274. }
  275. refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".")
  276. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
  277. h.w.WriteHeader(http.StatusOK)
  278. _, _ = h.w.Write(packetWrite("# service=git-" + service + "\n"))
  279. _, _ = h.w.Write([]byte("0000"))
  280. _, _ = h.w.Write(refs)
  281. }
  282. func getTextFile(h serviceHandler) {
  283. h.setHeaderNoCache()
  284. h.sendFile("text/plain")
  285. }
  286. func getInfoPacks(h serviceHandler) {
  287. h.setHeaderCacheForever()
  288. h.sendFile("text/plain; charset=utf-8")
  289. }
  290. func getLooseObject(h serviceHandler) {
  291. h.setHeaderCacheForever()
  292. h.sendFile("application/x-git-loose-object")
  293. }
  294. func getPackFile(h serviceHandler) {
  295. h.setHeaderCacheForever()
  296. h.sendFile("application/x-git-packed-objects")
  297. }
  298. func getIdxFile(h serviceHandler) {
  299. h.setHeaderCacheForever()
  300. h.sendFile("application/x-git-packed-objects-toc")
  301. }
  302. var routes = []struct {
  303. re *lazyregexp.Regexp
  304. method string
  305. handler func(serviceHandler)
  306. }{
  307. {lazyregexp.New("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  308. {lazyregexp.New("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  309. {lazyregexp.New("(.*?)/info/refs$"), "GET", getInfoRefs},
  310. {lazyregexp.New("(.*?)/HEAD$"), "GET", getTextFile},
  311. {lazyregexp.New("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  312. {lazyregexp.New("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  313. {lazyregexp.New("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  314. {lazyregexp.New("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  315. {lazyregexp.New("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  316. {lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  317. {lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
  318. }
  319. func getGitRepoPath(dir string) (string, error) {
  320. if !strings.HasSuffix(dir, ".git") {
  321. dir += ".git"
  322. }
  323. filename := filepath.Join(conf.Repository.Root, dir)
  324. if _, err := os.Stat(filename); os.IsNotExist(err) {
  325. return "", err
  326. }
  327. return filename, nil
  328. }
  329. func HTTP(c *HTTPContext) {
  330. for _, route := range routes {
  331. reqPath := strings.ToLower(c.Req.URL.Path)
  332. m := route.re.FindStringSubmatch(reqPath)
  333. if m == nil {
  334. continue
  335. }
  336. // We perform check here because route matched in cmd/web.go is wider than needed,
  337. // but we only want to output this message only if user is really trying to access
  338. // Git HTTP endpoints.
  339. if conf.Repository.DisableHTTPGit {
  340. c.PlainText(http.StatusForbidden, "Interacting with repositories by HTTP protocol is disabled")
  341. return
  342. }
  343. if route.method != c.Req.Method {
  344. c.NotFound()
  345. return
  346. }
  347. file := strings.TrimPrefix(reqPath, m[1]+"/")
  348. dir, err := getGitRepoPath(m[1])
  349. if err != nil {
  350. log.Warn("HTTP.getGitRepoPath: %v", err)
  351. c.NotFound()
  352. return
  353. }
  354. route.handler(serviceHandler{
  355. w: c.Resp,
  356. r: c.Req.Request,
  357. dir: dir,
  358. file: file,
  359. authUser: c.AuthUser,
  360. ownerName: c.OwnerName,
  361. ownerSalt: c.OwnerSalt,
  362. repoID: c.RepoID,
  363. repoName: c.RepoName,
  364. })
  365. return
  366. }
  367. c.NotFound()
  368. }