Files
Gogs/cmd/serv.go

317 lines
8.8 KiB
Go
Raw Normal View History

2014-04-10 14:20:58 -04:00
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
2014-05-01 21:21:46 -04:00
package cmd
2014-04-10 14:20:58 -04:00
import (
2015-10-26 09:16:24 -04:00
"crypto/tls"
2014-04-10 14:20:58 -04:00
"fmt"
"os"
"os/exec"
2014-06-29 22:31:46 +08:00
"path/filepath"
2014-04-10 14:20:58 -04:00
"strings"
2014-08-09 15:40:10 -07:00
"time"
2014-04-10 14:20:58 -04:00
2014-07-26 00:24:27 -04:00
"github.com/Unknwon/com"
"github.com/gogits/git-module"
gouuid "github.com/satori/go.uuid"
2016-08-30 13:57:58 +02:00
"github.com/urfave/cli"
2017-02-09 19:29:59 -05:00
log "gopkg.in/clog.v1"
2014-07-26 00:24:27 -04:00
2014-04-10 14:20:58 -04:00
"github.com/gogits/gogs/models"
2015-12-14 17:06:54 -05:00
"github.com/gogits/gogs/modules/base"
2015-07-25 21:32:04 +08:00
"github.com/gogits/gogs/modules/httplib"
2014-05-25 20:11:25 -04:00
"github.com/gogits/gogs/modules/setting"
2014-04-10 14:20:58 -04:00
)
2015-02-16 16:38:01 +02:00
const (
_ACCESS_DENIED_MESSAGE = "Repository does not exist or you do not have access"
_ENV_UPDATE_TASK_UUID = "UPDATE_TASK_UUID"
_ENV_REPO_CUSTOM_HOOKS_PATH = "REPO_CUSTOM_HOOKS_PATH"
2015-02-16 16:38:01 +02:00
)
var Serv = cli.Command{
2014-05-05 00:55:17 -04:00
Name: "serv",
Usage: "This command should only be called by SSH shell",
Description: `Serv provide access auth for repositories`,
Action: runServ,
Flags: []cli.Flag{
2015-11-15 17:07:44 -05:00
stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
},
2014-04-10 14:20:58 -04:00
}
func setup(c *cli.Context, logPath string) {
if c.IsSet("config") {
setting.CustomConf = c.String("config")
} else if c.GlobalIsSet("config") {
setting.CustomConf = c.GlobalString("config")
}
2015-09-16 23:08:46 -04:00
setting.NewContext()
setting.NewService()
2017-02-09 19:29:59 -05:00
log.New(log.FILE, log.FileConfig{
Filename: filepath.Join(setting.LogRootPath, logPath),
FileRotationConfig: log.FileRotationConfig{
Rotate: true,
Daily: true,
MaxDays: 3,
},
})
log.Delete(log.CONSOLE) // Remove primary logger
2015-02-07 10:46:57 -05:00
2015-09-16 23:08:46 -04:00
models.LoadConfigs()
2014-05-21 21:37:13 -04:00
if setting.UseSQLite3 {
2014-06-20 01:14:54 -04:00
workDir, _ := setting.WorkDir()
2014-05-25 20:11:25 -04:00
os.Chdir(workDir)
2014-05-21 21:37:13 -04:00
}
models.SetEngine()
}
func parseSSHCmd(cmd string) (string, string) {
2014-04-10 14:20:58 -04:00
ss := strings.SplitN(cmd, " ", 2)
if len(ss) != 2 {
return "", ""
}
2015-02-16 16:38:01 +02:00
return ss[0], strings.Replace(ss[1], "'/", "'", 1)
2014-04-10 14:20:58 -04:00
}
func checkDeployKey(key *models.PublicKey, repo *models.Repository) {
// Check if this deploy key belongs to current repository.
if !models.HasDeployKey(key.ID, repo.ID) {
fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
}
// Update deploy key activity.
deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
if err != nil {
fail("Internal error", "GetDeployKey: %v", err)
}
deployKey.Updated = time.Now()
if err = models.UpdateDeployKey(deployKey); err != nil {
fail("Internal error", "UpdateDeployKey: %v", err)
}
}
2014-05-21 21:37:13 -04:00
var (
allowedCommands = map[string]models.AccessMode{
2015-02-16 16:38:01 +02:00
"git-upload-pack": models.ACCESS_MODE_READ,
"git-upload-archive": models.ACCESS_MODE_READ,
"git-receive-pack": models.ACCESS_MODE_WRITE,
2014-05-21 21:37:13 -04:00
}
)
2015-08-06 22:48:11 +08:00
func fail(userMessage, logMessage string, args ...interface{}) {
fmt.Fprintln(os.Stderr, "Gogs:", userMessage)
2015-11-08 14:31:49 -05:00
if len(logMessage) > 0 {
if !setting.ProdMode {
2015-11-30 10:00:52 -05:00
fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
}
2017-02-09 19:29:59 -05:00
log.Fatal(3, logMessage, args...)
2015-11-08 14:31:49 -05:00
}
2017-02-09 19:29:59 -05:00
log.Shutdown()
2015-11-08 14:31:49 -05:00
os.Exit(1)
2015-08-06 22:48:11 +08:00
}
2015-12-14 17:06:54 -05:00
func handleUpdateTask(uuid string, user, repoUser *models.User, reponame string, isWiki bool) {
2015-11-04 21:57:10 -05:00
task, err := models.GetUpdateTaskByUUID(uuid)
if err != nil {
if models.IsErrUpdateTaskNotExist(err) {
2017-02-09 19:29:59 -05:00
log.Trace("No update task is presented: %s", uuid)
2015-11-04 21:57:10 -05:00
return
}
2017-02-09 19:29:59 -05:00
log.Fatal(2, "GetUpdateTaskByUUID: %v", err)
2015-11-30 20:45:55 -05:00
} else if err = models.DeleteUpdateTaskByUUID(uuid); err != nil {
2017-02-09 19:29:59 -05:00
log.Fatal(2, "DeleteUpdateTaskByUUID: %v", err)
2015-11-04 21:57:10 -05:00
}
2015-11-30 20:45:55 -05:00
if isWiki {
return
2015-11-04 21:57:10 -05:00
}
if err = models.PushUpdate(models.PushUpdateOptions{
2016-08-16 23:06:38 -07:00
RefFullName: task.RefName,
OldCommitID: task.OldCommitID,
NewCommitID: task.NewCommitID,
2016-07-24 01:08:22 +08:00
PusherID: user.ID,
PusherName: user.Name,
RepoUserName: repoUser.Name,
RepoName: reponame,
}); err != nil {
2017-02-09 19:29:59 -05:00
log.Error(2, "Update: %v", err)
2015-11-04 21:57:10 -05:00
}
// Ask for running deliver hook and test pull request tasks.
2015-12-17 02:28:47 -05:00
reqURL := setting.LocalURL + repoUser.Name + "/" + reponame + "/tasks/trigger?branch=" +
strings.TrimPrefix(task.RefName, git.BRANCH_PREFIX) + "&secret=" + base.EncodeMD5(repoUser.Salt) + "&pusher=" + com.ToStr(user.ID)
2017-02-09 19:29:59 -05:00
log.Trace("Trigger task: %s", reqURL)
2015-11-04 21:57:10 -05:00
resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
InsecureSkipVerify: true,
}).Response()
if err == nil {
resp.Body.Close()
if resp.StatusCode/100 != 2 {
2017-02-09 19:29:59 -05:00
log.Error(2, "Fail to trigger task: not 2xx response code")
2015-11-04 21:57:10 -05:00
}
} else {
2017-02-09 19:29:59 -05:00
log.Error(2, "Fail to trigger task: %v", err)
2015-11-04 21:57:10 -05:00
}
}
func runServ(c *cli.Context) error {
setup(c, "serv.log")
2014-04-10 14:20:58 -04:00
if setting.SSH.Disabled {
2016-02-21 21:55:59 -05:00
println("Gogs: SSH has been disabled")
return nil
2016-02-21 21:55:59 -05:00
}
2015-02-13 00:58:46 -05:00
if len(c.Args()) < 1 {
2015-06-18 05:01:05 -06:00
fail("Not enough arguments", "Not enough arguments")
}
2015-02-16 16:38:01 +02:00
sshCmd := os.Getenv("SSH_ORIGINAL_COMMAND")
if len(sshCmd) == 0 {
2015-08-05 11:14:17 +08:00
println("Hi there, You've successfully authenticated, but Gogs does not provide shell access.")
println("If this is unexpected, please log in with password and setup Gogs under another user.")
return nil
2014-04-10 14:20:58 -04:00
}
verb, args := parseSSHCmd(sshCmd)
repoFullName := strings.ToLower(strings.Trim(args, "'"))
repoFields := strings.SplitN(repoFullName, "/", 2)
if len(repoFields) != 2 {
2015-06-18 05:01:05 -06:00
fail("Invalid repository path", "Invalid repository path: %v", args)
2014-04-10 14:20:58 -04:00
}
username := strings.ToLower(repoFields[0])
reponame := strings.ToLower(strings.TrimSuffix(repoFields[1], ".git"))
2015-11-30 20:45:55 -05:00
isWiki := false
if strings.HasSuffix(reponame, ".wiki") {
isWiki = true
reponame = reponame[:len(reponame)-5]
}
2014-04-10 14:20:58 -04:00
repoOwner, err := models.GetUserByName(username)
2014-04-10 14:20:58 -04:00
if err != nil {
2015-08-05 11:14:17 +08:00
if models.IsErrUserNotExist(err) {
2015-11-30 20:45:55 -05:00
fail("Repository owner does not exist", "Unregistered owner: %s", username)
2014-05-21 21:37:13 -04:00
}
fail("Internal error", "Fail to get repository owner '%s': %v", username, err)
2014-04-10 14:20:58 -04:00
}
repo, err := models.GetRepositoryByName(repoOwner.ID, reponame)
if err != nil {
if models.IsErrRepoNotExist(err) {
fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", repoOwner.Name, reponame)
}
fail("Internal error", "Fail to get repository: %v", err)
}
repo.Owner = repoOwner
requestMode, ok := allowedCommands[verb]
if !ok {
fail("Unknown git command", "Unknown git command '%s'", verb)
2015-02-16 16:38:01 +02:00
}
2014-04-10 14:20:58 -04:00
2015-11-08 14:31:49 -05:00
// Prohibit push to mirror repositories.
if requestMode > models.ACCESS_MODE_READ && repo.IsMirror {
2015-11-08 14:31:49 -05:00
fail("mirror repository is read-only", "")
}
// Allow anonymous (user is nil) clone for public repositories.
var user *models.User
key, err := models.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
if err != nil {
fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
}
if requestMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
2015-08-06 22:48:11 +08:00
// Check deploy key or user key.
if key.IsDeployKey() {
if key.Mode < requestMode {
2015-08-06 22:48:11 +08:00
fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
}
checkDeployKey(key, repo)
2015-08-06 22:48:11 +08:00
} else {
2015-11-04 21:57:10 -05:00
user, err = models.GetUserByKeyID(key.ID)
2015-08-06 22:48:11 +08:00
if err != nil {
fail("Internal error", "Fail to get user by key ID '%d': %v", key.ID, err)
2015-08-06 22:48:11 +08:00
}
mode, err := models.AccessLevel(user, repo)
if err != nil {
fail("Internal error", "Fail to check access: %v", err)
}
if mode < requestMode {
2015-08-06 22:48:11 +08:00
clientMessage := _ACCESS_DENIED_MESSAGE
if mode >= models.ACCESS_MODE_READ {
clientMessage = "You do not have sufficient authorization for this action"
}
fail(clientMessage,
"User '%s' does not have level '%v' access to repository '%s'",
user.Name, requestMode, repoFullName)
2015-08-05 11:14:17 +08:00
}
2014-04-10 14:20:58 -04:00
}
} else {
// Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
// A deploy key doesn't represent a signed in user, so in a site with Service.RequireSignInView activated
// we should give read access only in repositories where this deploy key is in use. In other case, a server
// or system using an active deploy key can get read access to all the repositories in a Gogs service.
if key.IsDeployKey() && setting.Service.RequireSignInView {
checkDeployKey(key, repo)
}
2014-04-10 14:20:58 -04:00
}
uuid := gouuid.NewV4().String()
os.Setenv(_ENV_UPDATE_TASK_UUID, uuid)
os.Setenv(_ENV_REPO_CUSTOM_HOOKS_PATH, filepath.Join(repo.RepoPath(), "custom_hooks"))
2014-04-10 14:20:58 -04:00
// Special handle for Windows.
if setting.IsWindows {
verb = strings.Replace(verb, "-", " ", 1)
}
var gitCmd *exec.Cmd
2014-10-01 07:40:48 -04:00
verbs := strings.Split(verb, " ")
if len(verbs) == 2 {
gitCmd = exec.Command(verbs[0], verbs[1], repoFullName)
2014-10-01 07:40:48 -04:00
} else {
gitCmd = exec.Command(verb, repoFullName)
2014-10-01 07:40:48 -04:00
}
gitCmd.Dir = setting.RepoRootPath
gitCmd.Stdout = os.Stdout
gitCmd.Stdin = os.Stdin
gitCmd.Stderr = os.Stderr
if err = gitCmd.Run(); err != nil {
fail("Internal error", "Fail to execute git command: %v", err)
2014-04-10 14:20:58 -04:00
}
2014-06-28 23:56:41 +08:00
if requestMode == models.ACCESS_MODE_WRITE {
handleUpdateTask(uuid, user, repoOwner, reponame, isWiki)
2015-07-25 21:32:04 +08:00
}
2015-08-06 22:48:11 +08:00
// Update user key activity.
if key.ID > 0 {
key, err := models.GetPublicKeyByID(key.ID)
2015-08-05 11:14:17 +08:00
if err != nil {
fail("Internal error", "GetPublicKeyByID: %v", err)
2015-08-05 11:14:17 +08:00
}
key.Updated = time.Now()
if err = models.UpdatePublicKey(key); err != nil {
fail("Internal error", "UpdatePublicKey: %v", err)
}
2014-08-09 15:40:10 -07:00
}
return nil
2014-04-10 14:20:58 -04:00
}