/
config.go
268 lines (230 loc) · 5.38 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// Copyright 2020, Shulhan <ms@kilabit.info>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package config provide the ssh_config(5) parser and getter.
package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
const (
envSSHAuthSock = `SSH_AUTH_SOCK`
)
const (
keyHost = "host"
keyMatch = "match"
)
var (
errMultipleEqual = errors.New("multiple '=' character")
)
// Config contains mapping of host's patterns and its options from SSH
// configuration file.
type Config struct {
envs map[string]string
// dir store the path to the "config" directory.
dir string
// workDir store the current working directory.
workDir string
homeDir string
sections []*Section
// others Config, as result of [Config.Merge].
others []*Config
}
// newConfig create new SSH Config instance from file.
func newConfig(file string) (cfg *Config, err error) {
cfg = &Config{}
// If file is empty, the dir is set to ".".
cfg.dir, err = filepath.Abs(filepath.Dir(file))
if err != nil {
return nil, err
}
cfg.workDir, err = os.Getwd()
if err != nil {
return nil, err
}
cfg.homeDir, err = os.UserHomeDir()
if err != nil {
return nil, err
}
return cfg, nil
}
// Load SSH configuration from file.
func Load(file string) (cfg *Config, err error) {
if len(file) == 0 {
return nil, nil
}
var (
logp = "Load"
section *Section
)
cfg, err = newConfig(file)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", logp, file, err)
}
cfg.loadEnvironments()
var p *parser
p, err = newParser(cfg)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", logp, file, err)
}
var lines []string
lines, err = p.load("", file)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", logp, file, err)
}
var (
line string
x int
)
for x, line = range lines {
if line[0] == '#' {
continue
}
key, value, err := parseKeyValue(line)
if err != nil {
return nil, fmt.Errorf("%s %s line %d: %w", logp, file, x, err)
}
switch key {
case keyHost:
if section != nil {
cfg.sections = append(cfg.sections, section)
section = nil
}
section = newSectionHost(cfg, value)
case keyMatch:
if section != nil {
cfg.sections = append(cfg.sections, section)
section = nil
}
section, err = newSectionMatch(cfg, value)
if err != nil {
return nil, fmt.Errorf("%s %s line %d: %w", logp, file, x+1, err)
}
default:
if section == nil {
// No "Host" or "Match" define yet.
continue
}
err = section.Set(key, value)
if err != nil {
return nil, fmt.Errorf("%s %s line %d: %w", logp, file, x+1, err)
}
}
}
if section != nil {
cfg.sections = append(cfg.sections, section)
section = nil
}
return cfg, nil
}
// Get the Host or Match configuration that match with the host name "s".
// If no Host or Match found, it return non-nil Section with default values.
func (cfg *Config) Get(host string) (section *Section) {
section = NewSection(cfg, host)
var hostMatch *Section
for _, hostMatch = range cfg.sections {
if hostMatch.isMatch(host) {
section.merge(hostMatch)
}
}
var (
other *Config
subsec *Section
)
for _, other = range cfg.others {
subsec = other.Get(host)
section.merge(subsec)
}
section.setDefaults()
if host != `` && section.Field[KeyHostname] == `` {
section.Set(KeyHostname, host)
}
return section
}
// Merge other Config as part of this Config.
// This function can be used to combine multiple SSH config files into one.
//
// For example after the user's "~/.ssh/config" has been loaded, we can
// merge it with system "/etc/ssh/ssh_config".
// During [Config.Get] the top Config will be evaluated first, and then the
// other Config is evaluated in order of Merge-d.
func (cfg *Config) Merge(other *Config) {
if other == nil {
return
}
cfg.others = append(cfg.others, other)
}
// loadEnvironments get all environments variables and store it in the map for
// future use by SendEnv.
func (cfg *Config) loadEnvironments() {
envs := os.Environ()
for _, env := range envs {
kv := strings.SplitN(env, "=", 2)
if len(kv) == 0 {
cfg.envs[kv[0]] = kv[1]
}
}
}
func parseBool(key, val string) (out bool, err error) {
switch val {
case ValueNo:
return false, nil
case ValueYes:
return true, nil
}
return false, fmt.Errorf("%s: invalid value %q", key, val)
}
// parseKeyValue from single line.
//
// ssh_config(5):
//
// Configuration options may be separated by whitespace or optional
// whitespace and exactly one `='; the latter format is useful to avoid
// the need to quote whitespace ...
func parseKeyValue(line string) (key, value string, err error) {
var (
hasSeparator bool
nequal int
)
for y, r := range line {
if r == ' ' || r == '=' {
if r == '=' {
nequal++
if nequal > 1 {
return key, value, errMultipleEqual
}
}
if hasSeparator {
continue
}
key = line[:y]
hasSeparator = true
continue
}
if !hasSeparator {
continue
}
value = line[y:]
break
}
key = strings.ToLower(key)
value = strings.Trim(value, `"`)
return key, value, nil
}
// patternToRegex convert the Host and Match pattern string into regex.
func patternToRegex(in string) (out string) {
sr := make([]rune, 0, len(in))
for _, r := range in {
switch r {
case '*', '?':
sr = append(sr, '.')
case '.':
sr = append(sr, '\\')
}
sr = append(sr, r)
}
return string(sr)
}