vcom/internal/ssh/sshconfig/flatten.go

200 lines
5.3 KiB
Go
Raw Normal View History

package sshconfig
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
)
// hashMark stands in for a literal '#' inside a value while the flattened
// config goes through kevinburke/ssh_config, whose lexer treats every '#' as
// the start of a comment. OpenSSH only starts a comment at a '#' that begins
// a word outside quotes (N-P1-5: "IdentityFile ~/.ssh/key#1").
const hashMark = ""
const maxIncludeDepth = 5
// flattener turns an ssh_config file and everything it Includes into a single
// text that kevinburke/ssh_config can parse without touching the disk:
// - comments are stripped with OpenSSH rules, literal '#' is escaped;
// - Include is inlined (relative to ~/.ssh), restoring the enclosing Host
// context after the included text, as OpenSSH does;
// - Host patterns are lowercased (OpenSSH matches host names
// case-insensitively; the alias is lowercased too before lookup);
// - "Match all" and "Match host a,b" become Host blocks; other Match
// criteria (user, exec, canonical, ...) become a block that never
// matches, instead of failing the whole file.
type flattener struct {
home string
b strings.Builder
explicit []string // non-wildcard Host names, in file order
seen map[string]bool
warnings []string
}
func (f *flattener) warnf(format string, args ...any) {
f.warnings = append(f.warnings, fmt.Sprintf(format, args...))
}
func (f *flattener) file(path string, depth int) error {
data, err := os.ReadFile(path)
if err != nil {
return err
}
f.text(path, string(data), depth)
return nil
}
func (f *flattener) text(path, data string, depth int) {
context := "" // current Host line written to the output, "" = implicit Host *
for n, raw := range strings.Split(data, "\n") {
line := strings.TrimSpace(stripComment(strings.TrimRight(raw, "\r")))
if line == "" {
continue
}
kw, rest := splitKeyword(line)
switch strings.ToLower(kw) {
case "host":
pats := splitArgs(rest)
for i, p := range pats {
pats[i] = strings.ToLower(p)
if !strings.ContainsAny(p, "*?!") && !f.seen[pats[i]] {
f.seen[pats[i]] = true
f.explicit = append(f.explicit, p)
}
}
if len(pats) == 0 {
f.warnf("%s:%d: Host without patterns", path, n+1)
pats = []string{"!*"}
}
context = "Host " + strings.Join(pats, " ")
f.b.WriteString(context + "\n")
case "match":
context = f.match(path, n+1, rest)
f.b.WriteString(context + "\n")
case "include":
if depth >= maxIncludeDepth {
f.warnf("%s:%d: Include nested too deep, ignored", path, n+1)
continue
}
for _, pat := range splitArgs(rest) {
for _, m := range f.glob(pat) {
if err := f.file(m, depth+1); err != nil {
f.warnf("%s:%d: Include %s: %v", path, n+1, m, err)
}
}
}
// The included text may have opened its own Host blocks; the rest
// of this file continues in the block that contained the Include.
if context == "" {
f.b.WriteString("Host *\n")
} else {
f.b.WriteString(context + "\n")
}
default:
f.b.WriteString(kw + " " + strings.ReplaceAll(rest, "#", hashMark) + "\n")
}
}
}
func (f *flattener) match(path string, line int, rest string) string {
fields := splitArgs(rest)
if len(fields) == 1 && strings.EqualFold(fields[0], "all") {
return "Host *"
}
if len(fields) == 2 && (strings.EqualFold(fields[0], "host") || strings.EqualFold(fields[0], "originalhost")) {
var pats []string
for _, p := range strings.Split(fields[1], ",") {
if p != "" {
pats = append(pats, strings.ToLower(p))
}
}
if len(pats) > 0 {
return "Host " + strings.Join(pats, " ")
}
}
f.warnf("%s:%d: unsupported Match %q, block ignored", path, line, rest)
return "Host !*"
}
func (f *flattener) glob(pat string) []string {
p := expandTilde(pat, f.home)
if !filepath.IsAbs(p) {
p = filepath.Join(f.home, ".ssh", p)
}
ms, err := filepath.Glob(p)
if err != nil {
f.warnf("Include %s: %v", pat, err)
return nil
}
sort.Strings(ms)
return ms
}
// stripComment removes a trailing comment: a '#' that starts a word and is
// not inside double quotes (OpenSSH argv_split rules).
func stripComment(s string) string {
inQuote := false
for i := 0; i < len(s); i++ {
switch c := s[i]; {
case c == '"':
inQuote = !inQuote
case c == '#' && !inQuote && (i == 0 || s[i-1] == ' ' || s[i-1] == '\t'):
return s[:i]
}
}
return s
}
// splitKeyword splits "Key value", "Key=value" and "Key = value".
func splitKeyword(line string) (kw, rest string) {
i := strings.IndexAny(line, " \t=")
if i < 0 {
return line, ""
}
kw, rest = line[:i], strings.TrimLeft(line[i:], " \t")
if strings.HasPrefix(rest, "=") {
rest = strings.TrimLeft(rest[1:], " \t")
}
return kw, rest
}
// splitArgs splits on whitespace, honouring double quotes.
func splitArgs(s string) []string {
var out []string
var cur strings.Builder
inQuote, have := false, false
for _, r := range s {
switch {
case r == '"':
inQuote = !inQuote
have = true
case (r == ' ' || r == '\t') && !inQuote:
if have {
out = append(out, cur.String())
cur.Reset()
have = false
}
default:
cur.WriteRune(r)
have = true
}
}
if have {
out = append(out, cur.String())
}
return out
}
func expandTilde(p, home string) string {
if p == "~" {
return home
}
if strings.HasPrefix(p, "~/") {
return filepath.Join(home, p[2:])
}
return p
}