Refactoring of FilterDNSResponse and DecideOnConnection

This commit is contained in:
Patrick Pacher
2020-04-21 09:55:49 +02:00
parent 8c5526a69b
commit f2e41a0d32
8 changed files with 480 additions and 331 deletions

View File

@@ -1,8 +1,12 @@
package intel
import (
"encoding/json"
"fmt"
"strings"
"github.com/miekg/dns"
"github.com/safing/portbase/log"
)
// ListMatch represents an entity that has been
@@ -45,7 +49,49 @@ func (br ListBlockReason) String() string {
// Context returns br wrapped into a map. It implements
// the endpoints.Reason interface.
func (br ListBlockReason) Context() interface{} {
return map[string]interface{}{
"filterlists": br,
}
return br
}
// MarshalJSON marshals the list block reason into a map
// prefixed with filterlists.
func (br ListBlockReason) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
// we convert to []ListMatch to avoid recursing
// here.
"filterlists": []ListMatch(br),
})
}
// ToRRs returns a set of dns TXT records that describe the
// block reason.
func (br ListBlockReason) ToRRs() []dns.RR {
rrs := make([]dns.RR, 0, len(br))
for _, lm := range br {
blockedBy, err := dns.NewRR(fmt.Sprintf(
"%s-blockedBy. 0 IN TXT %q",
strings.TrimRight(lm.Entity, "."),
strings.Join(lm.ActiveLists, ","),
))
if err == nil {
rrs = append(rrs, blockedBy)
} else {
log.Errorf("intel: failed to create TXT RR for block reason: %s", err)
}
if len(lm.InactiveLists) > 0 {
wouldBeBlockedBy, err := dns.NewRR(fmt.Sprintf(
"%s-wouldBeBlockedBy. 0 IN TXT %q",
strings.TrimRight(lm.Entity, "."),
strings.Join(lm.ActiveLists, ","),
))
if err == nil {
rrs = append(rrs, wouldBeBlockedBy)
} else {
log.Errorf("intel: failed to create TXT RR for block reason: %s", err)
}
}
}
return rrs
}

View File

@@ -101,10 +101,10 @@ func (e *Entity) ResetLists() {
// list right now so we could be more efficient by keeping
// the other lists around.
// FIXME
//e.Lists = nil
//e.ListsMap = nil
e.BlockedByLists = nil
e.BlockedEntities = nil
e.ListOccurences = nil
e.domainListLoaded = false
e.ipListLoaded = false
e.countryListLoaded = false
@@ -421,15 +421,12 @@ func (e *Entity) getIPLists() {
})
}
// LoadLists searches all filterlists for all occurences of
// LoadLists searches all filterlists for all occurrences of
// this entity.
func (e *Entity) LoadLists() bool {
e.getLists()
if e.ListOccurences == nil {
return false
}
return true
return e.ListOccurences != nil
}
// MatchLists matches the entities lists against a slice
@@ -450,6 +447,7 @@ func (e *Entity) MatchLists(lists []string) bool {
}
makeDistinct(e.BlockedByLists)
makeDistinct(e.BlockedEntities)
return len(e.BlockedByLists) > 0
}
@@ -503,7 +501,7 @@ func mergeStringList(a, b []string) []string {
func makeDistinct(slice []string) []string {
m := make(map[string]struct{}, len(slice))
var result []string
result := make([]string, 0, len(slice))
for _, v := range slice {
if _, ok := m[v]; ok {