Make KnownHostsFile safe for concurrent use
This commit is contained in:
parent
846fa2ac41
commit
e687a05170
17
tofu.go
17
tofu.go
@ -25,18 +25,25 @@ type KnownHosts map[string]Fingerprint
|
|||||||
|
|
||||||
// KnownHostsFile represents a list of known hosts optionally loaded from a file.
|
// KnownHostsFile represents a list of known hosts optionally loaded from a file.
|
||||||
// The zero value for KnownHostsFile represents an empty list ready to use.
|
// The zero value for KnownHostsFile represents an empty list ready to use.
|
||||||
|
//
|
||||||
|
// KnownHostsFile is safe for concurrent use by multiple goroutines.
|
||||||
type KnownHostsFile struct {
|
type KnownHostsFile struct {
|
||||||
KnownHosts
|
KnownHosts
|
||||||
out io.Writer
|
out io.Writer
|
||||||
|
mu sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetOutput sets the output to which new known hosts will be written to.
|
// SetOutput sets the output to which new known hosts will be written to.
|
||||||
func (k *KnownHostsFile) SetOutput(w io.Writer) {
|
func (k *KnownHostsFile) SetOutput(w io.Writer) {
|
||||||
|
k.mu.Lock()
|
||||||
|
defer k.mu.Unlock()
|
||||||
k.out = w
|
k.out = w
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add adds a known host to the list of known hosts.
|
// Add adds a known host to the list of known hosts.
|
||||||
func (k *KnownHostsFile) Add(hostname string, fingerprint Fingerprint) {
|
func (k *KnownHostsFile) Add(hostname string, fingerprint Fingerprint) {
|
||||||
|
k.mu.Lock()
|
||||||
|
defer k.mu.Unlock()
|
||||||
if k.KnownHosts == nil {
|
if k.KnownHosts == nil {
|
||||||
k.KnownHosts = KnownHosts{}
|
k.KnownHosts = KnownHosts{}
|
||||||
}
|
}
|
||||||