mirror of https://github.com/gogits/gogs.git
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.
448 lines
12 KiB
448 lines
12 KiB
8 years ago
|
// Copyright 2017 The Gogs Authors. All rights reserved.
|
||
11 years ago
|
// Use of this source code is governed by a MIT-style
|
||
|
// license that can be found in the LICENSE file.
|
||
|
|
||
11 years ago
|
package repo
|
||
|
|
||
|
import (
|
||
11 years ago
|
"bytes"
|
||
10 years ago
|
"compress/gzip"
|
||
11 years ago
|
"fmt"
|
||
|
"net/http"
|
||
|
"os"
|
||
|
"os/exec"
|
||
|
"path"
|
||
|
"regexp"
|
||
|
"strconv"
|
||
|
"strings"
|
||
|
"time"
|
||
|
|
||
8 years ago
|
"github.com/Unknwon/com"
|
||
8 years ago
|
log "gopkg.in/clog.v1"
|
||
8 years ago
|
"gopkg.in/macaron.v1"
|
||
8 years ago
|
|
||
11 years ago
|
"github.com/gogits/gogs/models"
|
||
8 years ago
|
"github.com/gogits/gogs/models/errors"
|
||
8 years ago
|
"github.com/gogits/gogs/pkg/context"
|
||
|
"github.com/gogits/gogs/pkg/setting"
|
||
8 years ago
|
"github.com/gogits/gogs/pkg/tool"
|
||
11 years ago
|
)
|
||
|
|
||
8 years ago
|
const (
|
||
8 years ago
|
ENV_AUTH_USER_ID = "GOGS_AUTH_USER_ID"
|
||
|
ENV_AUTH_USER_NAME = "GOGS_AUTH_USER_NAME"
|
||
8 years ago
|
ENV_AUTH_USER_EMAIL = "GOGS_AUTH_USER_EMAIL"
|
||
8 years ago
|
ENV_REPO_OWNER_NAME = "GOGS_REPO_OWNER_NAME"
|
||
|
ENV_REPO_OWNER_SALT_MD5 = "GOGS_REPO_OWNER_SALT_MD5"
|
||
|
ENV_REPO_ID = "GOGS_REPO_ID"
|
||
|
ENV_REPO_NAME = "GOGS_REPO_NAME"
|
||
|
ENV_REPO_CUSTOM_HOOKS_PATH = "GOGS_REPO_CUSTOM_HOOKS_PATH"
|
||
8 years ago
|
)
|
||
11 years ago
|
|
||
8 years ago
|
type HTTPContext struct {
|
||
|
*context.Context
|
||
|
OwnerName string
|
||
|
OwnerSalt string
|
||
8 years ago
|
RepoID int64
|
||
8 years ago
|
RepoName string
|
||
|
AuthUser *models.User
|
||
|
}
|
||
9 years ago
|
|
||
8 years ago
|
// askCredentials responses HTTP header and status which informs client to provide credentials.
|
||
|
func askCredentials(c *context.Context, status int, text string) {
|
||
|
c.Resp.Header().Set("WWW-Authenticate", "Basic realm=\".\"")
|
||
|
c.HandleText(status, text)
|
||
|
}
|
||
|
|
||
8 years ago
|
func HTTPContexter() macaron.Handler {
|
||
8 years ago
|
return func(c *context.Context) {
|
||
|
ownerName := c.Params(":username")
|
||
|
repoName := strings.TrimSuffix(c.Params(":reponame"), ".git")
|
||
8 years ago
|
repoName = strings.TrimSuffix(repoName, ".wiki")
|
||
|
|
||
8 years ago
|
isPull := c.Query("service") == "git-upload-pack" ||
|
||
|
strings.HasSuffix(c.Req.URL.Path, "git-upload-pack") ||
|
||
|
c.Req.Method == "GET"
|
||
8 years ago
|
|
||
|
owner, err := models.GetUserByName(ownerName)
|
||
|
if err != nil {
|
||
8 years ago
|
c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
|
||
8 years ago
|
return
|
||
11 years ago
|
}
|
||
11 years ago
|
|
||
8 years ago
|
repo, err := models.GetRepositoryByName(owner.ID, repoName)
|
||
|
if err != nil {
|
||
8 years ago
|
c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
|
||
8 years ago
|
return
|
||
11 years ago
|
}
|
||
11 years ago
|
|
||
8 years ago
|
// Authentication is not required for pulling from public repositories.
|
||
|
if isPull && !repo.IsPrivate && !setting.Service.RequireSignInView {
|
||
8 years ago
|
c.Map(&HTTPContext{
|
||
|
Context: c,
|
||
8 years ago
|
})
|
||
|
return
|
||
|
}
|
||
11 years ago
|
|
||
8 years ago
|
// In case user requested a wrong URL and not intended to access Git objects.
|
||
8 years ago
|
action := c.Params("*")
|
||
8 years ago
|
if !strings.Contains(action, "git-") &&
|
||
|
!strings.Contains(action, "info/") &&
|
||
|
!strings.Contains(action, "HEAD") &&
|
||
|
!strings.Contains(action, "objects/") {
|
||
8 years ago
|
c.NotFound()
|
||
8 years ago
|
return
|
||
|
}
|
||
|
|
||
8 years ago
|
// Handle HTTP Basic Authentication
|
||
8 years ago
|
authHead := c.Req.Header.Get("Authorization")
|
||
9 years ago
|
if len(authHead) == 0 {
|
||
8 years ago
|
askCredentials(c, http.StatusUnauthorized, "")
|
||
11 years ago
|
return
|
||
|
}
|
||
|
|
||
9 years ago
|
auths := strings.Fields(authHead)
|
||
11 years ago
|
if len(auths) != 2 || auths[0] != "Basic" {
|
||
8 years ago
|
askCredentials(c, http.StatusUnauthorized, "")
|
||
11 years ago
|
return
|
||
|
}
|
||
8 years ago
|
authUsername, authPassword, err := tool.BasicAuthDecode(auths[1])
|
||
11 years ago
|
if err != nil {
|
||
8 years ago
|
askCredentials(c, http.StatusUnauthorized, "")
|
||
11 years ago
|
return
|
||
|
}
|
||
|
|
||
8 years ago
|
authUser, err := models.UserSignIn(authUsername, authPassword)
|
||
8 years ago
|
if err != nil && !errors.IsUserNotExist(err) {
|
||
8 years ago
|
c.Handle(http.StatusInternalServerError, "UserSignIn", err)
|
||
8 years ago
|
return
|
||
|
}
|
||
10 years ago
|
|
||
8 years ago
|
// If username and password combination failed, try again using username as a token.
|
||
|
if authUser == nil {
|
||
9 years ago
|
token, err := models.GetAccessTokenBySHA(authUsername)
|
||
10 years ago
|
if err != nil {
|
||
8 years ago
|
if models.IsErrAccessTokenEmpty(err) || models.IsErrAccessTokenNotExist(err) {
|
||
8 years ago
|
askCredentials(c, http.StatusUnauthorized, "")
|
||
8 years ago
|
} else {
|
||
8 years ago
|
c.Handle(http.StatusInternalServerError, "GetAccessTokenBySHA", err)
|
||
8 years ago
|
}
|
||
10 years ago
|
return
|
||
10 years ago
|
}
|
||
9 years ago
|
token.Updated = time.Now()
|
||
8 years ago
|
|
||
10 years ago
|
authUser, err = models.GetUserByID(token.UID)
|
||
10 years ago
|
if err != nil {
|
||
8 years ago
|
// Once we found token, we're supposed to find its related user,
|
||
|
// thus any error is unexpected.
|
||
8 years ago
|
c.Handle(http.StatusInternalServerError, "GetUserByID", err)
|
||
10 years ago
|
return
|
||
|
}
|
||
8 years ago
|
} else if authUser.IsEnabledTwoFactor() {
|
||
|
askCredentials(c, http.StatusUnauthorized, `User with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password
|
||
|
Please create and use personal access token on user settings page`)
|
||
|
return
|
||
11 years ago
|
}
|
||
|
|
||
8 years ago
|
log.Trace("HTTPGit - Authenticated user: %s", authUser.Name)
|
||
|
|
||
8 years ago
|
mode := models.ACCESS_MODE_WRITE
|
||
|
if isPull {
|
||
|
mode = models.ACCESS_MODE_READ
|
||
11 years ago
|
}
|
||
8 years ago
|
has, err := models.HasAccess(authUser.ID, repo, mode)
|
||
8 years ago
|
if err != nil {
|
||
8 years ago
|
c.Handle(http.StatusInternalServerError, "HasAccess", err)
|
||
8 years ago
|
return
|
||
|
} else if !has {
|
||
8 years ago
|
askCredentials(c, http.StatusForbidden, "User permission denied")
|
||
9 years ago
|
return
|
||
|
}
|
||
11 years ago
|
|
||
8 years ago
|
if !isPull && repo.IsMirror {
|
||
8 years ago
|
c.HandleText(http.StatusForbidden, "Mirror repository is read-only")
|
||
8 years ago
|
return
|
||
11 years ago
|
}
|
||
11 years ago
|
|
||
8 years ago
|
c.Map(&HTTPContext{
|
||
|
Context: c,
|
||
8 years ago
|
OwnerName: ownerName,
|
||
|
OwnerSalt: owner.Salt,
|
||
8 years ago
|
RepoID: repo.ID,
|
||
8 years ago
|
RepoName: repoName,
|
||
|
AuthUser: authUser,
|
||
|
})
|
||
|
}
|
||
11 years ago
|
}
|
||
|
|
||
9 years ago
|
type serviceHandler struct {
|
||
11 years ago
|
w http.ResponseWriter
|
||
|
r *http.Request
|
||
9 years ago
|
dir string
|
||
|
file string
|
||
8 years ago
|
|
||
|
authUser *models.User
|
||
|
ownerName string
|
||
|
ownerSalt string
|
||
8 years ago
|
repoID int64
|
||
8 years ago
|
repoName string
|
||
9 years ago
|
}
|
||
|
|
||
|
func (h *serviceHandler) setHeaderNoCache() {
|
||
|
h.w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
|
||
|
h.w.Header().Set("Pragma", "no-cache")
|
||
|
h.w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
|
||
|
}
|
||
|
|
||
|
func (h *serviceHandler) setHeaderCacheForever() {
|
||
|
now := time.Now().Unix()
|
||
|
expires := now + 31536000
|
||
|
h.w.Header().Set("Date", fmt.Sprintf("%d", now))
|
||
|
h.w.Header().Set("Expires", fmt.Sprintf("%d", expires))
|
||
|
h.w.Header().Set("Cache-Control", "public, max-age=31536000")
|
||
|
}
|
||
|
|
||
|
func (h *serviceHandler) sendFile(contentType string) {
|
||
|
reqFile := path.Join(h.dir, h.file)
|
||
|
fi, err := os.Stat(reqFile)
|
||
|
if os.IsNotExist(err) {
|
||
|
h.w.WriteHeader(http.StatusNotFound)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
h.w.Header().Set("Content-Type", contentType)
|
||
|
h.w.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size()))
|
||
|
h.w.Header().Set("Last-Modified", fi.ModTime().Format(http.TimeFormat))
|
||
|
http.ServeFile(h.w, h.r, reqFile)
|
||
11 years ago
|
}
|
||
|
|
||
8 years ago
|
type ComposeHookEnvsOptions struct {
|
||
|
AuthUser *models.User
|
||
|
OwnerName string
|
||
|
OwnerSalt string
|
||
|
RepoID int64
|
||
|
RepoName string
|
||
|
RepoPath string
|
||
|
}
|
||
|
|
||
|
func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
|
||
8 years ago
|
envs := []string{
|
||
|
"SSH_ORIGINAL_COMMAND=1",
|
||
8 years ago
|
ENV_AUTH_USER_ID + "=" + com.ToStr(opts.AuthUser.ID),
|
||
|
ENV_AUTH_USER_NAME + "=" + opts.AuthUser.Name,
|
||
8 years ago
|
ENV_AUTH_USER_EMAIL + "=" + opts.AuthUser.Email,
|
||
8 years ago
|
ENV_REPO_OWNER_NAME + "=" + opts.OwnerName,
|
||
8 years ago
|
ENV_REPO_OWNER_SALT_MD5 + "=" + tool.MD5(opts.OwnerSalt),
|
||
8 years ago
|
ENV_REPO_ID + "=" + com.ToStr(opts.RepoID),
|
||
|
ENV_REPO_NAME + "=" + opts.RepoName,
|
||
|
ENV_REPO_CUSTOM_HOOKS_PATH + "=" + path.Join(opts.RepoPath, "custom_hooks"),
|
||
9 years ago
|
}
|
||
8 years ago
|
return envs
|
||
11 years ago
|
}
|
||
|
|
||
9 years ago
|
func serviceRPC(h serviceHandler, service string) {
|
||
|
defer h.r.Body.Close()
|
||
11 years ago
|
|
||
8 years ago
|
if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) {
|
||
9 years ago
|
h.w.WriteHeader(http.StatusUnauthorized)
|
||
11 years ago
|
return
|
||
|
}
|
||
9 years ago
|
h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service))
|
||
11 years ago
|
|
||
10 years ago
|
var (
|
||
8 years ago
|
reqBody = h.r.Body
|
||
|
err error
|
||
10 years ago
|
)
|
||
|
|
||
8 years ago
|
// Handle GZIP
|
||
9 years ago
|
if h.r.Header.Get("Content-Encoding") == "gzip" {
|
||
10 years ago
|
reqBody, err = gzip.NewReader(reqBody)
|
||
|
if err != nil {
|
||
8 years ago
|
log.Error(2, "HTTP.Get: fail to create gzip reader: %v", err)
|
||
9 years ago
|
h.w.WriteHeader(http.StatusInternalServerError)
|
||
10 years ago
|
return
|
||
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
var stderr bytes.Buffer
|
||
9 years ago
|
cmd := exec.Command("git", service, "--stateless-rpc", h.dir)
|
||
8 years ago
|
if service == "receive-pack" {
|
||
8 years ago
|
cmd.Env = append(os.Environ(), ComposeHookEnvs(ComposeHookEnvsOptions{
|
||
|
AuthUser: h.authUser,
|
||
|
OwnerName: h.ownerName,
|
||
|
OwnerSalt: h.ownerSalt,
|
||
|
RepoID: h.repoID,
|
||
|
RepoName: h.repoName,
|
||
|
RepoPath: h.dir,
|
||
|
})...)
|
||
8 years ago
|
}
|
||
9 years ago
|
cmd.Dir = h.dir
|
||
|
cmd.Stdout = h.w
|
||
8 years ago
|
cmd.Stderr = &stderr
|
||
8 years ago
|
cmd.Stdin = reqBody
|
||
|
if err = cmd.Run(); err != nil {
|
||
|
log.Error(2, "HTTP.serviceRPC: fail to serve RPC '%s': %v - %s", service, err, stderr)
|
||
9 years ago
|
h.w.WriteHeader(http.StatusInternalServerError)
|
||
11 years ago
|
return
|
||
|
}
|
||
|
}
|
||
|
|
||
9 years ago
|
func serviceUploadPack(h serviceHandler) {
|
||
|
serviceRPC(h, "upload-pack")
|
||
11 years ago
|
}
|
||
|
|
||
9 years ago
|
func serviceReceivePack(h serviceHandler) {
|
||
|
serviceRPC(h, "receive-pack")
|
||
11 years ago
|
}
|
||
|
|
||
|
func getServiceType(r *http.Request) string {
|
||
|
serviceType := r.FormValue("service")
|
||
9 years ago
|
if !strings.HasPrefix(serviceType, "git-") {
|
||
11 years ago
|
return ""
|
||
|
}
|
||
8 years ago
|
return strings.TrimPrefix(serviceType, "git-")
|
||
|
}
|
||
|
|
||
|
// FIXME: use process module
|
||
|
func gitCommand(dir string, args ...string) []byte {
|
||
|
cmd := exec.Command("git", args...)
|
||
|
cmd.Dir = dir
|
||
|
out, err := cmd.Output()
|
||
|
if err != nil {
|
||
|
log.Error(2, fmt.Sprintf("Git: %v - %s", err, out))
|
||
|
}
|
||
|
return out
|
||
11 years ago
|
}
|
||
|
|
||
9 years ago
|
func updateServerInfo(dir string) []byte {
|
||
|
return gitCommand(dir, "update-server-info")
|
||
11 years ago
|
}
|
||
|
|
||
9 years ago
|
func packetWrite(str string) []byte {
|
||
|
s := strconv.FormatInt(int64(len(str)+4), 16)
|
||
|
if len(s)%4 != 0 {
|
||
|
s = strings.Repeat("0", 4-len(s)%4) + s
|
||
11 years ago
|
}
|
||
9 years ago
|
return []byte(s + str)
|
||
11 years ago
|
}
|
||
|
|
||
9 years ago
|
func getInfoRefs(h serviceHandler) {
|
||
|
h.setHeaderNoCache()
|
||
8 years ago
|
service := getServiceType(h.r)
|
||
|
if service != "upload-pack" && service != "receive-pack" {
|
||
9 years ago
|
updateServerInfo(h.dir)
|
||
|
h.sendFile("text/plain; charset=utf-8")
|
||
8 years ago
|
return
|
||
11 years ago
|
}
|
||
8 years ago
|
|
||
|
refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".")
|
||
|
h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
|
||
|
h.w.WriteHeader(http.StatusOK)
|
||
|
h.w.Write(packetWrite("# service=git-" + service + "\n"))
|
||
|
h.w.Write([]byte("0000"))
|
||
|
h.w.Write(refs)
|
||
11 years ago
|
}
|
||
|
|
||
9 years ago
|
func getTextFile(h serviceHandler) {
|
||
|
h.setHeaderNoCache()
|
||
|
h.sendFile("text/plain")
|
||
11 years ago
|
}
|
||
|
|
||
9 years ago
|
func getInfoPacks(h serviceHandler) {
|
||
|
h.setHeaderCacheForever()
|
||
|
h.sendFile("text/plain; charset=utf-8")
|
||
11 years ago
|
}
|
||
|
|
||
9 years ago
|
func getLooseObject(h serviceHandler) {
|
||
|
h.setHeaderCacheForever()
|
||
|
h.sendFile("application/x-git-loose-object")
|
||
11 years ago
|
}
|
||
|
|
||
9 years ago
|
func getPackFile(h serviceHandler) {
|
||
|
h.setHeaderCacheForever()
|
||
|
h.sendFile("application/x-git-packed-objects")
|
||
|
}
|
||
11 years ago
|
|
||
9 years ago
|
func getIdxFile(h serviceHandler) {
|
||
|
h.setHeaderCacheForever()
|
||
|
h.sendFile("application/x-git-packed-objects-toc")
|
||
11 years ago
|
}
|
||
|
|
||
8 years ago
|
var routes = []struct {
|
||
|
reg *regexp.Regexp
|
||
|
method string
|
||
|
handler func(serviceHandler)
|
||
|
}{
|
||
|
{regexp.MustCompile("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
|
||
|
{regexp.MustCompile("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
|
||
|
{regexp.MustCompile("(.*?)/info/refs$"), "GET", getInfoRefs},
|
||
|
{regexp.MustCompile("(.*?)/HEAD$"), "GET", getTextFile},
|
||
|
{regexp.MustCompile("(.*?)/objects/info/alternates$"), "GET", getTextFile},
|
||
|
{regexp.MustCompile("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
|
||
|
{regexp.MustCompile("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
|
||
|
{regexp.MustCompile("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
|
||
|
{regexp.MustCompile("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
|
||
|
{regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
|
||
|
{regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
|
||
|
}
|
||
|
|
||
|
func getGitRepoPath(dir string) (string, error) {
|
||
|
if !strings.HasSuffix(dir, ".git") {
|
||
|
dir += ".git"
|
||
9 years ago
|
}
|
||
11 years ago
|
|
||
8 years ago
|
filename := path.Join(setting.RepoRootPath, dir)
|
||
|
if _, err := os.Stat(filename); os.IsNotExist(err) {
|
||
9 years ago
|
return "", err
|
||
11 years ago
|
}
|
||
|
|
||
8 years ago
|
return filename, nil
|
||
11 years ago
|
}
|
||
|
|
||
8 years ago
|
func HTTP(c *HTTPContext) {
|
||
8 years ago
|
for _, route := range routes {
|
||
8 years ago
|
reqPath := strings.ToLower(c.Req.URL.Path)
|
||
8 years ago
|
m := route.reg.FindStringSubmatch(reqPath)
|
||
|
if m == nil {
|
||
|
continue
|
||
|
}
|
||
|
|
||
|
// We perform check here because routes matched in cmd/web.go is wider than needed,
|
||
|
// but we only want to output this message only if user is really trying to access
|
||
|
// Git HTTP endpoints.
|
||
|
if setting.Repository.DisableHTTPGit {
|
||
8 years ago
|
c.HandleText(http.StatusForbidden, "Interacting with repositories by HTTP protocol is not disabled")
|
||
8 years ago
|
return
|
||
|
}
|
||
|
|
||
8 years ago
|
if route.method != c.Req.Method {
|
||
|
c.NotFound()
|
||
8 years ago
|
return
|
||
9 years ago
|
}
|
||
|
|
||
8 years ago
|
file := strings.TrimPrefix(reqPath, m[1]+"/")
|
||
|
dir, err := getGitRepoPath(m[1])
|
||
|
if err != nil {
|
||
|
log.Warn("HTTP.getGitRepoPath: %v", err)
|
||
8 years ago
|
c.NotFound()
|
||
8 years ago
|
return
|
||
|
}
|
||
|
|
||
|
route.handler(serviceHandler{
|
||
8 years ago
|
w: c.Resp,
|
||
|
r: c.Req.Request,
|
||
8 years ago
|
dir: dir,
|
||
|
file: file,
|
||
|
|
||
8 years ago
|
authUser: c.AuthUser,
|
||
|
ownerName: c.OwnerName,
|
||
|
ownerSalt: c.OwnerSalt,
|
||
|
repoID: c.RepoID,
|
||
|
repoName: c.RepoName,
|
||
8 years ago
|
})
|
||
9 years ago
|
return
|
||
|
}
|
||
8 years ago
|
|
||
8 years ago
|
c.NotFound()
|
||
11 years ago
|
}
|