You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

http.go 16 kB

11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "bytes"
  8. "compress/gzip"
  9. "fmt"
  10. "net/http"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "regexp"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "code.gitea.io/gitea/models"
  19. "code.gitea.io/gitea/modules/auth"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/context"
  22. "code.gitea.io/gitea/modules/git"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/setting"
  25. "code.gitea.io/gitea/modules/util"
  26. )
  27. // HTTP implmentation git smart HTTP protocol
  28. func HTTP(ctx *context.Context) {
  29. if len(setting.Repository.AccessControlAllowOrigin) > 0 {
  30. allowedOrigin := setting.Repository.AccessControlAllowOrigin
  31. // Set CORS headers for browser-based git clients
  32. ctx.Resp.Header().Set("Access-Control-Allow-Origin", allowedOrigin)
  33. ctx.Resp.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, User-Agent")
  34. // Handle preflight OPTIONS request
  35. if ctx.Req.Method == "OPTIONS" {
  36. if allowedOrigin == "*" {
  37. ctx.Status(http.StatusOK)
  38. } else if allowedOrigin == "null" {
  39. ctx.Status(http.StatusForbidden)
  40. } else {
  41. origin := ctx.Req.Header.Get("Origin")
  42. if len(origin) > 0 && origin == allowedOrigin {
  43. ctx.Status(http.StatusOK)
  44. } else {
  45. ctx.Status(http.StatusForbidden)
  46. }
  47. }
  48. return
  49. }
  50. }
  51. username := ctx.Params(":username")
  52. reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
  53. if ctx.Query("go-get") == "1" {
  54. context.EarlyResponseForGoGetMeta(ctx)
  55. return
  56. }
  57. var isPull bool
  58. service := ctx.Query("service")
  59. if service == "git-receive-pack" ||
  60. strings.HasSuffix(ctx.Req.URL.Path, "git-receive-pack") {
  61. isPull = false
  62. } else if service == "git-upload-pack" ||
  63. strings.HasSuffix(ctx.Req.URL.Path, "git-upload-pack") {
  64. isPull = true
  65. } else if service == "git-upload-archive" ||
  66. strings.HasSuffix(ctx.Req.URL.Path, "git-upload-archive") {
  67. isPull = true
  68. } else {
  69. isPull = (ctx.Req.Method == "GET")
  70. }
  71. var accessMode models.AccessMode
  72. if isPull {
  73. accessMode = models.AccessModeRead
  74. } else {
  75. accessMode = models.AccessModeWrite
  76. }
  77. isWiki := false
  78. var unitType = models.UnitTypeCode
  79. if strings.HasSuffix(reponame, ".wiki") {
  80. isWiki = true
  81. unitType = models.UnitTypeWiki
  82. reponame = reponame[:len(reponame)-5]
  83. }
  84. owner, err := models.GetUserByName(username)
  85. if err != nil {
  86. ctx.NotFoundOrServerError("GetUserByName", models.IsErrUserNotExist, err)
  87. return
  88. }
  89. repo, err := models.GetRepositoryByName(owner.ID, reponame)
  90. if err != nil {
  91. if models.IsErrRepoNotExist(err) {
  92. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, reponame)
  93. if err == nil {
  94. context.RedirectToRepo(ctx, redirectRepoID)
  95. } else {
  96. ctx.NotFoundOrServerError("GetRepositoryByName", models.IsErrRepoRedirectNotExist, err)
  97. }
  98. } else {
  99. ctx.ServerError("GetRepositoryByName", err)
  100. }
  101. return
  102. }
  103. // Don't allow pushing if the repo is archived
  104. if repo.IsArchived && !isPull {
  105. ctx.HandleText(http.StatusForbidden, "This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.")
  106. return
  107. }
  108. // Only public pull don't need auth.
  109. isPublicPull := !repo.IsPrivate && isPull
  110. var (
  111. askAuth = !isPublicPull || setting.Service.RequireSignInView
  112. authUser *models.User
  113. authUsername string
  114. authPasswd string
  115. environ []string
  116. )
  117. // check access
  118. if askAuth {
  119. authUsername = ctx.Req.Header.Get(setting.ReverseProxyAuthUser)
  120. if setting.Service.EnableReverseProxyAuth && len(authUsername) > 0 {
  121. authUser, err = models.GetUserByName(authUsername)
  122. if err != nil {
  123. ctx.HandleText(401, "reverse proxy login error, got error while running GetUserByName")
  124. return
  125. }
  126. } else {
  127. authHead := ctx.Req.Header.Get("Authorization")
  128. if len(authHead) == 0 {
  129. ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=\".\"")
  130. ctx.Error(http.StatusUnauthorized)
  131. return
  132. }
  133. auths := strings.Fields(authHead)
  134. // currently check basic auth
  135. // TODO: support digit auth
  136. // FIXME: middlewares/context.go did basic auth check already,
  137. // maybe could use that one.
  138. if len(auths) != 2 || auths[0] != "Basic" {
  139. ctx.HandleText(http.StatusUnauthorized, "no basic auth and digit auth")
  140. return
  141. }
  142. authUsername, authPasswd, err = base.BasicAuthDecode(auths[1])
  143. if err != nil {
  144. ctx.HandleText(http.StatusUnauthorized, "no basic auth and digit auth")
  145. return
  146. }
  147. // Check if username or password is a token
  148. isUsernameToken := len(authPasswd) == 0 || authPasswd == "x-oauth-basic"
  149. // Assume username is token
  150. authToken := authUsername
  151. if !isUsernameToken {
  152. // Assume password is token
  153. authToken = authPasswd
  154. }
  155. uid := auth.CheckOAuthAccessToken(authToken)
  156. if uid != 0 {
  157. ctx.Data["IsApiToken"] = true
  158. authUser, err = models.GetUserByID(uid)
  159. if err != nil {
  160. ctx.ServerError("GetUserByID", err)
  161. return
  162. }
  163. }
  164. // Assume password is a token.
  165. token, err := models.GetAccessTokenBySHA(authToken)
  166. if err == nil {
  167. if isUsernameToken {
  168. authUser, err = models.GetUserByID(token.UID)
  169. if err != nil {
  170. ctx.ServerError("GetUserByID", err)
  171. return
  172. }
  173. } else {
  174. authUser, err = models.GetUserByName(authUsername)
  175. if err != nil {
  176. if models.IsErrUserNotExist(err) {
  177. ctx.HandleText(http.StatusUnauthorized, "invalid credentials")
  178. } else {
  179. ctx.ServerError("GetUserByName", err)
  180. }
  181. return
  182. }
  183. if authUser.ID != token.UID {
  184. ctx.HandleText(http.StatusUnauthorized, "invalid credentials")
  185. return
  186. }
  187. }
  188. token.UpdatedUnix = util.TimeStampNow()
  189. if err = models.UpdateAccessToken(token); err != nil {
  190. ctx.ServerError("UpdateAccessToken", err)
  191. }
  192. } else if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) {
  193. log.Error("GetAccessTokenBySha: %v", err)
  194. }
  195. if authUser == nil {
  196. // Check username and password
  197. authUser, err = models.UserSignIn(authUsername, authPasswd)
  198. if err != nil {
  199. if !models.IsErrUserNotExist(err) {
  200. ctx.ServerError("UserSignIn error: %v", err)
  201. return
  202. }
  203. }
  204. if authUser == nil {
  205. ctx.HandleText(http.StatusUnauthorized, "invalid credentials")
  206. return
  207. }
  208. _, err = models.GetTwoFactorByUID(authUser.ID)
  209. if err == nil {
  210. // TODO: This response should be changed to "invalid credentials" for security reasons once the expectation behind it (creating an app token to authenticate) is properly documented
  211. ctx.HandleText(http.StatusUnauthorized, "Users with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password. Please create and use a personal access token on the user settings page")
  212. return
  213. } else if !models.IsErrTwoFactorNotEnrolled(err) {
  214. ctx.ServerError("IsErrTwoFactorNotEnrolled", err)
  215. return
  216. }
  217. }
  218. }
  219. perm, err := models.GetUserRepoPermission(repo, authUser)
  220. if err != nil {
  221. ctx.ServerError("GetUserRepoPermission", err)
  222. return
  223. }
  224. if !perm.CanAccess(accessMode, unitType) {
  225. ctx.HandleText(http.StatusForbidden, "User permission denied")
  226. return
  227. }
  228. if !isPull && repo.IsMirror {
  229. ctx.HandleText(http.StatusForbidden, "mirror repository is read-only")
  230. return
  231. }
  232. environ = []string{
  233. models.EnvRepoUsername + "=" + username,
  234. models.EnvRepoName + "=" + reponame,
  235. models.EnvPusherName + "=" + authUser.Name,
  236. models.EnvPusherID + fmt.Sprintf("=%d", authUser.ID),
  237. models.ProtectedBranchRepoID + fmt.Sprintf("=%d", repo.ID),
  238. }
  239. if !authUser.KeepEmailPrivate {
  240. environ = append(environ, models.EnvPusherEmail+"="+authUser.Email)
  241. }
  242. if isWiki {
  243. environ = append(environ, models.EnvRepoIsWiki+"=true")
  244. } else {
  245. environ = append(environ, models.EnvRepoIsWiki+"=false")
  246. }
  247. }
  248. HTTPBackend(ctx, &serviceConfig{
  249. UploadPack: true,
  250. ReceivePack: true,
  251. Env: environ,
  252. })(ctx.Resp, ctx.Req.Request)
  253. }
  254. type serviceConfig struct {
  255. UploadPack bool
  256. ReceivePack bool
  257. Env []string
  258. }
  259. type serviceHandler struct {
  260. cfg *serviceConfig
  261. w http.ResponseWriter
  262. r *http.Request
  263. dir string
  264. file string
  265. environ []string
  266. }
  267. func (h *serviceHandler) setHeaderNoCache() {
  268. h.w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  269. h.w.Header().Set("Pragma", "no-cache")
  270. h.w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  271. }
  272. func (h *serviceHandler) setHeaderCacheForever() {
  273. now := time.Now().Unix()
  274. expires := now + 31536000
  275. h.w.Header().Set("Date", fmt.Sprintf("%d", now))
  276. h.w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  277. h.w.Header().Set("Cache-Control", "public, max-age=31536000")
  278. }
  279. func (h *serviceHandler) sendFile(contentType string) {
  280. reqFile := path.Join(h.dir, h.file)
  281. fi, err := os.Stat(reqFile)
  282. if os.IsNotExist(err) {
  283. h.w.WriteHeader(http.StatusNotFound)
  284. return
  285. }
  286. h.w.Header().Set("Content-Type", contentType)
  287. h.w.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size()))
  288. h.w.Header().Set("Last-Modified", fi.ModTime().Format(http.TimeFormat))
  289. http.ServeFile(h.w, h.r, reqFile)
  290. }
  291. type route struct {
  292. reg *regexp.Regexp
  293. method string
  294. handler func(serviceHandler)
  295. }
  296. var routes = []route{
  297. {regexp.MustCompile(`(.*?)/git-upload-pack$`), "POST", serviceUploadPack},
  298. {regexp.MustCompile(`(.*?)/git-receive-pack$`), "POST", serviceReceivePack},
  299. {regexp.MustCompile(`(.*?)/info/refs$`), "GET", getInfoRefs},
  300. {regexp.MustCompile(`(.*?)/HEAD$`), "GET", getTextFile},
  301. {regexp.MustCompile(`(.*?)/objects/info/alternates$`), "GET", getTextFile},
  302. {regexp.MustCompile(`(.*?)/objects/info/http-alternates$`), "GET", getTextFile},
  303. {regexp.MustCompile(`(.*?)/objects/info/packs$`), "GET", getInfoPacks},
  304. {regexp.MustCompile(`(.*?)/objects/info/[^/]*$`), "GET", getTextFile},
  305. {regexp.MustCompile(`(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$`), "GET", getLooseObject},
  306. {regexp.MustCompile(`(.*?)/objects/pack/pack-[0-9a-f]{40}\.pack$`), "GET", getPackFile},
  307. {regexp.MustCompile(`(.*?)/objects/pack/pack-[0-9a-f]{40}\.idx$`), "GET", getIdxFile},
  308. }
  309. func getGitConfig(option, dir string) string {
  310. out, err := git.NewCommand("config", option).RunInDir(dir)
  311. if err != nil {
  312. log.Error("%v - %s", err, out)
  313. }
  314. return out[0 : len(out)-1]
  315. }
  316. func getConfigSetting(service, dir string) bool {
  317. service = strings.Replace(service, "-", "", -1)
  318. setting := getGitConfig("http."+service, dir)
  319. if service == "uploadpack" {
  320. return setting != "false"
  321. }
  322. return setting == "true"
  323. }
  324. func hasAccess(service string, h serviceHandler, checkContentType bool) bool {
  325. if checkContentType {
  326. if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) {
  327. return false
  328. }
  329. }
  330. if !(service == "upload-pack" || service == "receive-pack") {
  331. return false
  332. }
  333. if service == "receive-pack" {
  334. return h.cfg.ReceivePack
  335. }
  336. if service == "upload-pack" {
  337. return h.cfg.UploadPack
  338. }
  339. return getConfigSetting(service, h.dir)
  340. }
  341. func serviceRPC(h serviceHandler, service string) {
  342. defer func() {
  343. if err := h.r.Body.Close(); err != nil {
  344. log.Error("serviceRPC: Close: %v", err)
  345. }
  346. }()
  347. if !hasAccess(service, h, true) {
  348. h.w.WriteHeader(http.StatusUnauthorized)
  349. return
  350. }
  351. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service))
  352. var err error
  353. var reqBody = h.r.Body
  354. // Handle GZIP.
  355. if h.r.Header.Get("Content-Encoding") == "gzip" {
  356. reqBody, err = gzip.NewReader(reqBody)
  357. if err != nil {
  358. log.Error("Fail to create gzip reader: %v", err)
  359. h.w.WriteHeader(http.StatusInternalServerError)
  360. return
  361. }
  362. }
  363. // set this for allow pre-receive and post-receive execute
  364. h.environ = append(h.environ, "SSH_ORIGINAL_COMMAND="+service)
  365. var stderr bytes.Buffer
  366. cmd := exec.Command(git.GitExecutable, service, "--stateless-rpc", h.dir)
  367. cmd.Dir = h.dir
  368. if service == "receive-pack" {
  369. cmd.Env = append(os.Environ(), h.environ...)
  370. }
  371. cmd.Stdout = h.w
  372. cmd.Stdin = reqBody
  373. cmd.Stderr = &stderr
  374. if err := cmd.Run(); err != nil {
  375. log.Error("Fail to serve RPC(%s): %v - %v", service, err, stderr)
  376. return
  377. }
  378. }
  379. func serviceUploadPack(h serviceHandler) {
  380. serviceRPC(h, "upload-pack")
  381. }
  382. func serviceReceivePack(h serviceHandler) {
  383. serviceRPC(h, "receive-pack")
  384. }
  385. func getServiceType(r *http.Request) string {
  386. serviceType := r.FormValue("service")
  387. if !strings.HasPrefix(serviceType, "git-") {
  388. return ""
  389. }
  390. return strings.Replace(serviceType, "git-", "", 1)
  391. }
  392. func updateServerInfo(dir string) []byte {
  393. out, err := git.NewCommand("update-server-info").RunInDirBytes(dir)
  394. if err != nil {
  395. log.Error(fmt.Sprintf("%v - %s", err, string(out)))
  396. }
  397. return out
  398. }
  399. func packetWrite(str string) []byte {
  400. s := strconv.FormatInt(int64(len(str)+4), 16)
  401. if len(s)%4 != 0 {
  402. s = strings.Repeat("0", 4-len(s)%4) + s
  403. }
  404. return []byte(s + str)
  405. }
  406. func getInfoRefs(h serviceHandler) {
  407. h.setHeaderNoCache()
  408. if hasAccess(getServiceType(h.r), h, false) {
  409. service := getServiceType(h.r)
  410. refs, err := git.NewCommand(service, "--stateless-rpc", "--advertise-refs", ".").RunInDirBytes(h.dir)
  411. if err != nil {
  412. log.Error(fmt.Sprintf("%v - %s", err, string(refs)))
  413. }
  414. h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
  415. h.w.WriteHeader(http.StatusOK)
  416. _, _ = h.w.Write(packetWrite("# service=git-" + service + "\n"))
  417. _, _ = h.w.Write([]byte("0000"))
  418. _, _ = h.w.Write(refs)
  419. } else {
  420. updateServerInfo(h.dir)
  421. h.sendFile("text/plain; charset=utf-8")
  422. }
  423. }
  424. func getTextFile(h serviceHandler) {
  425. h.setHeaderNoCache()
  426. h.sendFile("text/plain")
  427. }
  428. func getInfoPacks(h serviceHandler) {
  429. h.setHeaderCacheForever()
  430. h.sendFile("text/plain; charset=utf-8")
  431. }
  432. func getLooseObject(h serviceHandler) {
  433. h.setHeaderCacheForever()
  434. h.sendFile("application/x-git-loose-object")
  435. }
  436. func getPackFile(h serviceHandler) {
  437. h.setHeaderCacheForever()
  438. h.sendFile("application/x-git-packed-objects")
  439. }
  440. func getIdxFile(h serviceHandler) {
  441. h.setHeaderCacheForever()
  442. h.sendFile("application/x-git-packed-objects-toc")
  443. }
  444. func getGitRepoPath(subdir string) (string, error) {
  445. if !strings.HasSuffix(subdir, ".git") {
  446. subdir += ".git"
  447. }
  448. fpath := path.Join(setting.RepoRootPath, subdir)
  449. if _, err := os.Stat(fpath); os.IsNotExist(err) {
  450. return "", err
  451. }
  452. return fpath, nil
  453. }
  454. // HTTPBackend middleware for git smart HTTP protocol
  455. func HTTPBackend(ctx *context.Context, cfg *serviceConfig) http.HandlerFunc {
  456. return func(w http.ResponseWriter, r *http.Request) {
  457. for _, route := range routes {
  458. r.URL.Path = strings.ToLower(r.URL.Path) // blue: In case some repo name has upper case name
  459. if m := route.reg.FindStringSubmatch(r.URL.Path); m != nil {
  460. if setting.Repository.DisableHTTPGit {
  461. w.WriteHeader(http.StatusForbidden)
  462. _, err := w.Write([]byte("Interacting with repositories by HTTP protocol is not allowed"))
  463. if err != nil {
  464. log.Error(err.Error())
  465. }
  466. return
  467. }
  468. if route.method != r.Method {
  469. if r.Proto == "HTTP/1.1" {
  470. w.WriteHeader(http.StatusMethodNotAllowed)
  471. _, err := w.Write([]byte("Method Not Allowed"))
  472. if err != nil {
  473. log.Error(err.Error())
  474. }
  475. } else {
  476. w.WriteHeader(http.StatusBadRequest)
  477. _, err := w.Write([]byte("Bad Request"))
  478. if err != nil {
  479. log.Error(err.Error())
  480. }
  481. }
  482. return
  483. }
  484. file := strings.Replace(r.URL.Path, m[1]+"/", "", 1)
  485. dir, err := getGitRepoPath(m[1])
  486. if err != nil {
  487. log.Error(err.Error())
  488. ctx.NotFound("HTTPBackend", err)
  489. return
  490. }
  491. route.handler(serviceHandler{cfg, w, r, dir, file, cfg.Env})
  492. return
  493. }
  494. }
  495. ctx.NotFound("HTTPBackend", nil)
  496. }
  497. }