From e2a625a92e782fd0dd351afc9ce05a32451f832e Mon Sep 17 00:00:00 2001 From: bloved Date: Thu, 16 Sep 2021 09:40:03 +0200 Subject: [PATCH] if the DNS response Rcode contains an error the cache expires after just 10 seconds. this should limit the cache in case of temporary upstream DNS errors. --- 02.cache.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/02.cache.go b/02.cache.go index 7c4e1b5..ae40d26 100644 --- a/02.cache.go +++ b/02.cache.go @@ -13,7 +13,7 @@ import ( type cacheItem struct { Query []byte - Date time.Time + ExpireDate time.Time } //DomainCache stores a domain name inside the cache @@ -28,7 +28,17 @@ func DomainCache(s string, resp *dns.Msg) { if err != nil { fmt.Println("Problems packing the response: ", err.Error()) } - domain2cache.Date = time.Now() + if resp.Rcode == dns.RcodeSuccess{ + // on success stores response normally + domain2cache.ExpireDate = time.Now().Add((time.Duration(ZabovCacheTTL) * time.Hour)) + }else + { + // on failure stores response for a very short time + if ZabovDebug { + fmt.Println("DomainCache(): DNS error Rcode: ", resp.Rcode, s, "cache time reduced to 10 seconds...") + } + domain2cache.ExpireDate = time.Now().Add((time.Duration(10) * time.Second)) + } err = enc.Encode(domain2cache) @@ -65,7 +75,7 @@ func GetDomainFromCache(s string) *dns.Msg { conf, errDB = MyZabovCDB.Get([]byte(s), nil) if errDB != nil { - fmt.Println("Cant READ DB :" , errDB.Error() ) + fmt.Println("Cant READ DB:" , errDB.Error() ) return nil } @@ -77,7 +87,10 @@ func GetDomainFromCache(s string) *dns.Msg { return nil } - if time.Since(record.Date) > (time.Duration(ZabovCacheTTL) * time.Hour) { + if time.Now().After(record.ExpireDate) { + if ZabovDebug { + fmt.Println("GetDomainFromCache(): entry expired:", s) + } return nil }