chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
1134 files changed
+433629
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,185 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/base32"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
shm "github.com/kovidgoyal/go-shm/v2"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func fatal(err error) int {
|
||||
cli.ShowError(err)
|
||||
return 1
|
||||
}
|
||||
|
||||
func trigger_ask(name string) int {
|
||||
term, err := tty.OpenControllingTerm()
|
||||
if err != nil {
|
||||
return fatal(err)
|
||||
}
|
||||
defer term.Close()
|
||||
_, err = term.WriteString("\x1bP@kitty-ask|" + name + "\x1b\\")
|
||||
if err != nil {
|
||||
return fatal(err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func isPasswordPrompt(msg string) bool {
|
||||
q := strings.ToLower(msg)
|
||||
if strings.Contains(q, "passphrase") {
|
||||
return false
|
||||
}
|
||||
return strings.Contains(q, "password")
|
||||
}
|
||||
|
||||
func isOTPPrompt(msg string) bool {
|
||||
q := strings.ToLower(msg)
|
||||
if strings.Contains(q, "passphrase") {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(q, "verification code") || strings.Contains(q, "one-time password") || strings.Contains(q, "one time password") || strings.Contains(q, "authenticator code") || strings.Contains(q, "authentication code") || strings.Contains(q, "two-factor") || strings.Contains(q, "2fa") || strings.Contains(q, "otp") || strings.Contains(q, "passcode") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func generateTOTP(secret string, digits, period int64, t time.Time) (string, error) {
|
||||
s := strings.ToUpper(strings.TrimSpace(secret))
|
||||
s = strings.ReplaceAll(s, " ", "")
|
||||
key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(s)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid TOTP secret: %w", err)
|
||||
}
|
||||
counter := uint64(t.Unix() / period)
|
||||
var buf [8]byte
|
||||
binary.BigEndian.PutUint64(buf[:], counter)
|
||||
mac := hmac.New(sha1.New, key)
|
||||
_, _ = mac.Write(buf[:])
|
||||
sum := mac.Sum(nil)
|
||||
off := sum[len(sum)-1] & 0x0f
|
||||
code := (uint32(sum[off])&0x7f)<<24 | (uint32(sum[off+1])&0xff)<<16 | (uint32(sum[off+2])&0xff)<<8 | (uint32(sum[off+3]) & 0xff)
|
||||
mod := uint32(1)
|
||||
for range digits {
|
||||
mod *= 10
|
||||
}
|
||||
val := code % mod
|
||||
fmtstr := fmt.Sprintf("%%0%dd", digits)
|
||||
return fmt.Sprintf(fmtstr, val), nil
|
||||
}
|
||||
|
||||
func RunSSHAskpass() int {
|
||||
msg := os.Args[len(os.Args)-1]
|
||||
prompt := os.Getenv("SSH_ASKPASS_PROMPT")
|
||||
is_confirm := prompt == "confirm"
|
||||
q_type := "get_line"
|
||||
if is_confirm {
|
||||
q_type = "confirm"
|
||||
}
|
||||
is_fingerprint_check := strings.Contains(msg, "(yes/no/[fingerprint])")
|
||||
|
||||
// Auto-fill from ssh.conf if configured
|
||||
if !is_confirm && !is_fingerprint_check {
|
||||
host := os.Getenv("KITTY_SSH_ASKPASS_HOST")
|
||||
user := os.Getenv("KITTY_SSH_ASKPASS_USER")
|
||||
if host != "" {
|
||||
var overrides []string
|
||||
_ = json.Unmarshal([]byte(os.Getenv("KITTY_SSH_ASKPASS_OVERRIDES")), &overrides)
|
||||
if cfg, _, err := load_config(host, user, overrides); err == nil && cfg != nil {
|
||||
if err = resolve_secrets(cfg, false); err != nil {
|
||||
return fatal(err)
|
||||
}
|
||||
// Password autofill
|
||||
if isPasswordPrompt(msg) && cfg.Password != "" {
|
||||
fmt.Println(cfg.Password)
|
||||
return 0
|
||||
}
|
||||
// OTP autofill
|
||||
if isOTPPrompt(msg) && cfg.Totp_secret != "" {
|
||||
code, err := generateTOTP(cfg.Totp_secret, int64(cfg.Totp_digits), int64(cfg.Totp_period), time.Now())
|
||||
if err == nil {
|
||||
fmt.Println(code)
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
q := map[string]any{
|
||||
"message": msg,
|
||||
"type": q_type,
|
||||
"is_password": !is_fingerprint_check,
|
||||
}
|
||||
data, err := json.Marshal(q)
|
||||
if err != nil {
|
||||
return fatal(err)
|
||||
}
|
||||
data_shm, err := shm.CreateTemp("askpass-*", uint64(len(data)+32))
|
||||
if err != nil {
|
||||
return fatal(fmt.Errorf("Failed to create SHM file with error: %w", err))
|
||||
}
|
||||
defer data_shm.Close()
|
||||
defer func() { _ = data_shm.Unlink() }()
|
||||
|
||||
data_shm.Slice()[0] = 0
|
||||
if err = shm.WriteWithSize(data_shm, data, 1); err != nil {
|
||||
return fatal(fmt.Errorf("Failed to write to SHM file with error: %w", err))
|
||||
}
|
||||
if err = data_shm.Flush(); err != nil {
|
||||
return fatal(fmt.Errorf("Failed to flush SHM file with error: %w", err))
|
||||
}
|
||||
trigger_ask(data_shm.Name())
|
||||
for {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if data_shm.Slice()[0] == 1 {
|
||||
break
|
||||
}
|
||||
}
|
||||
data, err = shm.ReadWithSize(data_shm, 1)
|
||||
if err != nil {
|
||||
return fatal(fmt.Errorf("Failed to read from SHM file with error: %w", err))
|
||||
}
|
||||
response := ""
|
||||
if is_confirm {
|
||||
var ok bool
|
||||
err = json.Unmarshal(data, &ok)
|
||||
if err != nil {
|
||||
return fatal(fmt.Errorf("Failed to parse response data: %#v with error: %w", string(data), err))
|
||||
}
|
||||
response = "no"
|
||||
if ok {
|
||||
response = "yes"
|
||||
}
|
||||
} else {
|
||||
err = json.Unmarshal(data, &response)
|
||||
if err != nil {
|
||||
return fatal(fmt.Errorf("Failed to parse response data: %#v with error: %w", string(data), err))
|
||||
}
|
||||
if is_fingerprint_check {
|
||||
response = strings.ToLower(response)
|
||||
switch response {
|
||||
case "y":
|
||||
response = "yes"
|
||||
case "n":
|
||||
response = "no"
|
||||
}
|
||||
}
|
||||
}
|
||||
if response != "" {
|
||||
fmt.Println(response)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/paths"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
|
||||
"github.com/bmatcuk/doublestar/v4"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func resolve_secret(key, val string) (string, error) {
|
||||
v := strings.TrimSpace(val)
|
||||
if v == "" {
|
||||
return "", nil
|
||||
}
|
||||
if b, s, ok := strings.Cut(v, ":"); ok {
|
||||
b = strings.ToLower(strings.TrimSpace(b))
|
||||
s = strings.TrimSpace(s)
|
||||
switch b {
|
||||
case "text":
|
||||
return s, nil
|
||||
default:
|
||||
return "", fmt.Errorf("Unsupported secret backend %s for %s. Supported backends: text", b, key)
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("No secret backend specified for: %s", key)
|
||||
}
|
||||
|
||||
func resolve_secrets(c *Config, only_syntax bool) error {
|
||||
_ = only_syntax // this will be useful when using backends that require user interaction
|
||||
if r, err := resolve_secret("password", c.Password); err != nil {
|
||||
return err
|
||||
} else {
|
||||
c.Password = r
|
||||
}
|
||||
if r, err := resolve_secret("totp_secret", c.Totp_secret); err != nil {
|
||||
return err
|
||||
} else {
|
||||
c.Totp_secret = r
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type EnvInstruction struct {
|
||||
key, val string
|
||||
delete_on_remote, copy_from_local, literal_quote bool
|
||||
}
|
||||
|
||||
func quote_for_sh(val string, literal_quote bool) string {
|
||||
if literal_quote {
|
||||
return utils.QuoteStringForSH(val)
|
||||
}
|
||||
// See https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
|
||||
b := strings.Builder{}
|
||||
b.Grow(len(val) + 16)
|
||||
b.WriteRune('"')
|
||||
runes := []rune(val)
|
||||
for i, ch := range runes {
|
||||
if ch == '\\' || ch == '`' || ch == '"' || (ch == '$' && i+1 < len(runes) && runes[i+1] == '(') {
|
||||
// special chars are escaped
|
||||
// $( is escaped to prevent execution
|
||||
b.WriteRune('\\')
|
||||
}
|
||||
b.WriteRune(ch)
|
||||
}
|
||||
b.WriteRune('"')
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (self *EnvInstruction) Serialize(for_python bool, get_local_env func(string) (string, bool)) string {
|
||||
var unset func() string
|
||||
var export func(string) string
|
||||
if for_python {
|
||||
dumps := func(x ...any) string {
|
||||
ans, _ := json.Marshal(x)
|
||||
return utils.UnsafeBytesToString(ans)
|
||||
}
|
||||
export = func(val string) string {
|
||||
if val == "" {
|
||||
return fmt.Sprintf("export %s", dumps(self.key))
|
||||
}
|
||||
return fmt.Sprintf("export %s", dumps(self.key, val, self.literal_quote))
|
||||
}
|
||||
unset = func() string {
|
||||
return fmt.Sprintf("unset %s", dumps(self.key))
|
||||
}
|
||||
} else {
|
||||
kq := utils.QuoteStringForSH(self.key)
|
||||
unset = func() string {
|
||||
return fmt.Sprintf("unset %s", kq)
|
||||
}
|
||||
export = func(val string) string {
|
||||
return fmt.Sprintf("export %s=%s", kq, quote_for_sh(val, self.literal_quote))
|
||||
}
|
||||
}
|
||||
if self.delete_on_remote {
|
||||
return unset()
|
||||
}
|
||||
if self.copy_from_local {
|
||||
val, found := get_local_env(self.key)
|
||||
if !found {
|
||||
return ""
|
||||
}
|
||||
return export(val)
|
||||
}
|
||||
return export(self.val)
|
||||
}
|
||||
|
||||
func final_env_instructions(for_python bool, get_local_env func(string) (string, bool), env ...*EnvInstruction) string {
|
||||
seen := make(map[string]int, len(env))
|
||||
ans := make([]string, 0, len(env))
|
||||
for _, ei := range env {
|
||||
q := ei.Serialize(for_python, get_local_env)
|
||||
if q != "" {
|
||||
if pos, found := seen[ei.key]; found {
|
||||
ans[pos] = q
|
||||
} else {
|
||||
seen[ei.key] = len(ans)
|
||||
ans = append(ans, q)
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Join(ans, "\n")
|
||||
}
|
||||
|
||||
type CopyInstruction struct {
|
||||
local_path, arcname string
|
||||
exclude_patterns []string
|
||||
}
|
||||
|
||||
func ParseEnvInstruction(spec string) (ans []*EnvInstruction, err error) {
|
||||
const COPY_FROM_LOCAL string = "_kitty_copy_env_var_"
|
||||
ei := &EnvInstruction{}
|
||||
found := false
|
||||
ei.key, ei.val, found = strings.Cut(spec, "=")
|
||||
ei.key = strings.TrimSpace(ei.key)
|
||||
if found {
|
||||
ei.val = strings.TrimSpace(ei.val)
|
||||
if ei.val == COPY_FROM_LOCAL {
|
||||
ei.val = ""
|
||||
ei.copy_from_local = true
|
||||
}
|
||||
} else {
|
||||
ei.delete_on_remote = true
|
||||
}
|
||||
if ei.key == "" {
|
||||
err = fmt.Errorf("The env directive must not be empty")
|
||||
}
|
||||
ans = []*EnvInstruction{ei}
|
||||
return
|
||||
}
|
||||
|
||||
var paths_ctx *paths.Ctx
|
||||
|
||||
func resolve_file_spec(spec string, is_glob bool) ([]string, error) {
|
||||
if paths_ctx == nil {
|
||||
paths_ctx = &paths.Ctx{}
|
||||
}
|
||||
ans := os.ExpandEnv(paths_ctx.ExpandHome(spec))
|
||||
if !filepath.IsAbs(ans) {
|
||||
ans = paths_ctx.AbspathFromHome(ans)
|
||||
}
|
||||
if is_glob {
|
||||
files, err := doublestar.FilepathGlob(ans)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s is not a valid glob pattern with error: %w", spec, err)
|
||||
}
|
||||
if len(files) == 0 {
|
||||
return nil, fmt.Errorf("%s matches no files", spec)
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
err := unix.Access(ans, unix.R_OK)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, fmt.Errorf("%s does not exist", spec)
|
||||
}
|
||||
return nil, fmt.Errorf("Cannot read from: %s with error: %w", spec, err)
|
||||
}
|
||||
return []string{ans}, nil
|
||||
}
|
||||
|
||||
func get_arcname(loc, dest, home string) (arcname string) {
|
||||
if dest != "" {
|
||||
arcname = dest
|
||||
} else {
|
||||
arcname = filepath.Clean(loc)
|
||||
if ra, err := filepath.Rel(home, arcname); err == nil && filepath.IsLocal(ra) {
|
||||
arcname = ra
|
||||
}
|
||||
}
|
||||
prefix := "home/"
|
||||
if strings.HasPrefix(arcname, "/") {
|
||||
prefix = "root"
|
||||
}
|
||||
return prefix + arcname
|
||||
}
|
||||
|
||||
func ParseCopyInstruction(spec string) (ans []*CopyInstruction, err error) {
|
||||
args, err := shlex.Split("copy " + spec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts, args, err := parse_copy_args(args)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
locations := make([]string, 0, len(args))
|
||||
for _, arg := range args {
|
||||
locs, err := resolve_file_spec(arg, opts.Glob)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
locations = append(locations, locs...)
|
||||
}
|
||||
if len(locations) == 0 {
|
||||
return nil, fmt.Errorf("No files to copy specified")
|
||||
}
|
||||
if len(locations) > 1 && opts.Dest != "" {
|
||||
return nil, fmt.Errorf("Specifying a remote location with more than one file is not supported")
|
||||
}
|
||||
home := paths_ctx.HomePath()
|
||||
if opts.SymlinkStrategy == "resolve" {
|
||||
// The copied paths have their symlinks resolved, so HOME must be resolved
|
||||
// as well, otherwise paths under a HOME that is itself reached via a
|
||||
// symlink, such as /home -> /usr/home, are not recognized as being in HOME.
|
||||
// If HOME cannot be resolved fall back to using it as is.
|
||||
if rh, err := filepath.EvalSymlinks(home); err == nil {
|
||||
home = rh
|
||||
}
|
||||
}
|
||||
ans = make([]*CopyInstruction, 0, len(locations))
|
||||
for _, loc := range locations {
|
||||
ci := CopyInstruction{local_path: loc, exclude_patterns: opts.Exclude}
|
||||
if opts.SymlinkStrategy != "preserve" {
|
||||
ci.local_path, err = filepath.EvalSymlinks(loc)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to resolve symlinks in %#v with error: %w", loc, err)
|
||||
}
|
||||
}
|
||||
if opts.SymlinkStrategy == "resolve" {
|
||||
ci.arcname = get_arcname(ci.local_path, opts.Dest, home)
|
||||
} else {
|
||||
ci.arcname = get_arcname(loc, opts.Dest, home)
|
||||
}
|
||||
ans = append(ans, &ci)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type file_unique_id struct {
|
||||
dev, inode uint64
|
||||
}
|
||||
|
||||
func excluded(pattern, path string) bool {
|
||||
if !strings.ContainsRune(pattern, '/') {
|
||||
path = filepath.Base(path)
|
||||
}
|
||||
if matched, err := doublestar.PathMatch(pattern, path); matched && err == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func get_file_data(callback func(h *tar.Header, data []byte) error, seen map[file_unique_id]string, local_path, arcname string, exclude_patterns []string) error {
|
||||
var s unix.Stat_t
|
||||
if err := unix.Lstat(local_path, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
cb := func(h *tar.Header, data []byte, arcname string, st *unix.Stat_t) error {
|
||||
h.Name = arcname
|
||||
if h.Typeflag == tar.TypeDir {
|
||||
h.Name = strings.TrimRight(h.Name, "/") + "/"
|
||||
}
|
||||
h.Size = int64(len(data))
|
||||
h.Mode = int64(st.Mode & 0777) // discard the setuid, setgid and sticky bits
|
||||
h.ModTime = time.Unix(st.Mtim.Unix())
|
||||
h.AccessTime = time.Unix(st.Atim.Unix())
|
||||
h.ChangeTime = time.Unix(st.Ctim.Unix())
|
||||
h.Format = tar.FormatPAX
|
||||
return callback(h, data)
|
||||
}
|
||||
// we only copy regular files, directories and symlinks
|
||||
switch s.Mode & unix.S_IFMT {
|
||||
case unix.S_IFBLK, unix.S_IFIFO, unix.S_IFCHR, unix.S_IFSOCK: // ignored
|
||||
case unix.S_IFLNK: // symlink
|
||||
target, err := os.Readlink(local_path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = cb(&tar.Header{
|
||||
Typeflag: tar.TypeSymlink,
|
||||
Linkname: target,
|
||||
}, nil, arcname, &s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case unix.S_IFDIR: // directory
|
||||
local_path = filepath.Clean(local_path)
|
||||
type entry struct {
|
||||
path, arcname string
|
||||
}
|
||||
stack := []entry{{local_path, arcname}}
|
||||
for len(stack) > 0 {
|
||||
x := stack[0]
|
||||
stack = stack[1:]
|
||||
// Each directory needs its own metadata, re-check its type as it
|
||||
// may have been replaced since its parent was read
|
||||
ds := s
|
||||
if x.path != local_path {
|
||||
if err := unix.Lstat(x.path, &ds); err != nil || ds.Mode&unix.S_IFMT != unix.S_IFDIR {
|
||||
continue
|
||||
}
|
||||
}
|
||||
entries, err := os.ReadDir(x.path)
|
||||
if err != nil {
|
||||
if x.path == local_path {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
err = cb(&tar.Header{Typeflag: tar.TypeDir}, nil, x.arcname, &ds)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range entries {
|
||||
entry_path := filepath.Join(x.path, e.Name())
|
||||
aname := path.Join(x.arcname, e.Name())
|
||||
ok := true
|
||||
for _, pat := range exclude_patterns {
|
||||
if excluded(pat, entry_path) {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if e.IsDir() {
|
||||
stack = append(stack, entry{entry_path, aname})
|
||||
} else {
|
||||
err = get_file_data(callback, seen, entry_path, aname, exclude_patterns)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
case unix.S_IFREG: // Regular file
|
||||
fid := file_unique_id{dev: uint64(s.Dev), inode: uint64(s.Ino)}
|
||||
if prev, ok := seen[fid]; ok { // Hard link
|
||||
return cb(&tar.Header{Typeflag: tar.TypeLink, Linkname: prev}, nil, arcname, &s)
|
||||
}
|
||||
seen[fid] = arcname
|
||||
data, err := os.ReadFile(local_path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = cb(&tar.Header{Typeflag: tar.TypeReg}, data, arcname, &s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ci *CopyInstruction) get_file_data(callback func(h *tar.Header, data []byte) error, seen map[file_unique_id]string) (err error) {
|
||||
ep := ci.exclude_patterns
|
||||
for _, folder_name := range []string{"__pycache__", ".DS_Store"} {
|
||||
ep = append(ep, "**/"+folder_name, "**/"+folder_name+"/**")
|
||||
}
|
||||
return get_file_data(callback, seen, ci.local_path, ci.arcname, ep)
|
||||
}
|
||||
|
||||
type ConfigSet struct {
|
||||
all_configs []*Config
|
||||
}
|
||||
|
||||
func config_for_hostname(hostname_to_match, username_to_match string, cs *ConfigSet) *Config {
|
||||
matcher := func(q *Config) bool {
|
||||
for pat := range strings.SplitSeq(q.Hostname, " ") {
|
||||
upat := "*"
|
||||
if strings.Contains(pat, "@") {
|
||||
upat, pat, _ = strings.Cut(pat, "@")
|
||||
}
|
||||
var host_matched, user_matched bool
|
||||
if matched, err := filepath.Match(pat, hostname_to_match); matched && err == nil {
|
||||
host_matched = true
|
||||
}
|
||||
if matched, err := filepath.Match(upat, username_to_match); matched && err == nil {
|
||||
user_matched = true
|
||||
}
|
||||
if host_matched && user_matched {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for _, c := range utils.Reversed(cs.all_configs) {
|
||||
if matcher(c) {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return cs.all_configs[0]
|
||||
}
|
||||
|
||||
func (self *ConfigSet) line_handler(key, val string) error {
|
||||
c := self.all_configs[len(self.all_configs)-1]
|
||||
if key == "hostname" {
|
||||
c = NewConfig()
|
||||
self.all_configs = append(self.all_configs, c)
|
||||
}
|
||||
return c.Parse(key, val)
|
||||
}
|
||||
|
||||
func load_config(hostname_to_match string, username_to_match string, overrides []string, paths ...string) (*Config, []config.ConfigLine, error) {
|
||||
ans := &ConfigSet{all_configs: []*Config{NewConfig()}}
|
||||
p := config.ConfigParser{LineHandler: ans.line_handler}
|
||||
err := p.LoadConfig("ssh.conf", paths, nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
final_conf := config_for_hostname(hostname_to_match, username_to_match, ans)
|
||||
bad_lines := p.BadLines()
|
||||
if len(overrides) > 0 {
|
||||
h := final_conf.Hostname
|
||||
override_parser := config.ConfigParser{LineHandler: final_conf.Parse}
|
||||
if err = override_parser.ParseOverrides(overrides...); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
bad_lines = append(bad_lines, override_parser.BadLines()...)
|
||||
final_conf.Hostname = h
|
||||
}
|
||||
return final_conf, bad_lines, nil
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/paths"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Pair struct {
|
||||
Input, Uname, Host string
|
||||
}
|
||||
|
||||
func TestSSHConfigParsing(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
hostname := "unmatched"
|
||||
username := ""
|
||||
conf := ""
|
||||
overrides := []string{}
|
||||
for_python := false
|
||||
cf := filepath.Join(tdir, "ssh.conf")
|
||||
rt := func(expected_env ...string) {
|
||||
if err := os.WriteFile(cf, []byte(conf), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, bad_lines, err := load_config(hostname, username, overrides, cf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(bad_lines) != 0 {
|
||||
t.Fatalf("Bad config line: %s with error: %s", bad_lines[0].Line, bad_lines[0].Err)
|
||||
}
|
||||
actual := final_env_instructions(for_python, func(key string) (string, bool) {
|
||||
if key == "LOCAL_ENV" {
|
||||
return "LOCAL_VAL", true
|
||||
}
|
||||
return "", false
|
||||
}, c.Env...)
|
||||
if expected_env == nil {
|
||||
expected_env = []string{}
|
||||
}
|
||||
diff := cmp.Diff(expected_env, utils.Splitlines(actual))
|
||||
if diff != "" {
|
||||
t.Fatalf("Unexpected env for\nhostname: %#v\nusername: %#v\nconf: %s\n%s", hostname, username, conf, diff)
|
||||
}
|
||||
}
|
||||
rt()
|
||||
conf = "env a=b"
|
||||
rt(`export 'a'="b"`)
|
||||
conf = "env a=b"
|
||||
overrides = []string{"env=c=d"}
|
||||
rt(`export 'a'="b"`, `export 'c'="d"`)
|
||||
overrides = nil
|
||||
|
||||
conf = "env a=\\"
|
||||
rt(`export 'a'="\\"`)
|
||||
conf = `env
|
||||
\ a=
|
||||
\\`
|
||||
conf = "env\n \t \\ a=\n\\\\"
|
||||
rt(`export 'a'="\\"`)
|
||||
conf = `
|
||||
e
|
||||
\n
|
||||
\v
|
||||
\ a
|
||||
\=
|
||||
\\
|
||||
\`
|
||||
rt(`export 'a'="\\"`)
|
||||
|
||||
conf = "env a=b\nhostname 2\nenv a=c\nenv b=b"
|
||||
rt(`export 'a'="b"`)
|
||||
hostname = "2"
|
||||
rt(`export 'a'="c"`, `export 'b'="b"`)
|
||||
conf = "env a="
|
||||
rt(`export 'a'=""`)
|
||||
conf = "env a"
|
||||
rt(`unset 'a'`)
|
||||
conf = "env a=b\nhostname test@2\nenv a=c\nenv b=b"
|
||||
hostname = "unmatched"
|
||||
rt(`export 'a'="b"`)
|
||||
hostname = "2"
|
||||
rt(`export 'a'="b"`)
|
||||
username = "test"
|
||||
rt(`export 'a'="c"`, `export 'b'="b"`)
|
||||
conf = "env a=b\nhostname 1 2\nenv a=c\nenv b=b"
|
||||
username = ""
|
||||
hostname = "unmatched"
|
||||
rt(`export 'a'="b"`)
|
||||
hostname = "1"
|
||||
rt(`export 'a'="c"`, `export 'b'="b"`)
|
||||
hostname = "2"
|
||||
rt(`export 'a'="c"`, `export 'b'="b"`)
|
||||
for_python = true
|
||||
rt(`export ["a","c",false]`, `export ["b","b",false]`)
|
||||
conf = "env a="
|
||||
rt(`export ["a"]`)
|
||||
conf = "env a"
|
||||
rt(`unset ["a"]`)
|
||||
conf = "env LOCAL_ENV=_kitty_copy_env_var_"
|
||||
rt(`export ["LOCAL_ENV","LOCAL_VAL",false]`)
|
||||
conf = "env a=b\nhostname 2\ncolor_scheme xyz"
|
||||
hostname = "2"
|
||||
rt()
|
||||
|
||||
ci, err := ParseCopyInstruction("--exclude moose --exclude second --dest=target " + cf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
diff := cmp.Diff("home/target", ci[0].arcname)
|
||||
if diff != "" {
|
||||
t.Fatalf("Incorrect arcname:\n%s", diff)
|
||||
}
|
||||
diff = cmp.Diff(cf, ci[0].local_path)
|
||||
if diff != "" {
|
||||
t.Fatalf("Incorrect local_path:\n%s", diff)
|
||||
}
|
||||
diff = cmp.Diff([]string{"moose", "second"}, ci[0].exclude_patterns)
|
||||
if diff != "" {
|
||||
t.Fatalf("Incorrect excludes:\n%s", diff)
|
||||
}
|
||||
ci, err = ParseCopyInstruction("--glob " + filepath.Join(filepath.Dir(cf), "*.conf"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
diff = cmp.Diff(cf, ci[0].local_path)
|
||||
if diff != "" {
|
||||
t.Fatalf("Incorrect local_path:\n%s", diff)
|
||||
}
|
||||
if len(ci) != 1 {
|
||||
t.Fatal(ci)
|
||||
}
|
||||
|
||||
u, _ := user.Current()
|
||||
un := u.Username
|
||||
for _, x := range []Pair{
|
||||
{"localhost:12", un, "localhost:12"},
|
||||
{"@localhost", un, "@localhost"},
|
||||
{"ssh://@localhost:33", un, "localhost"},
|
||||
{"me@localhost", "me", "localhost"},
|
||||
{"ssh://me@localhost:12/something?else=1", "me", "localhost"},
|
||||
} {
|
||||
ue, uh := get_destination(x.Input)
|
||||
q := Pair{x.Input, ue, uh}
|
||||
if diff := cmp.Diff(x, q); diff != "" {
|
||||
t.Fatalf("Failed: %s", diff)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestSSHCopyArcnames(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, loc, dest, home, expected string
|
||||
}{
|
||||
{"home", "/home/alice", "", "/home/alice", "home/."},
|
||||
{"inside home", "/home/alice/.config/app", "", "/home/alice", "home/.config/app"},
|
||||
{"sibling directory", "/home/alice-backup/config", "", "/home/alice", "root/home/alice-backup/config"},
|
||||
{"sibling user", "/home/alice2/config", "", "/home/alice", "root/home/alice2/config"},
|
||||
{"outside home", "/etc/config", "", "/home/alice", "root/etc/config"},
|
||||
{"cleaned path", "/home/alice/../alice-backup/config", "", "/home/alice", "root/home/alice-backup/config"},
|
||||
{"trailing slash", "/home/alice/.config/app", "", "/home/alice/", "home/.config/app"},
|
||||
{"root home", "/etc/config", "", "/", "home/etc/config"},
|
||||
{"relative destination", "/home/alice-backup/config", "config", "/home/alice", "home/config"},
|
||||
{"absolute destination", "/home/alice/config", "/etc/config", "/home/alice", "root/etc/config"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if actual := get_arcname(tc.loc, tc.dest, tc.home); actual != tc.expected {
|
||||
t.Fatalf("Incorrect arcname: %q != %q", actual, tc.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHCopySymlinkedHome(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
real_home := filepath.Join(tdir, "usr", "home", "alice")
|
||||
if err := os.MkdirAll(real_home, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(tdir, "usr", "home"), filepath.Join(tdir, "home")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(real_home, "config"), []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
home := filepath.Join(tdir, "home", "alice")
|
||||
orig_paths_ctx := paths_ctx
|
||||
defer func() { paths_ctx = orig_paths_ctx }()
|
||||
paths_ctx = &paths.Ctx{}
|
||||
paths_ctx.SetHome(home)
|
||||
for _, strategy := range []string{"preserve", "keep-path", "resolve"} {
|
||||
t.Run(strategy, func(t *testing.T) {
|
||||
ci, err := ParseCopyInstruction("--symlink-strategy=" + strategy + " " + filepath.Join(home, "config"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ci[0].arcname != "home/config" {
|
||||
t.Fatalf("Incorrect arcname: %q != %q", ci[0].arcname, "home/config")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHCopyDirectoryMetadata(t *testing.T) {
|
||||
root := filepath.Join(t.TempDir(), "tree")
|
||||
dirs := []struct {
|
||||
name string
|
||||
mode os.FileMode
|
||||
}{
|
||||
{"", 0o755},
|
||||
{"private", 0o700},
|
||||
{"private/nested", 0o750},
|
||||
{"other", 0o711},
|
||||
}
|
||||
for _, d := range dirs {
|
||||
name := filepath.Join(root, d.name)
|
||||
if err := os.MkdirAll(name, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(name, d.mode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// symlinks to directories must be copied as symlinks
|
||||
if err := os.Symlink("private", filepath.Join(root, "link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, d := range dirs {
|
||||
stamp := time.Unix(1600000000+int64(i)*60, 0)
|
||||
if err := os.Chtimes(filepath.Join(root, d.name), stamp, stamp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
headers := make(map[string]tar.Header)
|
||||
ci := CopyInstruction{local_path: root, arcname: "home/tree"}
|
||||
if err := ci.get_file_data(func(h *tar.Header, data []byte) error {
|
||||
headers[strings.TrimSuffix(h.Name, "/")] = *h
|
||||
return nil
|
||||
}, make(map[file_unique_id]string)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, d := range dirs {
|
||||
name := filepath.ToSlash(filepath.Join("home/tree", d.name))
|
||||
h, found := headers[name]
|
||||
if !found {
|
||||
t.Fatalf("Missing directory: %s", name)
|
||||
}
|
||||
if h.Typeflag != tar.TypeDir {
|
||||
t.Errorf("%s: not a directory", name)
|
||||
}
|
||||
if h.Mode != int64(d.mode) {
|
||||
t.Errorf("%s: permissions %04o != %04o", name, h.Mode, d.mode)
|
||||
}
|
||||
if expected := time.Unix(1600000000+int64(i)*60, 0); !h.ModTime.Equal(expected) {
|
||||
t.Errorf("%s: modification time %s != %s", name, h.ModTime, expected)
|
||||
}
|
||||
}
|
||||
if h := headers["home/tree/link"]; h.Typeflag != tar.TypeSymlink || h.Linkname != "private" {
|
||||
t.Errorf("Symlink to directory not copied as symlink: %#v", h)
|
||||
}
|
||||
}
|
||||
+1125
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,396 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
|
||||
from kitty.conf.types import Definition
|
||||
from kitty.types import run_once
|
||||
|
||||
copy_message = """\
|
||||
Copy files and directories from local to remote hosts. The specified files are
|
||||
assumed to be relative to the HOME directory and copied to the HOME on the
|
||||
remote. Directories are copied recursively. If absolute paths are used, they are
|
||||
copied as is."""
|
||||
|
||||
|
||||
@run_once
|
||||
def option_text() -> str:
|
||||
return """
|
||||
--glob
|
||||
type=bool-set
|
||||
Interpret file arguments as glob patterns. Globbing is based on
|
||||
standard wildcards with the addition that ``/**/`` matches any number of directories.
|
||||
See the :link:`detailed syntax <https://github.com/bmatcuk/doublestar#patterns>`.
|
||||
|
||||
|
||||
--dest
|
||||
The destination on the remote host to copy to. Relative paths are resolved
|
||||
relative to HOME on the remote host. When this option is not specified, the
|
||||
local file path is used as the remote destination (with the HOME directory
|
||||
getting automatically replaced by the remote HOME). Note that environment
|
||||
variables and ~ are not expanded.
|
||||
|
||||
|
||||
--exclude
|
||||
type=list
|
||||
A glob pattern. Files with names matching this pattern are excluded from being
|
||||
transferred. Only used when copying directories. Can
|
||||
be specified multiple times, if any of the patterns match the file will be
|
||||
excluded. If the pattern includes a :code:`/` then it will match against the full
|
||||
path, not just the filename. In such patterns you can use :code:`/**/` to match zero
|
||||
or more directories. For example, to exclude a directory and everything under it use
|
||||
:code:`**/directory_name`.
|
||||
See the :link:`detailed syntax <https://github.com/bmatcuk/doublestar#patterns>` for
|
||||
how wildcards match.
|
||||
|
||||
|
||||
--symlink-strategy
|
||||
default=preserve
|
||||
choices=preserve,resolve,keep-path
|
||||
Control what happens if the specified path is a symlink. The default is to preserve
|
||||
the symlink, re-creating it on the remote machine. Setting this to :code:`resolve`
|
||||
will cause the symlink to be followed and its target used as the file/directory to copy.
|
||||
The value of :code:`keep-path` is the same as :code:`resolve` except that the remote
|
||||
file path is derived from the symlink's path instead of the path of the symlink's target.
|
||||
Note that this option does not apply to symlinks encountered while recursively copying directories,
|
||||
those are always preserved.
|
||||
"""
|
||||
|
||||
|
||||
definition = Definition(
|
||||
'!kittens.ssh',
|
||||
)
|
||||
|
||||
agr = definition.add_group
|
||||
egr = definition.end_group
|
||||
opt = definition.add_option
|
||||
|
||||
agr('bootstrap', 'Host bootstrap configuration') # {{{
|
||||
|
||||
opt(
|
||||
'hostname',
|
||||
'*',
|
||||
long_text="""
|
||||
The hostname that the following options apply to. A glob pattern to match
|
||||
multiple hosts can be used. Multiple hostnames can also be specified, separated
|
||||
by spaces. The hostname can include an optional username in the form
|
||||
:code:`user@host`. When not specified options apply to all hosts, until the
|
||||
first hostname specification is found. Note that matching of hostname is done
|
||||
against the name you specify on the command line to connect to the remote host.
|
||||
If you wish to include the same basic configuration for many different hosts,
|
||||
you can do so with the :ref:`include <include>` directive. In version 0.28.0
|
||||
the behavior of this option was changed slightly, now, when a hostname is encountered
|
||||
all its config values are set to defaults instead of being inherited from a previous
|
||||
matching hostname block. In particular it means hostnames dont inherit configurations,
|
||||
thereby avoiding hard to understand action-at-a-distance.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'interpreter',
|
||||
'sh',
|
||||
long_text="""
|
||||
The interpreter to use on the remote host. Must be either a POSIX complaint
|
||||
shell or a :program:`python` executable. If the default :program:`sh` is not
|
||||
available or broken, using an alternate interpreter can be useful.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'remote_dir',
|
||||
'.local/share/kitty-ssh-kitten',
|
||||
long_text="""
|
||||
The location on the remote host where the files needed for this kitten are
|
||||
installed. Relative paths are resolved with respect to :code:`$HOME`. Absolute
|
||||
paths have their leading / removed and so are also resolved with respect to $HOME.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'+copy',
|
||||
'',
|
||||
add_to_default=False,
|
||||
ctype='CopyInstruction',
|
||||
long_text=f"""
|
||||
{copy_message} For example::
|
||||
|
||||
copy .vimrc .zshrc .config/some-dir
|
||||
|
||||
Use :code:`--dest` to copy a file to some other destination on the remote host::
|
||||
|
||||
copy --dest some-other-name some-file
|
||||
|
||||
Glob patterns can be specified to copy multiple files, with :code:`--glob`::
|
||||
|
||||
copy --glob images/*.png
|
||||
|
||||
Files can be excluded when copying with :code:`--exclude`::
|
||||
|
||||
copy --glob --exclude *.jpg --exclude *.bmp images/*
|
||||
|
||||
Files whose remote name matches the exclude pattern will not be copied.
|
||||
For more details, see :ref:`ssh_copy_command`.
|
||||
""",
|
||||
)
|
||||
egr() # }}}
|
||||
|
||||
agr('shell', 'Login shell environment') # {{{
|
||||
|
||||
opt(
|
||||
'shell_integration',
|
||||
'inherited',
|
||||
long_text="""
|
||||
Control the shell integration on the remote host. See :ref:`shell_integration`
|
||||
for details on how this setting works. The special value :code:`inherited` means
|
||||
use the setting from :file:`kitty.conf`. This setting is useful for overriding
|
||||
integration on a per-host basis.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'login_shell',
|
||||
'',
|
||||
long_text="""
|
||||
The login shell to execute on the remote host. By default, the remote user
|
||||
account's login shell is used.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'+env',
|
||||
'',
|
||||
add_to_default=False,
|
||||
ctype='EnvInstruction',
|
||||
long_text="""
|
||||
Specify the environment variables to be set on the remote host. Using the
|
||||
name with an equal sign (e.g. :code:`env VAR=`) will set it to the empty string.
|
||||
Specifying only the name (e.g. :code:`env VAR`) will remove the variable from
|
||||
the remote shell environment. The special value :code:`_kitty_copy_env_var_`
|
||||
will cause the value of the variable to be copied from the local environment.
|
||||
The definitions are processed alphabetically. Note that environment variables
|
||||
are expanded recursively, for example::
|
||||
|
||||
env VAR1=a
|
||||
env VAR2=${HOME}/${VAR1}/b
|
||||
|
||||
The value of :code:`VAR2` will be :code:`<path to home directory>/a/b`.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'cwd',
|
||||
'',
|
||||
long_text="""
|
||||
The working directory on the remote host to change to. Environment variables in
|
||||
this value are expanded. The default is empty so no changing is done, which
|
||||
usually means the HOME directory is used.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'color_scheme',
|
||||
'',
|
||||
long_text="""
|
||||
Specify a color scheme to use when connecting to the remote host. If this option
|
||||
ends with :code:`.conf`, it is assumed to be the name of a config file to load
|
||||
from the kitty config directory, otherwise it is assumed to be the name of a
|
||||
color theme to load via the :doc:`themes kitten </kittens/themes>`. Note that
|
||||
only colors applying to the text/background are changed, other config settings
|
||||
in the .conf files/themes are ignored. To use different color schemes depending
|
||||
on whether the operating system is in dark or light mode, see
|
||||
:opt:`kitten-ssh.color_scheme_dark`.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'color_scheme_dark',
|
||||
'',
|
||||
long_text="""
|
||||
Specify a color scheme to use when connecting to the remote host while the
|
||||
operating system is in dark mode. Uses the same syntax as
|
||||
:opt:`kitten-ssh.color_scheme`. Similarly, use :opt:`kitten-ssh.color_scheme_light`
|
||||
and :opt:`kitten-ssh.color_scheme_no_preference` for light mode and when the
|
||||
operating system has no preference. When the operating system switches between
|
||||
modes, the colors of the remote session switch accordingly, just as for
|
||||
:ref:`automatic color themes <auto_color_scheme>` in kitty itself. For a mode
|
||||
with no color scheme specified, :opt:`kitten-ssh.color_scheme` is used, and if
|
||||
that is also not specified, the colors from kitty for that mode are used. For
|
||||
example::
|
||||
|
||||
color_scheme_dark Solarized Dark
|
||||
color_scheme_light Solarized Light
|
||||
|
||||
Requires the ssh kitten to be run in kitty, outside of terminal multiplexers
|
||||
such as tmux. Otherwise, only :opt:`kitten-ssh.color_scheme` is used.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'color_scheme_light',
|
||||
'',
|
||||
long_text="""
|
||||
Specify a color scheme to use when connecting to the remote host while the
|
||||
operating system is in light mode. See :opt:`kitten-ssh.color_scheme_dark` for
|
||||
details.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'color_scheme_no_preference',
|
||||
'',
|
||||
long_text="""
|
||||
Specify a color scheme to use when connecting to the remote host while the
|
||||
operating system has no dark or light mode preference. See
|
||||
:opt:`kitten-ssh.color_scheme_dark` for details.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'remote_kitty',
|
||||
'if-needed',
|
||||
choices=('if-needed', 'no', 'yes'),
|
||||
long_text="""
|
||||
Make :program:`kitten` available on the remote host. Useful to run kittens such
|
||||
as the :doc:`icat kitten </kittens/icat>` to display images or the
|
||||
:doc:`transfer file kitten </kittens/transfer>` to transfer files. Only works if
|
||||
the remote host has an architecture for which :link:`pre-compiled kitten binaries
|
||||
<https://github.com/kovidgoyal/kitty/releases>` are available. Note that kitten
|
||||
is not actually copied to the remote host, instead a small bootstrap script is
|
||||
copied which will download and run kitten when kitten is first executed on the
|
||||
remote host. A value of :code:`if-needed` means kitten is installed only if not
|
||||
already present in the system-wide PATH. A value of :code:`yes` means that kitten
|
||||
is installed even if already present, and the installed kitten takes precedence.
|
||||
Finally, :code:`no` means no kitten is installed on the remote host. The
|
||||
installed kitten can be updated by running: :code:`kitten update-self` on the
|
||||
remote host.
|
||||
""",
|
||||
)
|
||||
egr() # }}}
|
||||
|
||||
agr('ssh', 'SSH configuration') # {{{
|
||||
|
||||
opt(
|
||||
'share_connections',
|
||||
'yes',
|
||||
option_type='to_bool',
|
||||
long_text="""
|
||||
Within a single kitty instance, all connections to a particular server can be
|
||||
shared. This reduces startup latency for subsequent connections and means that
|
||||
you have to enter the password only once. Under the hood, it uses SSH
|
||||
ControlMasters and these are automatically cleaned up by kitty when it quits.
|
||||
You can map a shortcut to :ac:`close_shared_ssh_connections` to disconnect all
|
||||
active shared connections.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'askpass',
|
||||
'unless-set',
|
||||
choices=('unless-set', 'ssh', 'native'),
|
||||
long_text="""
|
||||
Control the program SSH uses to ask for passwords or confirmation of host keys
|
||||
etc. The default is to use kitty's native :program:`askpass`, unless the
|
||||
:envvar:`SSH_ASKPASS` environment variable is set. Set this option to
|
||||
:code:`ssh` to not interfere with the normal ssh askpass mechanism at all, which
|
||||
typically means that ssh will prompt at the terminal. Set it to :code:`native`
|
||||
to always use kitty's native, built-in askpass implementation. Note that not
|
||||
using the kitty askpass implementation means that SSH might need to use the
|
||||
terminal before the connection is established, so the kitten cannot use the
|
||||
terminal to send data without an extra roundtrip, adding to initial connection
|
||||
latency.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'delegate',
|
||||
'',
|
||||
long_text="""
|
||||
Do not use the SSH kitten for this host. Instead run the command specified as the delegate.
|
||||
For example using :code:`delegate ssh` will run the ssh command with all arguments passed
|
||||
to the kitten, except kitten specific ones. This is useful if some hosts are not capable
|
||||
of supporting the ssh kitten.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'forward_remote_control',
|
||||
'no',
|
||||
option_type='to_bool',
|
||||
long_text="""
|
||||
Forward the kitty remote control socket to the remote host. This allows using the kitty
|
||||
remote control facilities from the remote host. WARNING: This allows any software
|
||||
on the remote host full access to the local computer, so only do it for trusted remote hosts.
|
||||
Note that this does not work with abstract UNIX sockets such as :file:`@mykitty` because of SSH limitations.
|
||||
This option uses SSH socket forwarding to forward the socket pointed to by the :envvar:`KITTY_LISTEN_ON`
|
||||
environment variable.
|
||||
""",
|
||||
)
|
||||
|
||||
egr() # }}}
|
||||
|
||||
agr('askpass', 'Askpass automation') # {{{
|
||||
|
||||
opt(
|
||||
'password',
|
||||
'',
|
||||
long_text="""
|
||||
Specify a password to use when SSH prompts for a password. The value format is
|
||||
"backend:secret". Currently, only the "text" backend is supported, which stores
|
||||
the secret in plain text in the config file. For example:
|
||||
|
||||
password text:my_password
|
||||
|
||||
If the backend prefix is omitted, it is treated as "text:" for backward
|
||||
compatibility. Beware that storing passwords in plain text is insecure.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'totp_secret',
|
||||
'',
|
||||
long_text="""
|
||||
Specify a TOTP shared secret to auto-fill one-time codes when SSH asks for them.
|
||||
The value format is "backend:secret". Currently, only the "text" backend is
|
||||
supported. For example:
|
||||
|
||||
totp_secret text:JBSWY3DPEHPK3PXP
|
||||
|
||||
If the backend prefix is omitted, it is treated as "text:" for backward
|
||||
compatibility.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'totp_digits',
|
||||
'6',
|
||||
option_type='int',
|
||||
long_text="""
|
||||
Number of digits for the generated TOTP codes. Default is 6.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'totp_period',
|
||||
'30',
|
||||
option_type='int',
|
||||
long_text="""
|
||||
Time period in seconds for the TOTP code validity. Default is 30.
|
||||
""",
|
||||
)
|
||||
|
||||
egr() # }}}
|
||||
|
||||
|
||||
def main(args: list[str]) -> str | None:
|
||||
raise SystemExit('This should be run as kitten ssh')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main([])
|
||||
elif __name__ == '__wrapper_of__':
|
||||
cd = getattr(sys, 'cli_docs')
|
||||
cd['wrapper_of'] = 'ssh'
|
||||
elif __name__ == '__conf__':
|
||||
setattr(sys, 'options_definition', definition)
|
||||
elif __name__ == '__extra_cli_parsers__':
|
||||
setattr(sys, 'extra_cli_parsers', {'copy': option_text()})
|
||||
@@ -0,0 +1,231 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
shm "github.com/kovidgoyal/go-shm/v2"
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/themes"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestCloneEnv(t *testing.T) {
|
||||
env := map[string]string{"a": "1", "b": "2"}
|
||||
data, err := json.Marshal(env)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mmap, err := shm.CreateTemp("", 128)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer mmap.Unlink()
|
||||
copy(mmap.Slice()[4:], data)
|
||||
binary.BigEndian.PutUint32(mmap.Slice(), uint32(len(data)))
|
||||
mmap.Close()
|
||||
x, err := add_cloned_env(mmap.Name())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
diff := cmp.Diff(env, x)
|
||||
if diff != "" {
|
||||
t.Fatalf("Failed to deserialize env\n%s", diff)
|
||||
}
|
||||
}
|
||||
|
||||
func basic_connection_data(overrides ...string) *connection_data {
|
||||
ans := &connection_data{
|
||||
script_type: "sh", request_id: "123-123", remote_args: []string{},
|
||||
username: "testuser", hostname_for_match: "host.test",
|
||||
dont_create_shm: true,
|
||||
}
|
||||
opts, bad_lines, err := load_config(ans.hostname_for_match, ans.username, overrides)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if len(bad_lines) != 0 {
|
||||
panic(fmt.Sprintf("Bad config lines: %s with error: %s", bad_lines[0].Line, bad_lines[0].Err))
|
||||
}
|
||||
ans.host_opts = opts
|
||||
return ans
|
||||
}
|
||||
|
||||
func TestSSHBootstrapScriptLimit(t *testing.T) {
|
||||
cd := basic_connection_data()
|
||||
err := get_remote_command(cd)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
total := 0
|
||||
for _, x := range cd.rcmd {
|
||||
total += len(x)
|
||||
}
|
||||
if total > 9000 {
|
||||
t.Fatalf("Bootstrap script too large: %d bytes", total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHTarfile(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
cd := basic_connection_data()
|
||||
data, err := make_tarfile(cd, func(key string) (val string, found bool) { return })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command("tar", "xpzf", "-", "-C", tdir)
|
||||
cmd.Stderr = os.Stderr
|
||||
inp, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = cmd.Start()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = inp.Write(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inp.Close()
|
||||
err = cmd.Wait()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
err = filepath.WalkDir(tdir, func(name string, d fs.DirEntry, werr error) error {
|
||||
if werr != nil {
|
||||
return werr
|
||||
}
|
||||
rname, werr := filepath.Rel(tdir, name)
|
||||
if werr != nil {
|
||||
return werr
|
||||
}
|
||||
rname = strings.ReplaceAll(rname, "\\", "/")
|
||||
if rname == "." {
|
||||
return nil
|
||||
}
|
||||
fi, werr := d.Info()
|
||||
if werr != nil {
|
||||
return werr
|
||||
}
|
||||
if fi.Mode().Perm()&0o600 == 0 {
|
||||
return fmt.Errorf("%s is not rw for its owner. Actual permissions: %s", rname, fi.Mode().String())
|
||||
}
|
||||
seen[rname] = true
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !seen["data.sh"] {
|
||||
t.Fatalf("data.sh missing")
|
||||
}
|
||||
for _, x := range []string{".terminfo/kitty.terminfo", ".terminfo/x/" + kitty.DefaultTermName} {
|
||||
if !seen["home/"+x] {
|
||||
t.Fatalf("%s missing", x)
|
||||
}
|
||||
}
|
||||
for _, x := range []string{"shell-integration/bash/kitty.bash", "shell-integration/fish/vendor_completions.d/kitty.fish"} {
|
||||
if !seen[path.Join("home", cd.host_opts.Remote_dir, x)] {
|
||||
t.Fatalf("%s missing", x)
|
||||
}
|
||||
}
|
||||
for _, x := range []string{"kitty", "kitten"} {
|
||||
p := filepath.Join(tdir, "home", cd.host_opts.Remote_dir, "kitty", "bin", x)
|
||||
if err = unix.Access(p, unix.X_OK); err != nil {
|
||||
t.Fatalf("Cannot execute %s with error: %s", x, err)
|
||||
}
|
||||
}
|
||||
if seen[path.Join("home", cd.host_opts.Remote_dir, "shell-integration", "ssh", "kitten")] {
|
||||
t.Fatalf("Contents of shell-integration/ssh not excluded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHChangeColors(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
write_conf := func(name, text string) string {
|
||||
p := filepath.Join(tdir, name)
|
||||
if err := os.WriteFile(p, []byte(text), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
a := write_conf("a.conf", "background #010101\nforeground #020202\ncolor1 #030303\n")
|
||||
b := write_conf("b.conf", "background #fefefe\ncolor1 #fdfdfd\n")
|
||||
settings := func(p string) map[string]string {
|
||||
s, err := load_color_schemes(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s[p]
|
||||
}
|
||||
change := func(c Config) string {
|
||||
ans, err := change_colors(&c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
// existing configs with only color_scheme use escape codes
|
||||
if ans := change(Config{}); ans != "" {
|
||||
t.Fatalf("Colors changed with no color scheme: %#v", ans)
|
||||
}
|
||||
if ans := change(Config{Color_scheme: a}); ans != "\x1b[#P"+themes.ColorSettingsAsEscapeCodes(settings(a)) {
|
||||
t.Fatalf("Incorrect escape codes for color_scheme: %#v", ans)
|
||||
}
|
||||
if _, err := change_colors(&Config{Color_scheme_dark: filepath.Join(tdir, "missing.conf")}); err == nil {
|
||||
t.Fatal("No error for missing color scheme file")
|
||||
}
|
||||
|
||||
variants := func(c Config) map[string]any {
|
||||
ans := change(c)
|
||||
prefix := "\x1b[#P\x1bP@kitty-color-scheme|"
|
||||
if !strings.HasPrefix(ans, prefix) || !strings.HasSuffix(ans, "\x1b\\") {
|
||||
t.Fatalf("Incorrect escape code for color scheme variants: %#v", ans)
|
||||
}
|
||||
data, err := base64.StdEncoding.DecodeString(ans[len(prefix) : len(ans)-2])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err = json.Unmarshal(data, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return payload
|
||||
}
|
||||
spec := func(p string) any {
|
||||
data, err := json.Marshal(themes.ColorSettingsAsSpec(settings(p)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ans any
|
||||
if err = json.Unmarshal(data, &ans); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
// color_scheme is used for modes without a specific color scheme
|
||||
if diff := cmp.Diff(map[string]any{"dark": spec(b), "light": spec(a), "no_preference": spec(a)}, variants(Config{Color_scheme: a, Color_scheme_dark: b})); diff != "" {
|
||||
t.Fatalf("Incorrect color scheme variants:\n%s", diff)
|
||||
}
|
||||
// modes without any color scheme use the colors from kitty
|
||||
if diff := cmp.Diff(map[string]any{"light": spec(b)}, variants(Config{Color_scheme_light: b})); diff != "" {
|
||||
t.Fatalf("Incorrect color scheme variants:\n%s", diff)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
var SSHExe = sync.OnceValue(func() string {
|
||||
return utils.FindExe("ssh")
|
||||
})
|
||||
|
||||
var SSHOptions = sync.OnceValue(func() (ssh_options map[string]string) {
|
||||
defer func() {
|
||||
if ssh_options == nil {
|
||||
ssh_options = map[string]string{
|
||||
"4": "", "6": "", "A": "", "a": "", "C": "", "f": "", "G": "", "g": "", "K": "", "k": "",
|
||||
"M": "", "N": "", "n": "", "q": "", "s": "", "T": "", "t": "", "V": "", "v": "", "X": "",
|
||||
"x": "", "Y": "", "y": "", "B": "bind_interface", "b": "bind_address", "c": "cipher_spec",
|
||||
"D": "[bind_address:]port", "E": "log_file", "e": "escape_char", "F": "configfile", "I": "pkcs11",
|
||||
"i": "identity_file", "J": "[user@]host[:port]", "L": "address", "l": "login_name", "m": "mac_spec",
|
||||
"O": "ctl_cmd", "o": "option", "p": "port", "Q": "query_option", "R": "address",
|
||||
"S": "ctl_path", "W": "host:port", "w": "local_tun[:remote_tun]",
|
||||
}
|
||||
}
|
||||
}()
|
||||
cmd := exec.Command(SSHExe())
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
_ = cmd.Run()
|
||||
|
||||
text := stderr.String()
|
||||
if text == "" || strings.Contains(text, "OpenSSL version mismatch.") {
|
||||
// https://bugzilla.mindrot.org/show_bug.cgi?id=3548
|
||||
return
|
||||
}
|
||||
ssh_options = make(map[string]string, 32)
|
||||
for {
|
||||
pos := strings.IndexByte(text, '[')
|
||||
if pos < 0 {
|
||||
break
|
||||
}
|
||||
num := 1
|
||||
epos := pos
|
||||
for num > 0 {
|
||||
epos++
|
||||
switch text[epos] {
|
||||
case '[':
|
||||
num += 1
|
||||
case ']':
|
||||
num -= 1
|
||||
}
|
||||
}
|
||||
q := text[pos+1 : epos]
|
||||
text = text[epos:]
|
||||
if len(q) < 2 || !strings.HasPrefix(q, "-") {
|
||||
continue
|
||||
}
|
||||
opt, desc, found := strings.Cut(q, " ")
|
||||
if found {
|
||||
ssh_options[opt[1:]] = desc
|
||||
} else {
|
||||
for _, ch := range opt[1:] {
|
||||
ssh_options[string(ch)] = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
})
|
||||
|
||||
func GetSSHCLI() (boolean_ssh_args *utils.Set[string], other_ssh_args *utils.Set[string]) {
|
||||
other_ssh_args, boolean_ssh_args = utils.NewSet[string](32), utils.NewSet[string](32)
|
||||
for k, v := range SSHOptions() {
|
||||
k = "-" + k
|
||||
if v == "" {
|
||||
boolean_ssh_args.Add(k)
|
||||
} else {
|
||||
other_ssh_args.Add(k)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func is_extra_arg(arg string, extra_args []string) string {
|
||||
for _, x := range extra_args {
|
||||
if arg == x || strings.HasPrefix(arg, x+"=") {
|
||||
return x
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type ErrInvalidSSHArgs struct {
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (self *ErrInvalidSSHArgs) Error() string {
|
||||
return self.Msg
|
||||
}
|
||||
|
||||
func PassthroughArgs() map[string]bool {
|
||||
return map[string]bool{"-N": true, "-n": true, "-f": true, "-G": true, "-T": true, "-V": true}
|
||||
}
|
||||
|
||||
func ParseSSHArgs(args []string, extra_args ...string) (ssh_args []string, server_args []string, passthrough bool, found_extra_args []string, err error) {
|
||||
if extra_args == nil {
|
||||
extra_args = []string{}
|
||||
}
|
||||
if len(args) == 0 {
|
||||
passthrough = true
|
||||
return
|
||||
}
|
||||
passthrough_args := PassthroughArgs()
|
||||
boolean_ssh_args, other_ssh_args := GetSSHCLI()
|
||||
ssh_args, server_args, found_extra_args = make([]string, 0, 16), make([]string, 0, 16), make([]string, 0, 16)
|
||||
expecting_option_val := false
|
||||
stop_option_processing := false
|
||||
expecting_extra_val := ""
|
||||
for _, argument := range args {
|
||||
if len(server_args) > 1 || stop_option_processing {
|
||||
server_args = append(server_args, argument)
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(argument, "-") && !expecting_option_val {
|
||||
if argument == "--" {
|
||||
stop_option_processing = true
|
||||
continue
|
||||
}
|
||||
if len(extra_args) > 0 {
|
||||
matching_ex := is_extra_arg(argument, extra_args)
|
||||
if matching_ex != "" {
|
||||
_, exval, found := strings.Cut(argument, "=")
|
||||
if found {
|
||||
found_extra_args = append(found_extra_args, matching_ex, exval)
|
||||
} else {
|
||||
expecting_extra_val = matching_ex
|
||||
expecting_option_val = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
// could be a multi-character option
|
||||
all_args := []rune(argument[1:])
|
||||
for i, ch := range all_args {
|
||||
arg := "-" + string(ch)
|
||||
if passthrough_args[arg] {
|
||||
passthrough = true
|
||||
}
|
||||
if boolean_ssh_args.Has(arg) {
|
||||
ssh_args = append(ssh_args, arg)
|
||||
continue
|
||||
}
|
||||
if other_ssh_args.Has(arg) {
|
||||
ssh_args = append(ssh_args, arg)
|
||||
if i+1 < len(all_args) {
|
||||
ssh_args = append(ssh_args, string(all_args[i+1:]))
|
||||
} else {
|
||||
expecting_option_val = true
|
||||
}
|
||||
break
|
||||
}
|
||||
err = &ErrInvalidSSHArgs{Msg: "unknown option -- " + arg[1:]}
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if expecting_option_val {
|
||||
if expecting_extra_val != "" {
|
||||
found_extra_args = append(found_extra_args, expecting_extra_val, argument)
|
||||
expecting_extra_val = ""
|
||||
} else {
|
||||
ssh_args = append(ssh_args, argument)
|
||||
}
|
||||
expecting_option_val = false
|
||||
continue
|
||||
}
|
||||
server_args = append(server_args, argument)
|
||||
}
|
||||
if len(server_args) == 0 && !passthrough {
|
||||
err = &ErrInvalidSSHArgs{Msg: ""}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type SSHConfig struct {
|
||||
RemoteCommand string
|
||||
}
|
||||
|
||||
// ReadSSHConfig Asynchronously read ssh configuration
|
||||
func ReadSSHConfig(ctx context.Context, ssh_args []string, hostname string) <-chan *SSHConfig {
|
||||
ch := make(chan *SSHConfig, 1)
|
||||
|
||||
go func() {
|
||||
defer close(ch)
|
||||
|
||||
cmd_args := []string{SSHExe(), "-G"}
|
||||
cmd_args = append(cmd_args, ssh_args...)
|
||||
cmd_args = append(cmd_args, hostname)
|
||||
cmd := exec.CommandContext(ctx, cmd_args[0], cmd_args[1:]...)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
text := stdout.String()
|
||||
scanner := bufio.NewScanner(strings.NewReader(text))
|
||||
|
||||
config := &SSHConfig{}
|
||||
for scanner.Scan() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
line := scanner.Text()
|
||||
i := strings.IndexByte(line, ' ')
|
||||
if i <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
key, val := line[:i], line[i+1:]
|
||||
switch key {
|
||||
case "remotecommand":
|
||||
if val != "none" {
|
||||
config.RemoteCommand = val
|
||||
}
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ch <- config:
|
||||
}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
type SSHVersion struct{ Major, Minor int }
|
||||
|
||||
func (self SSHVersion) SupportsAskpassRequire() bool {
|
||||
return self.Major > 8 || (self.Major == 8 && self.Minor >= 4)
|
||||
}
|
||||
|
||||
var GetSSHVersion = sync.OnceValue(func() SSHVersion {
|
||||
b, err := exec.Command(SSHExe(), "-V").CombinedOutput()
|
||||
if err != nil {
|
||||
return SSHVersion{}
|
||||
}
|
||||
m := regexp.MustCompile(`OpenSSH_(\d+).(\d+)`).FindSubmatch(b)
|
||||
if len(m) == 3 {
|
||||
maj, _ := strconv.Atoi(utils.UnsafeBytesToString(m[1]))
|
||||
min, _ := strconv.Atoi(utils.UnsafeBytesToString(m[2]))
|
||||
return SSHVersion{Major: maj, Minor: min}
|
||||
}
|
||||
return SSHVersion{}
|
||||
})
|
||||
|
||||
type KittyOpts struct {
|
||||
Term, Shell_integration string
|
||||
}
|
||||
|
||||
func read_relevant_kitty_opts(override_conf_path ...string) KittyOpts {
|
||||
ans := KittyOpts{Term: kitty.KittyConfigDefaults.Term, Shell_integration: kitty.KittyConfigDefaults.Shell_integration}
|
||||
handle_line := func(key, val string) error {
|
||||
switch key {
|
||||
case "term":
|
||||
ans.Term = strings.TrimSpace(val)
|
||||
case "shell_integration":
|
||||
ans.Shell_integration = strings.TrimSpace(val)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
config.ReadKittyConfig(handle_line, override_conf_path...)
|
||||
return ans
|
||||
}
|
||||
|
||||
var RelevantKittyOpts = sync.OnceValue(func() KittyOpts {
|
||||
return read_relevant_kitty_opts()
|
||||
})
|
||||
@@ -0,0 +1,398 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import traceback
|
||||
from collections.abc import Iterator, Sequence
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from kitty.types import run_once
|
||||
from kitty.utils import SSHConnectionData
|
||||
|
||||
|
||||
@run_once
|
||||
def ssh_options() -> dict[str, str]:
|
||||
try:
|
||||
p = subprocess.run(['ssh'], stderr=subprocess.PIPE, encoding='utf-8')
|
||||
raw = p.stderr or ''
|
||||
except FileNotFoundError:
|
||||
return {
|
||||
'4': '',
|
||||
'6': '',
|
||||
'A': '',
|
||||
'a': '',
|
||||
'C': '',
|
||||
'f': '',
|
||||
'G': '',
|
||||
'g': '',
|
||||
'K': '',
|
||||
'k': '',
|
||||
'M': '',
|
||||
'N': '',
|
||||
'n': '',
|
||||
'q': '',
|
||||
's': '',
|
||||
'T': '',
|
||||
't': '',
|
||||
'V': '',
|
||||
'v': '',
|
||||
'X': '',
|
||||
'x': '',
|
||||
'Y': '',
|
||||
'y': '',
|
||||
'B': 'bind_interface',
|
||||
'b': 'bind_address',
|
||||
'c': 'cipher_spec',
|
||||
'D': '[bind_address:]port',
|
||||
'E': 'log_file',
|
||||
'e': 'escape_char',
|
||||
'F': 'configfile',
|
||||
'I': 'pkcs11',
|
||||
'i': 'identity_file',
|
||||
'J': '[user@]host[:port]',
|
||||
'L': 'address',
|
||||
'l': 'login_name',
|
||||
'm': 'mac_spec',
|
||||
'O': 'ctl_cmd',
|
||||
'o': 'option',
|
||||
'p': 'port',
|
||||
'Q': 'query_option',
|
||||
'R': 'address',
|
||||
'S': 'ctl_path',
|
||||
'W': 'host:port',
|
||||
'w': 'local_tun[:remote_tun]',
|
||||
}
|
||||
|
||||
ans: dict[str, str] = {}
|
||||
pos = 0
|
||||
while True:
|
||||
pos = raw.find('[', pos) # ]
|
||||
if pos < 0:
|
||||
break
|
||||
num = 1
|
||||
epos = pos
|
||||
while num > 0:
|
||||
epos += 1
|
||||
if raw[epos] not in '[]':
|
||||
continue
|
||||
num += 1 if raw[epos] == '[' else -1 # ]
|
||||
q = raw[pos + 1 : epos]
|
||||
pos = epos
|
||||
if len(q) < 2 or q[0] != '-':
|
||||
continue
|
||||
if ' ' in q:
|
||||
opt, desc = q.split(' ', 1)
|
||||
ans[opt[1:]] = desc
|
||||
else:
|
||||
ans.update(dict.fromkeys(q[1:], ''))
|
||||
return ans
|
||||
|
||||
|
||||
def is_kitten_cmdline(q: Sequence[str]) -> bool:
|
||||
if not q:
|
||||
return False
|
||||
exe_name = os.path.basename(q[0]).lower()
|
||||
if exe_name == 'kitten' and q[1:2] == ['ssh']:
|
||||
return True
|
||||
if len(q) < 4:
|
||||
return False
|
||||
if exe_name != 'kitty':
|
||||
return False
|
||||
if q[1:3] == ['+kitten', 'ssh'] or q[1:4] == ['+', 'kitten', 'ssh']:
|
||||
return True
|
||||
return q[1:3] == ['+runpy', 'from kittens.runner import main; main()'] and len(q) >= 6 and q[5] == 'ssh'
|
||||
|
||||
|
||||
def patch_cmdline(key: str, val: str, argv: list[str]) -> None:
|
||||
for i, arg in enumerate(tuple(argv)):
|
||||
if arg.startswith(f'--kitten={key}='):
|
||||
argv[i] = f'--kitten={key}={val}'
|
||||
return
|
||||
elif i > 0 and argv[i - 1] == '--kitten' and (arg.startswith(f'{key}=') or arg.startswith(f'{key} ')):
|
||||
argv[i] = f'{key}={val}'
|
||||
return
|
||||
idx = argv.index('ssh')
|
||||
argv.insert(idx + 1, f'--kitten={key}={val}')
|
||||
|
||||
|
||||
def remove_env_var_from_cmdline(key: str, argv: list[str]) -> None:
|
||||
while True:
|
||||
for i, arg in enumerate(tuple(argv)):
|
||||
if arg.startswith(f'--kitten=env={key}='):
|
||||
del argv[i]
|
||||
break
|
||||
elif i > 0 and argv[i - 1] == '--kitten' and (arg.startswith(f'env={key}=') or arg.startswith(f'env {key}=')):
|
||||
del argv[i - 1 : i + 1]
|
||||
break
|
||||
else:
|
||||
break
|
||||
|
||||
|
||||
def set_single_env_var_in_cmdline(key: str, val: str, argv: list[str]) -> None:
|
||||
remove_env_var_from_cmdline(key, argv)
|
||||
idx = argv.index('ssh')
|
||||
argv.insert(idx + 1, f'--kitten=env={key}={val}')
|
||||
|
||||
|
||||
def set_cwd_in_cmdline(cwd: str, argv: list[str]) -> None:
|
||||
patch_cmdline('cwd', cwd, argv)
|
||||
|
||||
|
||||
def create_shared_memory(data: Any, prefix: str) -> str:
|
||||
import atexit
|
||||
import json
|
||||
|
||||
from kitty.fast_data_types import get_boss
|
||||
from kitty.shm import SharedMemory
|
||||
|
||||
db = json.dumps(data).encode('utf-8')
|
||||
with SharedMemory(size=len(db) + SharedMemory.num_bytes_for_size, prefix=prefix) as shm:
|
||||
shm.write_data_with_size(db)
|
||||
shm.flush()
|
||||
atexit.register(shm.close) # keeps shm alive till exit
|
||||
get_boss().atexit.shm_unlink(shm.name)
|
||||
return shm.name
|
||||
|
||||
|
||||
def read_data_from_shared_memory(shm_name: str) -> Any:
|
||||
import json
|
||||
|
||||
from kitty.shm import SharedMemory
|
||||
|
||||
with SharedMemory(shm_name, readonly=True) as shm:
|
||||
shm.unlink()
|
||||
shm.verify_owner_and_mode()
|
||||
return json.loads(shm.read_data_with_size())
|
||||
|
||||
|
||||
def get_ssh_data(msgb: memoryview, request_id: str) -> Iterator[bytes | memoryview]:
|
||||
# Unfortunately we cannot use EOF (\x04) to flush the kernel line buffer
|
||||
# because ssh with controlmasters mangles EOF replacing it with null bytes
|
||||
from base64 import standard_b64decode
|
||||
|
||||
yield b'\nKITTY_DATA_START\n' # to discard leading data
|
||||
try:
|
||||
msg = standard_b64decode(msgb).decode('utf-8')
|
||||
md = dict(x.split('=', 1) for x in msg.split(':'))
|
||||
pw = md['pw']
|
||||
pwfilename = md['pwfile']
|
||||
rq_id = md['id']
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
yield b'invalid ssh data request message\n'
|
||||
else:
|
||||
try:
|
||||
env_data = read_data_from_shared_memory(pwfilename)
|
||||
if pw != env_data['pw']:
|
||||
raise ValueError('Incorrect password')
|
||||
if rq_id != request_id:
|
||||
raise ValueError(f'Incorrect request id: {rq_id!r} expecting the KITTY_PID-KITTY_WINDOW_ID for the current kitty window')
|
||||
except Exception as e:
|
||||
traceback.print_exc()
|
||||
import re
|
||||
|
||||
msg = re.sub(r'[^a-zA-Z0-9 ]+', '_', str(e))
|
||||
yield f'{msg}\n'.encode()
|
||||
else:
|
||||
yield b'OK\n'
|
||||
encoded_data = memoryview(env_data['tarfile'].encode('ascii'))
|
||||
# macOS has a 255 byte limit on its input queue as per man stty.
|
||||
# Not clear if that applies to canonical mode input as well, but
|
||||
# better to be safe.
|
||||
line_sz = 254
|
||||
while encoded_data:
|
||||
yield encoded_data[:line_sz]
|
||||
yield b'\n'
|
||||
encoded_data = encoded_data[line_sz:]
|
||||
yield b'KITTY_DATA_END\n'
|
||||
|
||||
|
||||
def set_env_in_cmdline(env: dict[str, str], argv: list[str], clone: bool = True) -> None:
|
||||
from kitty.options.utils import DELETE_ENV_VAR
|
||||
|
||||
if clone:
|
||||
patch_cmdline('clone_env', create_shared_memory(env, 'ksse-'), argv)
|
||||
return
|
||||
idx = argv.index('ssh') - 1
|
||||
for i in range(idx, len(argv)):
|
||||
if argv[i] == '--kitten':
|
||||
idx = i + 1
|
||||
elif argv[i].startswith('--kitten='):
|
||||
idx = i
|
||||
env_dirs = []
|
||||
for k, v in env.items():
|
||||
if v is DELETE_ENV_VAR:
|
||||
x = f'--kitten=env={k}'
|
||||
else:
|
||||
x = f'--kitten=env={k}={v}'
|
||||
env_dirs.append(x)
|
||||
argv[idx + 1 : idx + 1] = env_dirs
|
||||
|
||||
|
||||
def get_ssh_cli() -> tuple[set[str], set[str]]:
|
||||
other_ssh_args: set[str] = set()
|
||||
boolean_ssh_args: set[str] = set()
|
||||
for k, v in ssh_options().items():
|
||||
k = f'-{k}'
|
||||
if v:
|
||||
other_ssh_args.add(k)
|
||||
else:
|
||||
boolean_ssh_args.add(k)
|
||||
return boolean_ssh_args, other_ssh_args
|
||||
|
||||
|
||||
def is_extra_arg(arg: str, extra_args: tuple[str, ...]) -> str:
|
||||
for x in extra_args:
|
||||
if arg == x or arg.startswith(f'{x}='):
|
||||
return x
|
||||
return ''
|
||||
|
||||
|
||||
passthrough_args = {f'-{x}' for x in 'NnfGT'}
|
||||
|
||||
|
||||
def set_server_args_in_cmdline(server_args: list[str], argv: list[str], extra_args: tuple[str, ...] = ('--kitten',), allocate_tty: bool = False) -> None:
|
||||
boolean_ssh_args, other_ssh_args = get_ssh_cli()
|
||||
ssh_args = []
|
||||
expecting_option_val = False
|
||||
found_extra_args: list[str] = []
|
||||
expecting_extra_val = ''
|
||||
ans = list(argv)
|
||||
found_ssh = False
|
||||
for i, argument in enumerate(argv):
|
||||
if not found_ssh:
|
||||
found_ssh = argument == 'ssh'
|
||||
continue
|
||||
if argument.startswith('-') and not expecting_option_val:
|
||||
if argument == '--':
|
||||
del ans[i + 2 :]
|
||||
if allocate_tty and ans[i - 1] != '-t':
|
||||
ans.insert(i, '-t')
|
||||
break
|
||||
if extra_args:
|
||||
matching_ex = is_extra_arg(argument, extra_args)
|
||||
if matching_ex:
|
||||
if '=' in argument:
|
||||
exval = argument.partition('=')[-1]
|
||||
found_extra_args.extend((matching_ex, exval))
|
||||
else:
|
||||
expecting_extra_val = matching_ex
|
||||
expecting_option_val = True
|
||||
continue
|
||||
# could be a multi-character option
|
||||
all_args = argument[1:]
|
||||
for i, arg in enumerate(all_args):
|
||||
arg = f'-{arg}'
|
||||
if arg in boolean_ssh_args:
|
||||
ssh_args.append(arg)
|
||||
continue
|
||||
if arg in other_ssh_args:
|
||||
ssh_args.append(arg)
|
||||
rest = all_args[i + 1 :]
|
||||
if rest:
|
||||
ssh_args.append(rest)
|
||||
else:
|
||||
expecting_option_val = True
|
||||
break
|
||||
raise KeyError(f'unknown option -- {arg[1:]}')
|
||||
continue
|
||||
if expecting_option_val:
|
||||
if expecting_extra_val:
|
||||
found_extra_args.extend((expecting_extra_val, argument))
|
||||
expecting_extra_val = ''
|
||||
else:
|
||||
ssh_args.append(argument)
|
||||
expecting_option_val = False
|
||||
continue
|
||||
del ans[i + 1 :]
|
||||
if allocate_tty and ans[i] != '-t':
|
||||
ans.insert(i, '-t')
|
||||
break
|
||||
argv[:] = ans + server_args
|
||||
|
||||
|
||||
def get_connection_data(args: list[str], cwd: str = '', extra_args: tuple[str, ...] = ()) -> SSHConnectionData | None:
|
||||
boolean_ssh_args, other_ssh_args = get_ssh_cli()
|
||||
port: int | None = None
|
||||
expecting_port = expecting_identity = False
|
||||
expecting_option_val = False
|
||||
expecting_hostname = False
|
||||
expecting_extra_val = ''
|
||||
host_name = identity_file = found_ssh = ''
|
||||
found_extra_args: list[tuple[str, str]] = []
|
||||
|
||||
for i, arg in enumerate(args):
|
||||
if not found_ssh:
|
||||
if os.path.basename(arg).lower() in ('ssh', 'ssh.exe'):
|
||||
found_ssh = arg
|
||||
continue
|
||||
if expecting_hostname:
|
||||
host_name = arg
|
||||
continue
|
||||
if arg.startswith('-') and not expecting_option_val:
|
||||
if arg in boolean_ssh_args:
|
||||
continue
|
||||
if arg == '--':
|
||||
expecting_hostname = True
|
||||
if arg.startswith('-p'):
|
||||
if arg[2:].isdigit():
|
||||
with suppress(Exception):
|
||||
port = int(arg[2:])
|
||||
continue
|
||||
elif arg == '-p':
|
||||
expecting_port = True
|
||||
elif arg.startswith('-i'):
|
||||
if arg == '-i':
|
||||
expecting_identity = True
|
||||
else:
|
||||
identity_file = arg[2:]
|
||||
continue
|
||||
if arg.startswith('--') and extra_args:
|
||||
matching_ex = is_extra_arg(arg, extra_args)
|
||||
if matching_ex:
|
||||
if '=' in arg:
|
||||
exval = arg.partition('=')[-1]
|
||||
found_extra_args.append((matching_ex, exval))
|
||||
continue
|
||||
expecting_extra_val = matching_ex
|
||||
|
||||
expecting_option_val = True
|
||||
continue
|
||||
|
||||
if expecting_option_val:
|
||||
if expecting_port:
|
||||
with suppress(Exception):
|
||||
port = int(arg)
|
||||
expecting_port = False
|
||||
elif expecting_identity:
|
||||
identity_file = arg
|
||||
elif expecting_extra_val:
|
||||
found_extra_args.append((expecting_extra_val, arg))
|
||||
expecting_extra_val = ''
|
||||
expecting_option_val = False
|
||||
continue
|
||||
|
||||
if not host_name:
|
||||
host_name = arg
|
||||
if not host_name:
|
||||
return None
|
||||
if host_name.startswith('ssh://'):
|
||||
from urllib.parse import urlparse
|
||||
|
||||
purl = urlparse(host_name)
|
||||
if purl.hostname:
|
||||
host_name = purl.hostname
|
||||
if purl.username:
|
||||
host_name = f'{purl.username}@{host_name}'
|
||||
if port is None and purl.port:
|
||||
port = purl.port
|
||||
if identity_file:
|
||||
if not os.path.isabs(identity_file):
|
||||
identity_file = os.path.expanduser(identity_file)
|
||||
if not os.path.isabs(identity_file):
|
||||
identity_file = os.path.normpath(os.path.join(cwd or os.getcwd(), identity_file))
|
||||
|
||||
return SSHConnectionData(found_ssh, host_name, port, identity_file, tuple(found_extra_args))
|
||||
@@ -0,0 +1,78 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestGetSSHOptions(t *testing.T) {
|
||||
m := SSHOptions()
|
||||
if m["w"] != "local_tun[:remote_tun]" {
|
||||
|
||||
cmd := exec.Command(SSHExe())
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
cmd.Run()
|
||||
t.Fatalf("Unexpected set of SSH options: %#v", m)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSSHArgs(t *testing.T) {
|
||||
split := func(x string) []string {
|
||||
ans, err := shlex.Split(x)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(ans) == 0 {
|
||||
ans = []string{}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
p := func(args, expected_ssh_args, expected_server_args, expected_extra_args string, expected_passthrough bool) {
|
||||
ssh_args, server_args, passthrough, extra_args, err := ParseSSHArgs(split(args), "--kitten")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check := func(a, b any) {
|
||||
diff := cmp.Diff(a, b)
|
||||
if diff != "" {
|
||||
t.Fatalf("Unexpected value for args: %#v\n%s", args, diff)
|
||||
}
|
||||
}
|
||||
check(split(expected_ssh_args), ssh_args)
|
||||
check(split(expected_server_args), server_args)
|
||||
check(split(expected_extra_args), extra_args)
|
||||
check(expected_passthrough, passthrough)
|
||||
}
|
||||
p(`localhost`, ``, `localhost`, ``, false)
|
||||
p(`-- localhost`, ``, `localhost`, ``, false)
|
||||
p(`-46p23 localhost sh -c "a b"`, `-4 -6 -p 23`, `localhost sh -c "a b"`, ``, false)
|
||||
p(`-46p23 -S/moose -W x:6 -- localhost sh -c "a b"`, `-4 -6 -p 23 -S /moose -W x:6`, `localhost sh -c "a b"`, ``, false)
|
||||
p(`--kitten=abc -np23 --kitten xyz host`, `-n -p 23`, `host`, `--kitten abc --kitten xyz`, true)
|
||||
p(`--kitten cwd=/tmp -p 2222 -i key host`, `-p 2222 -i key`, `host`, `--kitten cwd=/tmp`, false)
|
||||
}
|
||||
|
||||
func TestRelevantKittyOpts(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
path := filepath.Join(tdir, "kitty.conf")
|
||||
os.WriteFile(path, []byte("term XXX\nshell_integration changed\nterm abcd"), 0o600)
|
||||
rko := read_relevant_kitty_opts(path)
|
||||
if rko.Term != "abcd" {
|
||||
t.Fatalf("Unexpected TERM: %s", RelevantKittyOpts().Term)
|
||||
}
|
||||
if rko.Shell_integration != "changed" {
|
||||
t.Fatalf("Unexpected shell_integration: %s", RelevantKittyOpts().Shell_integration)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user