From c4fce20678b9b31e70f4789fd9f8b8ab5007aa5e Mon Sep 17 00:00:00 2001 From: Joachim Bauch Date: Tue, 30 Jan 2024 16:29:22 +0100 Subject: [PATCH] Add lock to entries to prevent concurrent modifications. --- dns_monitor.go | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/dns_monitor.go b/dns_monitor.go index 48f6231..3240682 100644 --- a/dns_monitor.go +++ b/dns_monitor.go @@ -55,11 +55,15 @@ type dnsMonitorEntry struct { hostname string hostIP net.IP + mu sync.Mutex ips []net.IP entries map[*DnsMonitorEntry]bool } func (e *dnsMonitorEntry) setIPs(ips []net.IP, fromIP bool) { + e.mu.Lock() + defer e.mu.Unlock() + empty := len(e.ips) == 0 if empty { // Simple case: initial lookup. @@ -113,6 +117,21 @@ func (e *dnsMonitorEntry) setIPs(ips []net.IP, fromIP bool) { } } +func (e *dnsMonitorEntry) addEntry(entry *DnsMonitorEntry) { + e.mu.Lock() + defer e.mu.Unlock() + + e.entries[entry] = true +} + +func (e *dnsMonitorEntry) removeEntry(entry *DnsMonitorEntry) bool { + e.mu.Lock() + defer e.mu.Unlock() + + delete(e.entries, entry) + return len(e.entries) == 0 +} + func (e *dnsMonitorEntry) runCallbacks(all []net.IP, add []net.IP, keep []net.IP, remove []net.IP) { for entry := range e.entries { entry.callback(entry, all, add, keep, remove) @@ -197,7 +216,7 @@ func (m *DnsMonitor) Add(target string, callback DnsMonitorCallback) (*DnsMonito m.hostnames[hostname] = entry } e.entry = entry - entry.entries[e] = true + entry.addEntry(e) m.cond.Signal() return e, nil } @@ -216,8 +235,7 @@ func (m *DnsMonitor) Remove(entry *DnsMonitorEntry) { } entry.entry = nil - delete(e.entries, entry) - if len(e.entries) == 0 { + if e.removeEntry(entry) { delete(m.hostnames, e.hostname) } }