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. "strconv"
  14. "strings"
  15. "time"
  16. "gopkg.in/macaron.v1"
  17. log "unknwon.dev/clog/v2"
  18. "gogs.io/gogs/internal/conf"
  19. "gogs.io/gogs/internal/context"
  20. "gogs.io/gogs/internal/db"
  21. "gogs.io/gogs/internal/lazyregexp"
  22. "gogs.io/gogs/internal/tool"
  23. )
  24. type HTTPContext struct {
  25. *context.Context
  26. OwnerName string
  27. OwnerSalt string
  28. RepoID int64
  29. RepoName string
  30. AuthUser *db.User
  31. }
  32. // askCredentials responses HTTP header and status which informs client to provide credentials.
  33. func askCredentials(c *context.Context, status int, text string) {
  34. c.Resp.Header().Set("WWW-Authenticate", "Basic realm=\".\"")
  35. c.PlainText(status, text)
  36. }
  37. func HTTPContexter() macaron.Handler {
  38. return func(c *context.Context) {
  39. if len(conf.HTTP.AccessControlAllowOrigin) > 0 {
  40. // Set CORS headers for browser-based git clients
  41. c.Resp.Header().Set("Access-Control-Allow-Origin", conf.HTTP.AccessControlAllowOrigin)
  42. c.Resp.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, User-Agent")
  43. // Handle preflight OPTIONS request
  44. if c.Req.Method == "OPTIONS" {
  45. c.Status(http.StatusOK)
  46. return
  47. }
  48. }
  49. ownerName := c.Params(":username")
  50. repoName := strings.TrimSuffix(c.Params(":reponame"), ".git")
  51. repoName = strings.TrimSuffix(repoName, ".wiki")
  52. isPull := c.Query("service") == "git-upload-pack" ||
  53. strings.HasSuffix(c.Req.URL.Path, "git-upload-pack") ||
  54. c.Req.Method == "GET"
  55. owner, err := db.GetUserByName(ownerName)
  56. if err != nil {
  57. c.NotFoundOrError(err, "get user by name")
  58. return
  59. }
  60. repo, err := db.GetRepositoryByName(owner.ID, repoName)
  61. if err != nil {
  62. c.NotFoundOrError(err, "get repository by name")
  63. return
  64. }
  65. // Authentication is not required for pulling from public repositories.
  66. if isPull && !repo.IsPrivate && !conf.Auth.RequireSigninView {
  67. c.Map(&HTTPContext{
  68. Context: c,
  69. })
  70. return
  71. }
  72. // In case user requested a wrong URL and not intended to access Git objects.
  73. action := c.Params("*")
  74. if !strings.Contains(action, "git-") &&
  75. !strings.Contains(action, "info/") &&
  76. !strings.Contains(action, "HEAD") &&
  77. !strings.Contains(action, "objects/") {
  78. c.NotFound()
  79. return
  80. }
  81. // Handle HTTP Basic Authentication
  82. authHead := c.Req.Header.Get("Authorization")
  83. if len(authHead) == 0 {
  84. askCredentials(c, http.StatusUnauthorized, "")
  85. return
  86. }
  87. auths := strings.Fields(authHead)
  88. if len(auths) != 2 || auths[0] != "Basic" {
  89. askCredentials(c, http.StatusUnauthorized, "")
  90. return
  91. }
  92. authUsername, authPassword, err := tool.BasicAuthDecode(auths[1])
  93. if err != nil {
  94. askCredentials(c, http.StatusUnauthorized, "")
  95. return
  96. }
  97. authUser, err := db.UserLogin(authUsername, authPassword, -1)
  98. if err != nil && !db.IsErrUserNotExist(err) {
  99. c.Error(err, "authenticate user")
  100. return
  101. }
  102. // If username and password combination failed, try again using username as a token.
  103. if authUser == nil {
  104. token, err := db.GetAccessTokenBySHA(authUsername)
  105. if err != nil {
  106. if db.IsErrAccessTokenEmpty(err) || db.IsErrAccessTokenNotExist(err) {
  107. askCredentials(c, http.StatusUnauthorized, "")
  108. } else {
  109. c.Error(err, "get access token by SHA")
  110. }
  111. return
  112. }
  113. token.Updated = time.Now()
  114. // TODO: verify or update token.Updated in database
  115. authUser, err = db.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.Error(err, "get user by ID")
  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 := db.ACCESS_MODE_WRITE
  129. if isPull {
  130. mode = db.ACCESS_MODE_READ
  131. }
  132. has, err := db.HasAccess(authUser.ID, repo, mode)
  133. if err != nil {
  134. c.Error(err, "check access")
  135. return
  136. } else if !has {
  137. askCredentials(c, http.StatusForbidden, "User permission denied")
  138. return
  139. }
  140. if !isPull && repo.IsMirror {
  141. c.PlainText(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 *db.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("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(), db.ComposeHookEnvs(db.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("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(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. re *lazyregexp.Regexp
  301. method string
  302. handler func(serviceHandler)
  303. }{
  304. {lazyregexp.New("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
  305. {lazyregexp.New("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
  306. {lazyregexp.New("(.*?)/info/refs$"), "GET", getInfoRefs},
  307. {lazyregexp.New("(.*?)/HEAD$"), "GET", getTextFile},
  308. {lazyregexp.New("(.*?)/objects/info/alternates$"), "GET", getTextFile},
  309. {lazyregexp.New("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
  310. {lazyregexp.New("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
  311. {lazyregexp.New("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
  312. {lazyregexp.New("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
  313. {lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
  314. {lazyregexp.New("(.*?)/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(conf.Repository.Root, 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.re.FindStringSubmatch(reqPath)
  330. if m == nil {
  331. continue
  332. }
  333. // We perform check here because route 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 conf.Repository.DisableHTTPGit {
  337. c.PlainText(http.StatusForbidden, "Interacting with repositories by HTTP protocol is 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. }