2018-11-28 10:14:54 -07:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2019-03-15 06:49:10 -07:00
|
|
|
"hash/crc32"
|
2018-11-28 10:14:54 -07:00
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"regexp"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2018-11-30 03:24:42 -07:00
|
|
|
"github.com/AdguardTeam/AdGuardHome/dnsfilter"
|
2019-03-06 02:20:34 -07:00
|
|
|
"github.com/AdguardTeam/golibs/file"
|
2019-02-25 06:44:22 -07:00
|
|
|
"github.com/AdguardTeam/golibs/log"
|
2018-11-28 10:14:54 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
nextFilterID = time.Now().Unix() // semi-stable way to generate an unique ID
|
|
|
|
filterTitleRegexp = regexp.MustCompile(`^! Title: +(.*)$`)
|
|
|
|
)
|
|
|
|
|
|
|
|
// field ordering is important -- yaml fields will mirror ordering from here
|
|
|
|
type filter struct {
|
|
|
|
Enabled bool `json:"enabled"`
|
|
|
|
URL string `json:"url"`
|
|
|
|
Name string `json:"name" yaml:"name"`
|
|
|
|
RulesCount int `json:"rulesCount" yaml:"-"`
|
2019-02-10 11:44:16 -07:00
|
|
|
LastUpdated time.Time `json:"lastUpdated,omitempty" yaml:"-"`
|
2019-03-15 06:49:10 -07:00
|
|
|
checksum uint32 // checksum of the file data
|
2018-11-28 10:14:54 -07:00
|
|
|
|
2018-11-30 03:24:42 -07:00
|
|
|
dnsfilter.Filter `yaml:",inline"`
|
2018-11-28 10:14:54 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Creates a helper object for working with the user rules
|
|
|
|
func userFilter() filter {
|
|
|
|
return filter{
|
|
|
|
// User filter always has constant ID=0
|
|
|
|
Enabled: true,
|
2018-11-30 03:24:42 -07:00
|
|
|
Filter: dnsfilter.Filter{
|
2018-11-28 10:14:54 -07:00
|
|
|
Rules: config.UserRules,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-18 04:12:04 -07:00
|
|
|
// Enable or disable a filter
|
|
|
|
func filterEnable(url string, enable bool) bool {
|
|
|
|
r := false
|
|
|
|
config.Lock()
|
|
|
|
for i := range config.Filters {
|
|
|
|
filter := &config.Filters[i] // otherwise we will be operating on a copy
|
|
|
|
if filter.URL == url {
|
|
|
|
filter.Enabled = enable
|
|
|
|
if enable {
|
|
|
|
e := filter.load()
|
|
|
|
if e != nil {
|
|
|
|
// This isn't a fatal error,
|
|
|
|
// because it may occur when someone removes the file from disk.
|
|
|
|
// In this case the periodic update task will try to download the file.
|
|
|
|
filter.LastUpdated = time.Time{}
|
|
|
|
log.Tracef("%s filter load: %v", url, e)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
filter.unload()
|
|
|
|
}
|
|
|
|
r = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
config.Unlock()
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
2019-03-18 04:41:38 -07:00
|
|
|
// Return TRUE if a filter with this URL exists
|
|
|
|
func filterExists(url string) bool {
|
|
|
|
r := false
|
|
|
|
config.RLock()
|
|
|
|
for i := range config.Filters {
|
|
|
|
if config.Filters[i].URL == url {
|
|
|
|
r = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
config.RUnlock()
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add a filter
|
|
|
|
// Return FALSE if a filter with this URL exists
|
|
|
|
func filterAdd(f filter) bool {
|
|
|
|
config.Lock()
|
|
|
|
|
|
|
|
// Check for duplicates
|
|
|
|
for i := range config.Filters {
|
|
|
|
if config.Filters[i].URL == f.URL {
|
|
|
|
config.Unlock()
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
config.Filters = append(config.Filters, f)
|
|
|
|
config.Unlock()
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2019-03-15 09:41:45 -07:00
|
|
|
// Load filters from the disk
|
|
|
|
// And if any filter has zero ID, assign a new one
|
|
|
|
func loadFilters() {
|
|
|
|
for i := range config.Filters {
|
|
|
|
filter := &config.Filters[i] // otherwise we're operating on a copy
|
|
|
|
if filter.ID == 0 {
|
|
|
|
filter.ID = assignUniqueFilterID()
|
|
|
|
}
|
2019-03-18 02:52:34 -07:00
|
|
|
|
|
|
|
if !filter.Enabled {
|
|
|
|
// No need to load a filter that is not enabled
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-03-15 09:41:45 -07:00
|
|
|
err := filter.load()
|
|
|
|
if err != nil {
|
|
|
|
// This is okay for the first start, the filter will be loaded later
|
|
|
|
log.Debug("Couldn't load filter %d contents due to %s", filter.ID, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-28 10:14:54 -07:00
|
|
|
func deduplicateFilters() {
|
|
|
|
// Deduplicate filters
|
|
|
|
i := 0 // output index, used for deletion later
|
|
|
|
urls := map[string]bool{}
|
|
|
|
for _, filter := range config.Filters {
|
|
|
|
if _, ok := urls[filter.URL]; !ok {
|
|
|
|
// we didn't see it before, keep it
|
|
|
|
urls[filter.URL] = true // remember the URL
|
|
|
|
config.Filters[i] = filter
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// all entries we want to keep are at front, delete the rest
|
|
|
|
config.Filters = config.Filters[:i]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set the next filter ID to max(filter.ID) + 1
|
|
|
|
func updateUniqueFilterID(filters []filter) {
|
|
|
|
for _, filter := range filters {
|
|
|
|
if nextFilterID < filter.ID {
|
|
|
|
nextFilterID = filter.ID + 1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func assignUniqueFilterID() int64 {
|
|
|
|
value := nextFilterID
|
2019-01-24 10:11:01 -07:00
|
|
|
nextFilterID++
|
2018-11-28 10:14:54 -07:00
|
|
|
return value
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sets up a timer that will be checking for filters updates periodically
|
|
|
|
func periodicallyRefreshFilters() {
|
|
|
|
for range time.Tick(time.Minute) {
|
2019-01-24 10:11:01 -07:00
|
|
|
refreshFiltersIfNecessary(false)
|
2018-11-28 10:14:54 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Checks filters updates if necessary
|
|
|
|
// If force is true, it ignores the filter.LastUpdated field value
|
2019-01-24 10:11:01 -07:00
|
|
|
func refreshFiltersIfNecessary(force bool) int {
|
2018-11-28 10:14:54 -07:00
|
|
|
config.Lock()
|
|
|
|
|
|
|
|
// fetch URLs
|
|
|
|
updateCount := 0
|
|
|
|
for i := range config.Filters {
|
|
|
|
filter := &config.Filters[i] // otherwise we will be operating on a copy
|
|
|
|
|
2019-03-18 02:52:34 -07:00
|
|
|
if !filter.Enabled {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2018-11-28 10:14:54 -07:00
|
|
|
updated, err := filter.update(force)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Failed to update filter %s: %s\n", filter.URL, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if updated {
|
|
|
|
// Saving it to the filters dir now
|
|
|
|
err = filter.save()
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Failed to save the updated filter %d: %s", filter.ID, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
updateCount++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
config.Unlock()
|
|
|
|
|
2019-01-24 10:11:01 -07:00
|
|
|
if updateCount > 0 && isRunning() {
|
|
|
|
err := reconfigureDNSServer()
|
|
|
|
if err != nil {
|
|
|
|
msg := fmt.Sprintf("SHOULD NOT HAPPEN: cannot reconfigure DNS server with the new filters: %s", err)
|
|
|
|
panic(msg)
|
|
|
|
}
|
2018-11-28 10:14:54 -07:00
|
|
|
}
|
|
|
|
return updateCount
|
|
|
|
}
|
|
|
|
|
|
|
|
// A helper function that parses filter contents and returns a number of rules and a filter name (if there's any)
|
|
|
|
func parseFilterContents(contents []byte) (int, string, []string) {
|
|
|
|
lines := strings.Split(string(contents), "\n")
|
|
|
|
rulesCount := 0
|
|
|
|
name := ""
|
|
|
|
seenTitle := false
|
|
|
|
|
|
|
|
// Count lines in the filter
|
|
|
|
for _, line := range lines {
|
2019-03-15 06:02:48 -07:00
|
|
|
|
2018-11-28 10:14:54 -07:00
|
|
|
line = strings.TrimSpace(line)
|
2019-03-15 06:02:48 -07:00
|
|
|
if len(line) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if line[0] == '!' {
|
|
|
|
m := filterTitleRegexp.FindAllStringSubmatch(line, -1)
|
|
|
|
if len(m) > 0 && len(m[0]) >= 2 && !seenTitle {
|
2018-11-28 10:14:54 -07:00
|
|
|
name = m[0][1]
|
|
|
|
seenTitle = true
|
|
|
|
}
|
2019-03-15 06:02:48 -07:00
|
|
|
} else {
|
2018-11-28 10:14:54 -07:00
|
|
|
rulesCount++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return rulesCount, name, lines
|
|
|
|
}
|
|
|
|
|
|
|
|
// Checks for filters updates
|
|
|
|
// If "force" is true -- does not check the filter's LastUpdated field
|
|
|
|
// Call "save" to persist the filter contents
|
|
|
|
func (filter *filter) update(force bool) (bool, error) {
|
|
|
|
if !force && time.Since(filter.LastUpdated) <= updatePeriod {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2019-02-12 09:22:17 -07:00
|
|
|
log.Tracef("Downloading update for filter %d from %s", filter.ID, filter.URL)
|
2018-11-28 10:14:54 -07:00
|
|
|
|
|
|
|
resp, err := client.Get(filter.URL)
|
|
|
|
if resp != nil && resp.Body != nil {
|
|
|
|
defer resp.Body.Close()
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Couldn't request filter from URL %s, skipping: %s", filter.URL, err)
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if resp.StatusCode != 200 {
|
|
|
|
log.Printf("Got status code %d from URL %s, skipping", resp.StatusCode, filter.URL)
|
|
|
|
return false, fmt.Errorf("got status code != 200: %d", resp.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
contentType := strings.ToLower(resp.Header.Get("content-type"))
|
|
|
|
if !strings.HasPrefix(contentType, "text/plain") {
|
|
|
|
log.Printf("Non-text response %s from %s, skipping", contentType, filter.URL)
|
|
|
|
return false, fmt.Errorf("non-text response %s", contentType)
|
|
|
|
}
|
|
|
|
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Couldn't fetch filter contents from URL %s, skipping: %s", filter.URL, err)
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if the filter has been really changed
|
2019-03-15 06:49:10 -07:00
|
|
|
checksum := crc32.ChecksumIEEE(body)
|
|
|
|
if filter.checksum == checksum {
|
2019-02-12 09:22:17 -07:00
|
|
|
log.Tracef("Filter #%d at URL %s hasn't changed, not updating it", filter.ID, filter.URL)
|
2018-11-28 10:14:54 -07:00
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2019-03-15 06:49:10 -07:00
|
|
|
// Extract filter name and count number of rules
|
|
|
|
rulesCount, filterName, rules := parseFilterContents(body)
|
2018-11-28 10:14:54 -07:00
|
|
|
log.Printf("Filter %d has been updated: %d bytes, %d rules", filter.ID, len(body), rulesCount)
|
2019-03-15 06:49:10 -07:00
|
|
|
if filterName != "" {
|
|
|
|
filter.Name = filterName
|
|
|
|
}
|
2018-11-28 10:14:54 -07:00
|
|
|
filter.RulesCount = rulesCount
|
|
|
|
filter.Rules = rules
|
2019-03-15 06:49:10 -07:00
|
|
|
filter.checksum = checksum
|
2018-11-28 10:14:54 -07:00
|
|
|
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// saves filter contents to the file in dataDir
|
|
|
|
func (filter *filter) save() error {
|
|
|
|
filterFilePath := filter.Path()
|
|
|
|
log.Printf("Saving filter %d contents to: %s", filter.ID, filterFilePath)
|
|
|
|
body := []byte(strings.Join(filter.Rules, "\n"))
|
|
|
|
|
2019-03-06 02:20:34 -07:00
|
|
|
err := file.SafeWrite(filterFilePath, body)
|
2019-02-10 11:44:16 -07:00
|
|
|
|
|
|
|
// update LastUpdated field after saving the file
|
|
|
|
filter.LastUpdated = filter.LastTimeUpdated()
|
|
|
|
return err
|
2018-11-28 10:14:54 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// loads filter contents from the file in dataDir
|
|
|
|
func (filter *filter) load() error {
|
|
|
|
filterFilePath := filter.Path()
|
2019-02-07 08:24:12 -07:00
|
|
|
log.Tracef("Loading filter %d contents to: %s", filter.ID, filterFilePath)
|
2018-11-28 10:14:54 -07:00
|
|
|
|
|
|
|
if _, err := os.Stat(filterFilePath); os.IsNotExist(err) {
|
|
|
|
// do nothing, file doesn't exist
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
filterFileContents, err := ioutil.ReadFile(filterFilePath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-02-07 08:24:12 -07:00
|
|
|
log.Tracef("File %s, id %d, length %d", filterFilePath, filter.ID, len(filterFileContents))
|
2018-11-28 10:14:54 -07:00
|
|
|
rulesCount, _, rules := parseFilterContents(filterFileContents)
|
|
|
|
|
|
|
|
filter.RulesCount = rulesCount
|
|
|
|
filter.Rules = rules
|
2019-03-15 06:49:10 -07:00
|
|
|
filter.checksum = crc32.ChecksumIEEE(filterFileContents)
|
2019-02-10 11:44:16 -07:00
|
|
|
filter.LastUpdated = filter.LastTimeUpdated()
|
2018-11-28 10:14:54 -07:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-03-18 04:12:04 -07:00
|
|
|
// Clear filter rules
|
|
|
|
func (filter *filter) unload() {
|
|
|
|
filter.Rules = []string{}
|
|
|
|
filter.RulesCount = 0
|
|
|
|
}
|
|
|
|
|
2018-11-28 10:14:54 -07:00
|
|
|
// Path to the filter contents
|
|
|
|
func (filter *filter) Path() string {
|
2019-02-10 10:47:43 -07:00
|
|
|
return filepath.Join(config.ourWorkingDir, dataDir, filterDir, strconv.FormatInt(filter.ID, 10)+".txt")
|
2018-11-28 10:14:54 -07:00
|
|
|
}
|
2019-02-10 11:44:16 -07:00
|
|
|
|
2019-03-10 17:49:32 -07:00
|
|
|
// LastTimeUpdated returns the time when the filter was last time updated
|
2019-02-10 11:44:16 -07:00
|
|
|
func (filter *filter) LastTimeUpdated() time.Time {
|
|
|
|
filterFilePath := filter.Path()
|
2019-03-15 06:02:48 -07:00
|
|
|
s, err := os.Stat(filterFilePath)
|
|
|
|
if os.IsNotExist(err) {
|
2019-02-10 11:44:16 -07:00
|
|
|
// if the filter file does not exist, return 0001-01-01
|
|
|
|
return time.Time{}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
// if the filter file does not exist, return 0001-01-01
|
|
|
|
return time.Time{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// filter file modified time
|
|
|
|
return s.ModTime()
|
|
|
|
}
|