safing-portmaster/service/resolver/namerecord.go
Daniel Hååvi 80664d1a27
Restructure modules ()
* Move portbase into monorepo

* Add new simple module mgr

* [WIP] Switch to new simple module mgr

* Add StateMgr and more worker variants

* [WIP] Switch more modules

* [WIP] Switch more modules

* [WIP] swtich more modules

* [WIP] switch all SPN modules

* [WIP] switch all service modules

* [WIP] Convert all workers to the new module system

* [WIP] add new task system to module manager

* [WIP] Add second take for scheduling workers

* [WIP] Add FIXME for bugs in new scheduler

* [WIP] Add minor improvements to scheduler

* [WIP] Add new worker scheduler

* [WIP] Fix more bug related to new module system

* [WIP] Fix start handing of the new module system

* [WIP] Improve startup process

* [WIP] Fix minor issues

* [WIP] Fix missing subsystem in settings

* [WIP] Initialize managers in constructor

* [WIP] Move module event initialization to constrictors

* [WIP] Fix setting for enabling and disabling the SPN module

* [WIP] Move API registeration into module construction

* [WIP] Update states mgr for all modules

* [WIP] Add CmdLine operation support

* Add state helper methods to module group and instance

* Add notification and module status handling to status package

* Fix starting issues

* Remove pilot widget and update security lock to new status data

* Remove debug logs

* Improve http server shutdown

* Add workaround for cleanly shutting down firewall+netquery

* Improve logging

* Add syncing states with notifications for new module system

* Improve starting, stopping, shutdown; resolve FIXMEs/TODOs

* [WIP] Fix most unit tests

* Review new module system and fix minor issues

* Push shutdown and restart events again via API

* Set sleep mode via interface

* Update example/template module

* [WIP] Fix spn/cabin unit test

* Remove deprecated UI elements

* Make log output more similar for the logging transition phase

* Switch spn hub and observer cmds to new module system

* Fix log sources

* Make worker mgr less error prone

* Fix tests and minor issues

* Fix observation hub

* Improve shutdown and restart handling

* Split up big connection.go source file

* Move varint and dsd packages to structures repo

* Improve expansion test

* Fix linter warnings

* Fix interception module on windows

* Fix linter errors

---------

Co-authored-by: Vladimir Stoilov <vladimir@safing.io>
2024-08-09 18:15:48 +03:00

151 lines
3.9 KiB
Go

package resolver
import (
"context"
"errors"
"fmt"
"sync"
"github.com/safing/portmaster/base/api"
"github.com/safing/portmaster/base/database"
"github.com/safing/portmaster/base/database/query"
"github.com/safing/portmaster/base/database/record"
"github.com/safing/portmaster/base/log"
)
const (
// databaseOvertime defines how much longer than the TTL name records are
// cached in the database.
databaseOvertime = 86400 * 14 // two weeks
)
var (
recordDatabase = database.NewInterface(&database.Options{
Local: true,
Internal: true,
// Cache entries because application often resolve domains multiple times.
CacheSize: 256,
// We only use the cache database here, so we can delay and batch all our
// writes. Also, no one else accesses these records, so we are fine using
// this.
DelayCachedWrites: "cache",
})
nameRecordsKeyPrefix = "cache:intel/nameRecord/"
)
// NameRecord is helper struct to RRCache to better save data to the database.
type NameRecord struct {
record.Base
sync.Mutex
Domain string
Question string
RCode int
Answer []string
Ns []string
Extra []string
Expires int64
Resolver *ResolverInfo
}
// IsValid returns whether the NameRecord is valid and may be used. Otherwise,
// it should be disregarded.
func (nameRecord *NameRecord) IsValid() bool {
switch {
case nameRecord.Resolver == nil || nameRecord.Resolver.Type == "":
// Changed in v0.6.7: Introduced Resolver *ResolverInfo
return false
default:
// Up to date!
return true
}
}
func makeNameRecordKey(domain string, question string) string {
return nameRecordsKeyPrefix + domain + question
}
// GetNameRecord gets a NameRecord from the database.
func GetNameRecord(domain, question string) (*NameRecord, error) {
key := makeNameRecordKey(domain, question)
r, err := recordDatabase.Get(key)
if err != nil {
return nil, err
}
// Unwrap record if it's wrapped.
if r.IsWrapped() {
// only allocate a new struct, if we need it
newNR := &NameRecord{}
err = record.Unwrap(r, newNR)
if err != nil {
return nil, err
}
// Check if the record is valid.
if !newNR.IsValid() {
return nil, errors.New("record is invalid (outdated format)")
}
return newNR, nil
}
// Or just adjust the type.
newNR, ok := r.(*NameRecord)
if !ok {
return nil, fmt.Errorf("record not of type *NameRecord, but %T", r)
}
// Check if the record is valid.
if !newNR.IsValid() {
return nil, errors.New("record is invalid (outdated format)")
}
return newNR, nil
}
// ResetCachedRecord deletes a NameRecord from the cache database.
func ResetCachedRecord(domain, question string) error {
// In order to properly delete an entry, we must also clear the caches.
recordDatabase.FlushCache()
recordDatabase.ClearCache()
key := makeNameRecordKey(domain, question)
return recordDatabase.Delete(key)
}
// Save saves the NameRecord to the database.
func (nameRecord *NameRecord) Save() error {
if nameRecord.Domain == "" || nameRecord.Question == "" {
return errors.New("could not save NameRecord, missing Domain and/or Question")
}
nameRecord.SetKey(makeNameRecordKey(nameRecord.Domain, nameRecord.Question))
nameRecord.UpdateMeta()
nameRecord.Meta().SetAbsoluteExpiry(nameRecord.Expires + databaseOvertime)
return recordDatabase.PutNew(nameRecord)
}
// clearNameCacheHandler is an API handler that clears all dns caches from the database.
func clearNameCacheHandler(ar *api.Request) (msg string, err error) {
log.Info("resolver: user requested dns cache clearing via action")
return clearNameCache(ar.Context())
}
// clearNameCache clears all dns caches from the database.
func clearNameCache(ctx context.Context) (msg string, err error) {
recordDatabase.FlushCache()
recordDatabase.ClearCache()
n, err := recordDatabase.Purge(ctx, query.New(nameRecordsKeyPrefix))
if err != nil {
return "", err
}
log.Debugf("resolver: cleared %d entries from dns cache", n)
return fmt.Sprintf("cleared %d dns cache entries", n), nil
}