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