Skip to content

Commit

Permalink
Use a global lock instead
Browse files Browse the repository at this point in the history
  • Loading branch information
Alfonso Acosta committed Jun 23, 2017
1 parent 22a31fc commit 9778be7
Showing 1 changed file with 12 additions and 24 deletions.
36 changes: 12 additions & 24 deletions probe/endpoint/dns_snooper_linux_amd64.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,15 @@ const (

// DNSSnooper is a snopper of DNS queries
type DNSSnooper struct {
stop chan struct{}
pcapHandle *pcap.Handle
stop chan struct{}
pcapHandle *pcap.Handle
// gcache is goroutine-safe, but the
// values cached values aren't
reverseDNSMutex sync.RWMutex
reverseDNSCache gcache.Cache
decodingErrorCounts map[string]uint64 // for limiting
}

type domainSet struct {
// Not worth using a RMutex since we don't expect a lot of contention
// and they are considerably larger (8 bytes vs 24 bytes), which would
// bloat the cache
mutex *sync.Mutex
domains map[string]struct{}
}

// NewDNSSnooper creates a new snooper of DNS queries
func NewDNSSnooper() (*DNSSnooper, error) {
pcapHandle, err := newPcapHandle()
Expand Down Expand Up @@ -110,13 +105,11 @@ func (s *DNSSnooper) CachedNamesForIP(ip string) []string {
if err != nil {
return result
}

domainSet := domains.(domainSet)
domainSet.mutex.Lock()
for domain := range domainSet.domains {
s.reverseDNSMutex.RLock()
for domain := range domains.(map[string]struct{}) {
result = append(result, domain)
}
domainSet.mutex.Unlock()
s.reverseDNSMutex.RUnlock()

return result
}
Expand Down Expand Up @@ -281,17 +274,12 @@ func (s *DNSSnooper) processDNSMessage(dns *layers.DNS) {
log.Debugf("DNSSnooper: caught DNS lookup: %s -> %v", newDomain, ips)
for ip := range ips {
if existingDomains, err := s.reverseDNSCache.Get(ip); err != nil {
singleton := domainSet{
domains: map[string]struct{}{newDomain: {}},
mutex: &sync.Mutex{},
}
s.reverseDNSCache.Set(ip, singleton)
s.reverseDNSCache.Set(ip, map[string]struct{}{newDomain: {}})
} else {
// TODO: Be smarter about the expiration of entries with pre-existing associated domains
domainSet := existingDomains.(domainSet)
domainSet.mutex.Lock()
domainSet.domains[newDomain] = struct{}{}
domainSet.mutex.Unlock()
s.reverseDNSMutex.Lock()
existingDomains.(map[string]struct{})[newDomain] = struct{}{}
s.reverseDNSMutex.Unlock()
}
}
}

0 comments on commit 9778be7

Please sign in to comment.