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

http.go 15KB

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