2021-03-22 16:46:36 +03:00
|
|
|
package aghnet
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/AdguardTeam/golibs/log"
|
|
|
|
)
|
|
|
|
|
|
|
|
// DefaultRefreshIvl is the default period of time between refreshing cached
|
|
|
|
// addresses.
|
|
|
|
// const DefaultRefreshIvl = 5 * time.Minute
|
|
|
|
|
|
|
|
// HostGenFunc is the signature for functions generating fake hostnames. The
|
|
|
|
// implementation must be safe for concurrent use.
|
|
|
|
type HostGenFunc func() (host string)
|
|
|
|
|
|
|
|
// SystemResolvers helps to work with local resolvers' addresses provided by OS.
|
|
|
|
type SystemResolvers interface {
|
2021-06-01 14:28:34 +03:00
|
|
|
// Get returns the slice of local resolvers' addresses. It should be
|
|
|
|
// safe for concurrent use.
|
2021-03-22 16:46:36 +03:00
|
|
|
Get() (rs []string)
|
2021-03-31 15:00:47 +03:00
|
|
|
// refresh refreshes the local resolvers' addresses cache. It should be
|
2021-03-22 16:46:36 +03:00
|
|
|
// safe for concurrent use.
|
2021-03-31 15:00:47 +03:00
|
|
|
refresh() (err error)
|
2021-03-22 16:46:36 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// refreshWithTicker refreshes the cache of sr after each tick form tickCh.
|
|
|
|
func refreshWithTicker(sr SystemResolvers, tickCh <-chan time.Time) {
|
2021-05-24 17:28:11 +03:00
|
|
|
defer log.OnPanic("systemResolvers")
|
2021-03-22 16:46:36 +03:00
|
|
|
|
|
|
|
// TODO(e.burkov): Implement a functionality to stop ticker.
|
|
|
|
for range tickCh {
|
2021-03-31 15:00:47 +03:00
|
|
|
err := sr.refresh()
|
2021-03-22 16:46:36 +03:00
|
|
|
if err != nil {
|
|
|
|
log.Error("systemResolvers: error in refreshing goroutine: %s", err)
|
|
|
|
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Debug("systemResolvers: local addresses cache is refreshed")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewSystemResolvers returns a SystemResolvers with the cache refresh rate
|
|
|
|
// defined by refreshIvl. It disables auto-resfreshing if refreshIvl is 0. If
|
|
|
|
// nil is passed for hostGenFunc, the default generator will be used.
|
|
|
|
func NewSystemResolvers(
|
|
|
|
refreshIvl time.Duration,
|
|
|
|
hostGenFunc HostGenFunc,
|
|
|
|
) (sr SystemResolvers, err error) {
|
|
|
|
sr = newSystemResolvers(refreshIvl, hostGenFunc)
|
|
|
|
|
|
|
|
// Fill cache.
|
2021-03-31 15:00:47 +03:00
|
|
|
err = sr.refresh()
|
2021-03-22 16:46:36 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if refreshIvl > 0 {
|
|
|
|
ticker := time.NewTicker(refreshIvl)
|
|
|
|
|
|
|
|
go refreshWithTicker(sr, ticker.C)
|
|
|
|
}
|
|
|
|
|
|
|
|
return sr, nil
|
|
|
|
}
|