| 1 | // Package ssh_config provides tools for manipulating SSH config files. |
| 2 | // |
| 3 | // Importantly, this parser attempts to preserve comments in a given file, so |
| 4 | // you can manipulate a `ssh_config` file from a program, if your heart desires. |
| 5 | // |
| 6 | // The Get() and GetStrict() functions will attempt to read values from |
| 7 | // $HOME/.ssh/config, falling back to /etc/ssh/ssh_config. The first argument is |
| 8 | // the host name to match on ("example.com"), and the second argument is the key |
| 9 | // you want to retrieve ("Port"). The keywords are case insensitive. |
| 10 | // |
| 11 | // port := ssh_config.Get("myhost", "Port") |
| 12 | // |
| 13 | // You can also manipulate an SSH config file and then print it or write it back |
| 14 | // to disk. |
| 15 | // |
| 16 | // f, _ := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config")) |
| 17 | // cfg, _ := ssh_config.Decode(f) |
| 18 | // for _, host := range cfg.Hosts { |
| 19 | // fmt.Println("patterns:", host.Patterns) |
| 20 | // for _, node := range host.Nodes { |
| 21 | // fmt.Println(node.String()) |
| 22 | // } |
| 23 | // } |
| 24 | // |
| 25 | // // Write the cfg back to disk: |
| 26 | // fmt.Println(cfg.String()) |
| 27 | // |
| 28 | // BUG: the Match directive is currently unsupported; parsing a config with |
| 29 | // a Match directive will trigger an error. |
| 30 | package ssh_config |
| 31 | |
| 32 | import ( |
| 33 | "bytes" |
| 34 | "errors" |
| 35 | "fmt" |
| 36 | "io" |
| 37 | "os" |
| 38 | osuser "os/user" |
| 39 | "path/filepath" |
| 40 | "regexp" |
| 41 | "runtime" |
| 42 | "strings" |
| 43 | "sync" |
| 44 | ) |
| 45 | |
| 46 | const version = "1.2" |
| 47 | |
| 48 | var _ = version |
| 49 | |
| 50 | type configFinder func() string |
| 51 | |
| 52 | // UserSettings checks ~/.ssh and /etc/ssh for configuration files. The config |
| 53 | // files are parsed and cached the first time Get() or GetStrict() is called. |
| 54 | type UserSettings struct { |
| 55 | IgnoreErrors bool |
| 56 | IgnoreMatchDirective bool |
| 57 | customConfig *Config |
| 58 | customConfigFinder configFinder |
| 59 | systemConfig *Config |
| 60 | systemConfigFinder configFinder |
| 61 | userConfig *Config |
| 62 | userConfigFinder configFinder |
| 63 | loadConfigs sync.Once |
| 64 | onceErr error |
| 65 | } |
| 66 | |
| 67 | func homedir() string { |
| 68 | user, err := osuser.Current() |
| 69 | if err == nil { |
| 70 | return user.HomeDir |
| 71 | } else { |
| 72 | return os.Getenv("HOME") |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | func userConfigFinder() string { |
| 77 | return filepath.Join(homedir(), ".ssh", "config") |
| 78 | } |
| 79 | |
| 80 | // DefaultUserSettings is the default UserSettings and is used by Get and |
| 81 | // GetStrict. It checks both $HOME/.ssh/config and /etc/ssh/ssh_config for keys, |
| 82 | // and it will return parse errors (if any) instead of swallowing them. |
| 83 | var DefaultUserSettings = &UserSettings{ |
| 84 | IgnoreErrors: false, |
| 85 | IgnoreMatchDirective: false, |
| 86 | systemConfigFinder: systemConfigFinder, |
| 87 | userConfigFinder: userConfigFinder, |
| 88 | } |
| 89 | |
| 90 | func systemConfigFinder() string { |
| 91 | return filepath.Join("/", "etc", "ssh", "ssh_config") |
| 92 | } |
| 93 | |
| 94 | func findVal(c *Config, alias, key string) (string, error) { |
| 95 | if c == nil { |
| 96 | return "", nil |
| 97 | } |
| 98 | val, err := c.Get(alias, key) |
| 99 | if err != nil || val == "" { |
| 100 | return "", err |
| 101 | } |
| 102 | if err := validate(key, val); err != nil { |
| 103 | return "", err |
| 104 | } |
| 105 | return val, nil |
| 106 | } |
| 107 | |
| 108 | func findAll(c *Config, alias, key string) ([]string, error) { |
| 109 | if c == nil { |
| 110 | return nil, nil |
| 111 | } |
| 112 | return c.GetAll(alias, key) |
| 113 | } |
| 114 | |
| 115 | // Get finds the first value for key within a declaration that matches the |
| 116 | // alias. Get returns the empty string if no value was found, or if IgnoreErrors |
| 117 | // is false and we could not parse the configuration file. Use GetStrict to |
| 118 | // disambiguate the latter cases. |
| 119 | // |
| 120 | // The match for key is case insensitive. |
| 121 | // |
| 122 | // Get is a wrapper around DefaultUserSettings.Get. |
| 123 | func Get(alias, key string) string { |
| 124 | return DefaultUserSettings.Get(alias, key) |
| 125 | } |
| 126 | |
| 127 | // GetAll retrieves zero or more directives for key for the given alias. GetAll |
| 128 | // returns nil if no value was found, or if IgnoreErrors is false and we could |
| 129 | // not parse the configuration file. Use GetAllStrict to disambiguate the |
| 130 | // latter cases. |
| 131 | // |
| 132 | // In most cases you want to use Get or GetStrict, which returns a single value. |
| 133 | // However, a subset of ssh configuration values (IdentityFile, for example) |
| 134 | // allow you to specify multiple directives. |
| 135 | // |
| 136 | // The match for key is case insensitive. |
| 137 | // |
| 138 | // GetAll is a wrapper around DefaultUserSettings.GetAll. |
| 139 | func GetAll(alias, key string) []string { |
| 140 | return DefaultUserSettings.GetAll(alias, key) |
| 141 | } |
| 142 | |
| 143 | // GetStrict finds the first value for key within a declaration that matches the |
| 144 | // alias. If key has a default value and no matching configuration is found, the |
| 145 | // default will be returned. For more information on default values and the way |
| 146 | // patterns are matched, see the manpage for ssh_config. |
| 147 | // |
| 148 | // The returned error will be non-nil if and only if a user's configuration file |
| 149 | // or the system configuration file could not be parsed, and u.IgnoreErrors is |
| 150 | // false. |
| 151 | // |
| 152 | // GetStrict is a wrapper around DefaultUserSettings.GetStrict. |
| 153 | func GetStrict(alias, key string) (string, error) { |
| 154 | return DefaultUserSettings.GetStrict(alias, key) |
| 155 | } |
| 156 | |
| 157 | // GetAllStrict retrieves zero or more directives for key for the given alias. |
| 158 | // |
| 159 | // In most cases you want to use Get or GetStrict, which returns a single value. |
| 160 | // However, a subset of ssh configuration values (IdentityFile, for example) |
| 161 | // allow you to specify multiple directives. |
| 162 | // |
| 163 | // The returned error will be non-nil if and only if a user's configuration file |
| 164 | // or the system configuration file could not be parsed, and u.IgnoreErrors is |
| 165 | // false. |
| 166 | // |
| 167 | // GetAllStrict is a wrapper around DefaultUserSettings.GetAllStrict. |
| 168 | func GetAllStrict(alias, key string) ([]string, error) { |
| 169 | return DefaultUserSettings.GetAllStrict(alias, key) |
| 170 | } |
| 171 | |
| 172 | // Get finds the first value for key within a declaration that matches the |
| 173 | // alias. Get returns the empty string if no value was found, or if IgnoreErrors |
| 174 | // is false and we could not parse the configuration file. Use GetStrict to |
| 175 | // disambiguate the latter cases. |
| 176 | // |
| 177 | // The match for key is case insensitive. |
| 178 | func (u *UserSettings) Get(alias, key string) string { |
| 179 | val, err := u.GetStrict(alias, key) |
| 180 | if err != nil { |
| 181 | return "" |
| 182 | } |
| 183 | return val |
| 184 | } |
| 185 | |
| 186 | // GetAll retrieves zero or more directives for key for the given alias. GetAll |
| 187 | // returns nil if no value was found, or if IgnoreErrors is false and we could |
| 188 | // not parse the configuration file. Use GetStrict to disambiguate the latter |
| 189 | // cases. |
| 190 | // |
| 191 | // The match for key is case insensitive. |
| 192 | func (u *UserSettings) GetAll(alias, key string) []string { |
| 193 | val, _ := u.GetAllStrict(alias, key) |
| 194 | return val |
| 195 | } |
| 196 | |
| 197 | // GetStrict finds the first value for key within a declaration that matches the |
| 198 | // alias. If key has a default value and no matching configuration is found, the |
| 199 | // default will be returned. For more information on default values and the way |
| 200 | // patterns are matched, see the manpage for ssh_config. |
| 201 | // |
| 202 | // error will be non-nil if and only if a user's configuration file or the |
| 203 | // system configuration file could not be parsed, and u.IgnoreErrors is false. |
| 204 | func (u *UserSettings) GetStrict(alias, key string) (string, error) { |
| 205 | u.doLoadConfigs() |
| 206 | //lint:ignore S1002 I prefer it this way |
| 207 | if u.onceErr != nil && u.IgnoreErrors == false { |
| 208 | return "", u.onceErr |
| 209 | } |
| 210 | // TODO this is getting repetitive |
| 211 | if u.customConfig != nil { |
| 212 | val, err := findVal(u.customConfig, alias, key) |
| 213 | if err != nil || val != "" { |
| 214 | return val, err |
| 215 | } |
| 216 | } |
| 217 | val, err := findVal(u.userConfig, alias, key) |
| 218 | if err != nil || val != "" { |
| 219 | return val, err |
| 220 | } |
| 221 | val2, err2 := findVal(u.systemConfig, alias, key) |
| 222 | if err2 != nil || val2 != "" { |
| 223 | return val2, err2 |
| 224 | } |
| 225 | return Default(key), nil |
| 226 | } |
| 227 | |
| 228 | // GetAllStrict retrieves zero or more directives for key for the given alias. |
| 229 | // If key has a default value and no matching configuration is found, the |
| 230 | // default will be returned. For more information on default values and the way |
| 231 | // patterns are matched, see the manpage for ssh_config. |
| 232 | // |
| 233 | // The returned error will be non-nil if and only if a user's configuration file |
| 234 | // or the system configuration file could not be parsed, and u.IgnoreErrors is |
| 235 | // false. |
| 236 | func (u *UserSettings) GetAllStrict(alias, key string) ([]string, error) { |
| 237 | u.doLoadConfigs() |
| 238 | //lint:ignore S1002 I prefer it this way |
| 239 | if u.onceErr != nil && u.IgnoreErrors == false { |
| 240 | return nil, u.onceErr |
| 241 | } |
| 242 | if u.customConfig != nil { |
| 243 | val, err := findAll(u.customConfig, alias, key) |
| 244 | if err != nil || val != nil { |
| 245 | return val, err |
| 246 | } |
| 247 | } |
| 248 | val, err := findAll(u.userConfig, alias, key) |
| 249 | if err != nil || val != nil { |
| 250 | return val, err |
| 251 | } |
| 252 | val2, err2 := findAll(u.systemConfig, alias, key) |
| 253 | if err2 != nil || val2 != nil { |
| 254 | return val2, err2 |
| 255 | } |
| 256 | // TODO: IdentityFile has multiple default values that we should return. |
| 257 | if def := Default(key); def != "" { |
| 258 | return []string{def}, nil |
| 259 | } |
| 260 | return []string{}, nil |
| 261 | } |
| 262 | |
| 263 | // ConfigFinder will invoke f to try to find a ssh config file in a custom |
| 264 | // location on disk, instead of in /etc/ssh or $HOME/.ssh. f should return the |
| 265 | // name of a file containing SSH configuration. |
| 266 | // |
| 267 | // ConfigFinder must be invoked before any calls to Get or GetStrict and panics |
| 268 | // if f is nil. Most users should not need to use this function. |
| 269 | func (u *UserSettings) ConfigFinder(f func() string) { |
| 270 | if f == nil { |
| 271 | panic("cannot call ConfigFinder with nil function") |
| 272 | } |
| 273 | u.customConfigFinder = f |
| 274 | } |
| 275 | |
| 276 | func (u *UserSettings) doLoadConfigs() { |
| 277 | u.loadConfigs.Do(func() { |
| 278 | var filename string |
| 279 | var err error |
| 280 | if u.customConfigFinder != nil { |
| 281 | filename = u.customConfigFinder() |
| 282 | u.customConfig, err = parseFile(filename, u.IgnoreMatchDirective) |
| 283 | // IsNotExist should be returned because a user specified this |
| 284 | // function - not existing likely means they made an error |
| 285 | // We should also respect the ignore flag |
| 286 | if err != nil && !u.IgnoreErrors { |
| 287 | u.onceErr = err |
| 288 | } |
| 289 | return |
| 290 | } |
| 291 | if u.userConfigFinder == nil { |
| 292 | filename = userConfigFinder() |
| 293 | } else { |
| 294 | filename = u.userConfigFinder() |
| 295 | } |
| 296 | u.userConfig, err = parseFile(filename, u.IgnoreMatchDirective) |
| 297 | //lint:ignore S1002 I prefer it this way |
| 298 | if err != nil && os.IsNotExist(err) == false { |
| 299 | u.onceErr = err |
| 300 | return |
| 301 | } |
| 302 | if u.systemConfigFinder == nil { |
| 303 | filename = systemConfigFinder() |
| 304 | } else { |
| 305 | filename = u.systemConfigFinder() |
| 306 | } |
| 307 | u.systemConfig, err = parseFile(filename, u.IgnoreMatchDirective) |
| 308 | //lint:ignore S1002 I prefer it this way |
| 309 | if err != nil && os.IsNotExist(err) == false { |
| 310 | u.onceErr = err |
| 311 | return |
| 312 | } |
| 313 | }, |
| 314 | ) |
| 315 | } |
| 316 | |
| 317 | func parseFile(filename string, ignoreMatchDirective bool) (*Config, error) { |
| 318 | return parseWithDepth(filename, ignoreMatchDirective, 0) |
| 319 | } |
| 320 | |
| 321 | func parseWithDepth(filename string, ignoreMatchDirective bool, depth uint8) (*Config, error) { |
| 322 | b, err := os.ReadFile(filename) |
| 323 | if err != nil { |
| 324 | return nil, err |
| 325 | } |
| 326 | return decodeBytes(b, isSystem(filename), ignoreMatchDirective, depth) |
| 327 | } |
| 328 | |
| 329 | func isSystem(filename string) bool { |
| 330 | // TODO: not sure this is the best way to detect a system repo |
| 331 | return strings.HasPrefix(filepath.Clean(filename), "/etc/ssh") |
| 332 | } |
| 333 | |
| 334 | // Decode reads r into a Config, or returns an error if r could not be parsed as |
| 335 | // an SSH config file. |
| 336 | func Decode(r io.Reader, ignoreMatchDirective bool) (*Config, error) { |
| 337 | b, err := io.ReadAll(r) |
| 338 | if err != nil { |
| 339 | return nil, err |
| 340 | } |
| 341 | return decodeBytes(b, false, ignoreMatchDirective, 0) |
| 342 | } |
| 343 | |
| 344 | // DecodeBytes reads b into a Config, or returns an error if r could not be |
| 345 | // parsed as an SSH config file. |
| 346 | func DecodeBytes(b []byte, ignoreMatchDirective bool) (*Config, error) { |
| 347 | return decodeBytes(b, false, ignoreMatchDirective, 0) |
| 348 | } |
| 349 | |
| 350 | func decodeBytes(b []byte, system, ignoreMatchDirective bool, depth uint8) (c *Config, err error) { |
| 351 | defer func() { |
| 352 | if r := recover(); r != nil { |
| 353 | if _, ok := r.(runtime.Error); ok { |
| 354 | panic(r) |
| 355 | } |
| 356 | if e, ok := r.(error); ok && e == ErrDepthExceeded { |
| 357 | err = e |
| 358 | return |
| 359 | } |
| 360 | err = errors.New(r.(string)) |
| 361 | } |
| 362 | }() |
| 363 | |
| 364 | c = parseSSH(lexSSH(b), system, ignoreMatchDirective, depth) |
| 365 | return c, err |
| 366 | } |
| 367 | |
| 368 | // Config represents an SSH config file. |
| 369 | type Config struct { |
| 370 | // A list of hosts to match against. The file begins with an implicit |
| 371 | // "Host *" declaration matching all hosts. |
| 372 | Hosts []*Host |
| 373 | depth uint8 |
| 374 | position Position |
| 375 | ignoreMatchDirective bool |
| 376 | } |
| 377 | |
| 378 | // Get finds the first value in the configuration that matches the alias and |
| 379 | // contains key. Get returns the empty string if no value was found, or if the |
| 380 | // Config contains an invalid conditional Include value. |
| 381 | // |
| 382 | // The match for key is case insensitive. |
| 383 | func (c *Config) Get(alias, key string) (string, error) { |
| 384 | lowerKey := strings.ToLower(key) |
| 385 | for _, host := range c.Hosts { |
| 386 | if !host.Matches(alias) { |
| 387 | continue |
| 388 | } |
| 389 | for _, node := range host.Nodes { |
| 390 | switch t := node.(type) { |
| 391 | case *Empty: |
| 392 | continue |
| 393 | case *KV: |
| 394 | // "keys are case insensitive" per the spec |
| 395 | lkey := strings.ToLower(t.Key) |
| 396 | if lkey == "match" && !c.ignoreMatchDirective { |
| 397 | panic("can't handle Match directives") |
| 398 | } |
| 399 | if lkey == lowerKey { |
| 400 | return t.Value, nil |
| 401 | } |
| 402 | case *Include: |
| 403 | val := t.Get(alias, key) |
| 404 | if val != "" { |
| 405 | return val, nil |
| 406 | } |
| 407 | default: |
| 408 | return "", fmt.Errorf("unknown Node type %v", t) |
| 409 | } |
| 410 | } |
| 411 | } |
| 412 | return "", nil |
| 413 | } |
| 414 | |
| 415 | // GetAll returns all values in the configuration that match the alias and |
| 416 | // contains key, or nil if none are present. |
| 417 | func (c *Config) GetAll(alias, key string) ([]string, error) { |
| 418 | lowerKey := strings.ToLower(key) |
| 419 | all := []string(nil) |
| 420 | for _, host := range c.Hosts { |
| 421 | if !host.Matches(alias) { |
| 422 | continue |
| 423 | } |
| 424 | for _, node := range host.Nodes { |
| 425 | switch t := node.(type) { |
| 426 | case *Empty: |
| 427 | continue |
| 428 | case *KV: |
| 429 | // "keys are case insensitive" per the spec |
| 430 | lkey := strings.ToLower(t.Key) |
| 431 | if lkey == "match" { |
| 432 | panic("can't handle Match directives") |
| 433 | } |
| 434 | if lkey == lowerKey { |
| 435 | all = append(all, t.Value) |
| 436 | } |
| 437 | case *Include: |
| 438 | val, _ := t.GetAll(alias, key) |
| 439 | if len(val) > 0 { |
| 440 | all = append(all, val...) |
| 441 | } |
| 442 | default: |
| 443 | return nil, fmt.Errorf("unknown Node type %v", t) |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | return all, nil |
| 449 | } |
| 450 | |
| 451 | // String returns a string representation of the Config file. |
| 452 | func (c Config) String() string { |
| 453 | return marshal(c).String() |
| 454 | } |
| 455 | |
| 456 | func (c Config) MarshalText() ([]byte, error) { |
| 457 | return marshal(c).Bytes(), nil |
| 458 | } |
| 459 | |
| 460 | func marshal(c Config) *bytes.Buffer { |
| 461 | var buf bytes.Buffer |
| 462 | for i := range c.Hosts { |
| 463 | buf.WriteString(c.Hosts[i].String()) |
| 464 | } |
| 465 | return &buf |
| 466 | } |
| 467 | |
| 468 | // Pattern is a pattern in a Host declaration. Patterns are read-only values; |
| 469 | // create a new one with NewPattern(). |
| 470 | type Pattern struct { |
| 471 | str string // Its appearance in the file, not the value that gets compiled. |
| 472 | regex *regexp.Regexp |
| 473 | not bool // True if this is a negated match |
| 474 | } |
| 475 | |
| 476 | // String prints the string representation of the pattern. |
| 477 | func (p Pattern) String() string { |
| 478 | return p.str |
| 479 | } |
| 480 | |
| 481 | // Copied from regexp.go with * and ? removed. |
| 482 | var specialBytes = []byte(`\.+()|[]{}^$`) |
| 483 | |
| 484 | func special(b byte) bool { |
| 485 | return bytes.IndexByte(specialBytes, b) >= 0 |
| 486 | } |
| 487 | |
| 488 | // NewPattern creates a new Pattern for matching hosts. NewPattern("*") creates |
| 489 | // a Pattern that matches all hosts. |
| 490 | // |
| 491 | // From the manpage, a pattern consists of zero or more non-whitespace |
| 492 | // characters, `*' (a wildcard that matches zero or more characters), or `?' (a |
| 493 | // wildcard that matches exactly one character). For example, to specify a set |
| 494 | // of declarations for any host in the ".co.uk" set of domains, the following |
| 495 | // pattern could be used: |
| 496 | // |
| 497 | // Host *.co.uk |
| 498 | // |
| 499 | // The following pattern would match any host in the 192.168.0.[0-9] network range: |
| 500 | // |
| 501 | // Host 192.168.0.? |
| 502 | func NewPattern(s string) (*Pattern, error) { |
| 503 | if s == "" { |
| 504 | return nil, errors.New("ssh_config: empty pattern") |
| 505 | } |
| 506 | negated := false |
| 507 | if s[0] == '!' { |
| 508 | negated = true |
| 509 | s = s[1:] |
| 510 | } |
| 511 | var buf bytes.Buffer |
| 512 | buf.WriteByte('^') |
| 513 | for i := 0; i < len(s); i++ { |
| 514 | // A byte loop is correct because all metacharacters are ASCII. |
| 515 | switch b := s[i]; b { |
| 516 | case '*': |
| 517 | buf.WriteString(".*") |
| 518 | case '?': |
| 519 | buf.WriteString(".?") |
| 520 | default: |
| 521 | // borrowing from QuoteMeta here. |
| 522 | if special(b) { |
| 523 | buf.WriteByte('\\') |
| 524 | } |
| 525 | buf.WriteByte(b) |
| 526 | } |
| 527 | } |
| 528 | buf.WriteByte('$') |
| 529 | r, err := regexp.Compile(buf.String()) |
| 530 | if err != nil { |
| 531 | return nil, err |
| 532 | } |
| 533 | return &Pattern{str: s, regex: r, not: negated}, nil |
| 534 | } |
| 535 | |
| 536 | // Host describes a Host directive and the keywords that follow it. |
| 537 | type Host struct { |
| 538 | // A list of host patterns that should match this host. |
| 539 | Patterns []*Pattern |
| 540 | // A Node is either a key/value pair or a comment line. |
| 541 | Nodes []Node |
| 542 | // EOLComment is the comment (if any) terminating the Host line. |
| 543 | EOLComment string |
| 544 | // Whitespace if any between the Host declaration and a trailing comment. |
| 545 | spaceBeforeComment string |
| 546 | |
| 547 | hasEquals bool |
| 548 | leadingSpace int // TODO: handle spaces vs tabs here. |
| 549 | // The file starts with an implicit "Host *" declaration. |
| 550 | implicit bool |
| 551 | } |
| 552 | |
| 553 | // Matches returns true if the Host matches for the given alias. For |
| 554 | // a description of the rules that provide a match, see the manpage for |
| 555 | // ssh_config. |
| 556 | func (h *Host) Matches(alias string) bool { |
| 557 | found := false |
| 558 | for i := range h.Patterns { |
| 559 | if h.Patterns[i].regex.MatchString(alias) { |
| 560 | if h.Patterns[i].not { |
| 561 | // Negated match. "A pattern entry may be negated by prefixing |
| 562 | // it with an exclamation mark (`!'). If a negated entry is |
| 563 | // matched, then the Host entry is ignored, regardless of |
| 564 | // whether any other patterns on the line match. Negated matches |
| 565 | // are therefore useful to provide exceptions for wildcard |
| 566 | // matches." |
| 567 | return false |
| 568 | } |
| 569 | found = true |
| 570 | } |
| 571 | } |
| 572 | return found |
| 573 | } |
| 574 | |
| 575 | // String prints h as it would appear in a config file. Minor tweaks may be |
| 576 | // present in the whitespace in the printed file. |
| 577 | func (h *Host) String() string { |
| 578 | var buf strings.Builder |
| 579 | //lint:ignore S1002 I prefer to write it this way |
| 580 | if h.implicit == false { |
| 581 | buf.WriteString(strings.Repeat(" ", int(h.leadingSpace))) |
| 582 | buf.WriteString("Host") |
| 583 | if h.hasEquals { |
| 584 | buf.WriteString(" = ") |
| 585 | } else { |
| 586 | buf.WriteString(" ") |
| 587 | } |
| 588 | for i, pat := range h.Patterns { |
| 589 | buf.WriteString(pat.String()) |
| 590 | if i < len(h.Patterns)-1 { |
| 591 | buf.WriteString(" ") |
| 592 | } |
| 593 | } |
| 594 | buf.WriteString(h.spaceBeforeComment) |
| 595 | if h.EOLComment != "" { |
| 596 | buf.WriteByte('#') |
| 597 | buf.WriteString(h.EOLComment) |
| 598 | } |
| 599 | buf.WriteByte('\n') |
| 600 | } |
| 601 | for i := range h.Nodes { |
| 602 | buf.WriteString(h.Nodes[i].String()) |
| 603 | buf.WriteByte('\n') |
| 604 | } |
| 605 | return buf.String() |
| 606 | } |
| 607 | |
| 608 | // Node represents a line in a Config. |
| 609 | type Node interface { |
| 610 | Pos() Position |
| 611 | String() string |
| 612 | } |
| 613 | |
| 614 | // KV is a line in the config file that contains a key, a value, and possibly |
| 615 | // a comment. |
| 616 | type KV struct { |
| 617 | Key string |
| 618 | Value string |
| 619 | // Whitespace after the value but before any comment |
| 620 | spaceAfterValue string |
| 621 | Comment string |
| 622 | hasEquals bool |
| 623 | leadingSpace int // Space before the key. TODO handle spaces vs tabs. |
| 624 | position Position |
| 625 | } |
| 626 | |
| 627 | // Pos returns k's Position. |
| 628 | func (k *KV) Pos() Position { |
| 629 | return k.position |
| 630 | } |
| 631 | |
| 632 | // String prints k as it was parsed in the config file. |
| 633 | func (k *KV) String() string { |
| 634 | if k == nil { |
| 635 | return "" |
| 636 | } |
| 637 | equals := " " |
| 638 | if k.hasEquals { |
| 639 | equals = " = " |
| 640 | } |
| 641 | line := strings.Repeat(" ", int(k.leadingSpace)) + k.Key + equals + k.Value + k.spaceAfterValue |
| 642 | if k.Comment != "" { |
| 643 | line += "#" + k.Comment |
| 644 | } |
| 645 | return line |
| 646 | } |
| 647 | |
| 648 | // Empty is a line in the config file that contains only whitespace or comments. |
| 649 | type Empty struct { |
| 650 | Comment string |
| 651 | leadingSpace int // TODO handle spaces vs tabs. |
| 652 | position Position |
| 653 | } |
| 654 | |
| 655 | // Pos returns e's Position. |
| 656 | func (e *Empty) Pos() Position { |
| 657 | return e.position |
| 658 | } |
| 659 | |
| 660 | // String prints e as it was parsed in the config file. |
| 661 | func (e *Empty) String() string { |
| 662 | if e == nil { |
| 663 | return "" |
| 664 | } |
| 665 | if e.Comment == "" { |
| 666 | return "" |
| 667 | } |
| 668 | return fmt.Sprintf("%s#%s", strings.Repeat(" ", int(e.leadingSpace)), e.Comment) |
| 669 | } |
| 670 | |
| 671 | // Include holds the result of an Include directive, including the config files |
| 672 | // that have been parsed as part of that directive. At most 5 levels of Include |
| 673 | // statements will be parsed. |
| 674 | type Include struct { |
| 675 | // Comment is the contents of any comment at the end of the Include |
| 676 | // statement. |
| 677 | Comment string |
| 678 | // an include directive can include several different files, and wildcards |
| 679 | directives []string |
| 680 | |
| 681 | mu sync.Mutex |
| 682 | // 1:1 mapping between matches and keys in files array; matches preserves |
| 683 | // ordering |
| 684 | matches []string |
| 685 | // actual filenames are listed here |
| 686 | files map[string]*Config |
| 687 | leadingSpace int |
| 688 | position Position |
| 689 | depth uint8 |
| 690 | hasEquals bool |
| 691 | } |
| 692 | |
| 693 | const maxRecurseDepth = 5 |
| 694 | |
| 695 | // ErrDepthExceeded is returned if too many Include directives are parsed. |
| 696 | // Usually this indicates a recursive loop (an Include directive pointing to the |
| 697 | // file it contains). |
| 698 | var ErrDepthExceeded = errors.New("ssh_config: max recurse depth exceeded") |
| 699 | |
| 700 | func removeDups(arr []string) []string { |
| 701 | // Use map to record duplicates as we find them. |
| 702 | encountered := make(map[string]bool, len(arr)) |
| 703 | result := make([]string, 0) |
| 704 | |
| 705 | for v := range arr { |
| 706 | //lint:ignore S1002 I prefer it this way |
| 707 | if encountered[arr[v]] == false { |
| 708 | encountered[arr[v]] = true |
| 709 | result = append(result, arr[v]) |
| 710 | } |
| 711 | } |
| 712 | return result |
| 713 | } |
| 714 | |
| 715 | // NewInclude creates a new Include with a list of file globs to include. |
| 716 | // Configuration files are parsed greedily (e.g. as soon as this function runs). |
| 717 | // Any error encountered while parsing nested configuration files will be |
| 718 | // returned. |
| 719 | func NewInclude(directives []string, hasEquals bool, pos Position, comment string, system, ignoreMatchDirective bool, depth uint8, |
| 720 | ) (*Include, error) { |
| 721 | if depth > maxRecurseDepth { |
| 722 | return nil, ErrDepthExceeded |
| 723 | } |
| 724 | inc := &Include{ |
| 725 | Comment: comment, |
| 726 | directives: directives, |
| 727 | files: make(map[string]*Config), |
| 728 | position: pos, |
| 729 | leadingSpace: pos.Col - 1, |
| 730 | depth: depth, |
| 731 | hasEquals: hasEquals, |
| 732 | } |
| 733 | // no need for inc.mu.Lock() since nothing else can access this inc |
| 734 | matches := make([]string, 0) |
| 735 | for i := range directives { |
| 736 | var path string |
| 737 | if filepath.IsAbs(directives[i]) { |
| 738 | path = directives[i] |
| 739 | } else if system { |
| 740 | path = filepath.Join("/etc/ssh", directives[i]) |
| 741 | } else { |
| 742 | path = filepath.Join(homedir(), ".ssh", directives[i]) |
| 743 | } |
| 744 | theseMatches, err := filepath.Glob(path) |
| 745 | if err != nil { |
| 746 | return nil, err |
| 747 | } |
| 748 | matches = append(matches, theseMatches...) |
| 749 | } |
| 750 | matches = removeDups(matches) |
| 751 | inc.matches = matches |
| 752 | for i := range matches { |
| 753 | config, err := parseWithDepth(matches[i], ignoreMatchDirective, depth) |
| 754 | if err != nil { |
| 755 | return nil, err |
| 756 | } |
| 757 | inc.files[matches[i]] = config |
| 758 | } |
| 759 | return inc, nil |
| 760 | } |
| 761 | |
| 762 | // Pos returns the position of the Include directive in the larger file. |
| 763 | func (i *Include) Pos() Position { |
| 764 | return i.position |
| 765 | } |
| 766 | |
| 767 | // Get finds the first value in the Include statement matching the alias and the |
| 768 | // given key. |
| 769 | func (inc *Include) Get(alias, key string) string { |
| 770 | inc.mu.Lock() |
| 771 | defer inc.mu.Unlock() |
| 772 | // TODO: we search files in any order which is not correct |
| 773 | for i := range inc.matches { |
| 774 | cfg := inc.files[inc.matches[i]] |
| 775 | if cfg == nil { |
| 776 | panic("nil cfg") |
| 777 | } |
| 778 | val, err := cfg.Get(alias, key) |
| 779 | if err == nil && val != "" { |
| 780 | return val |
| 781 | } |
| 782 | } |
| 783 | return "" |
| 784 | } |
| 785 | |
| 786 | // GetAll finds all values in the Include statement matching the alias and the |
| 787 | // given key. |
| 788 | func (inc *Include) GetAll(alias, key string) ([]string, error) { |
| 789 | inc.mu.Lock() |
| 790 | defer inc.mu.Unlock() |
| 791 | var vals []string |
| 792 | |
| 793 | // TODO: we search files in any order which is not correct |
| 794 | for i := range inc.matches { |
| 795 | cfg := inc.files[inc.matches[i]] |
| 796 | if cfg == nil { |
| 797 | panic("nil cfg") |
| 798 | } |
| 799 | val, err := cfg.GetAll(alias, key) |
| 800 | if err == nil && len(val) != 0 { |
| 801 | // In theory if SupportsMultiple was false for this key we could |
| 802 | // stop looking here. But the caller has asked us to find all |
| 803 | // instances of the keyword (and could use Get() if they wanted) so |
| 804 | // let's keep looking. |
| 805 | vals = append(vals, val...) |
| 806 | } |
| 807 | } |
| 808 | return vals, nil |
| 809 | } |
| 810 | |
| 811 | // String prints out a string representation of this Include directive. Note |
| 812 | // included Config files are not printed as part of this representation. |
| 813 | func (inc *Include) String() string { |
| 814 | equals := " " |
| 815 | if inc.hasEquals { |
| 816 | equals = " = " |
| 817 | } |
| 818 | line := fmt.Sprintf("%sInclude%s%s", strings.Repeat(" ", int(inc.leadingSpace)), equals, strings.Join(inc.directives, " ")) |
| 819 | if inc.Comment != "" { |
| 820 | line += " #" + inc.Comment |
| 821 | } |
| 822 | return line |
| 823 | } |
| 824 | |
| 825 | var matchAll *Pattern |
| 826 | |
| 827 | func init() { |
| 828 | var err error |
| 829 | matchAll, err = NewPattern("*") |
| 830 | if err != nil { |
| 831 | panic(err) |
| 832 | } |
| 833 | } |
| 834 | |
| 835 | func newConfig() *Config { |
| 836 | return &Config{ |
| 837 | Hosts: []*Host{ |
| 838 | &Host{ |
| 839 | implicit: true, |
| 840 | Patterns: []*Pattern{matchAll}, |
| 841 | Nodes: make([]Node, 0), |
| 842 | }, |
| 843 | }, |
| 844 | depth: 0, |
| 845 | } |
| 846 | } |