MagiTrickle/kvas2.go

222 lines
4.6 KiB
Go
Raw Normal View History

2024-08-26 19:10:40 +03:00
package main
import (
"context"
2024-08-27 03:07:58 +03:00
"errors"
2024-08-26 19:10:40 +03:00
"fmt"
2024-08-30 05:27:52 +03:00
"log"
2024-08-30 04:44:08 +03:00
"net"
2024-08-27 03:07:58 +03:00
"sync"
"time"
2024-08-26 19:10:40 +03:00
"kvas2-go/models"
"kvas2-go/pkg/dns-proxy"
"kvas2-go/pkg/iptables-helper"
2024-08-27 03:07:58 +03:00
)
var (
2024-08-30 04:29:05 +03:00
ErrAlreadyRunning = errors.New("already running")
2024-08-27 03:07:58 +03:00
ErrGroupIDConflict = errors.New("group id conflict")
2024-08-26 19:10:40 +03:00
)
type Config struct {
MinimalTTL time.Duration
ChainPostfix string
2024-08-30 04:40:46 +03:00
IpSetPostfix string
2024-08-26 19:10:40 +03:00
TargetDNSServerAddress string
ListenPort uint16
}
type App struct {
Config Config
DNSProxy *dnsProxy.DNSProxy
DNSOverrider *iptablesHelper.DNSOverrider
Records *Records
2024-08-27 03:19:10 +03:00
Groups map[int]*Group
2024-08-30 04:29:05 +03:00
isRunning bool
2024-08-26 19:10:40 +03:00
}
func (a *App) Listen(ctx context.Context) []error {
2024-08-30 04:29:05 +03:00
if a.isRunning {
return []error{ErrAlreadyRunning}
}
a.isRunning = true
defer func() { a.isRunning = false }()
2024-08-26 19:10:40 +03:00
errs := make([]error, 0)
isError := make(chan struct{})
var once sync.Once
var errsMu sync.Mutex
handleError := func(err error) {
errsMu.Lock()
defer errsMu.Unlock()
errs = append(errs, err)
once.Do(func() { close(isError) })
}
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
handleError(err)
} else {
handleError(fmt.Errorf("%v", r))
}
}
}()
newCtx, cancel := context.WithCancel(ctx)
defer cancel()
if err := a.DNSOverrider.Enable(); err != nil {
handleError(fmt.Errorf("failed to override DNS: %w", err))
return errs
}
2024-08-27 03:19:10 +03:00
for idx, _ := range a.Groups {
2024-08-30 04:30:33 +03:00
err := a.Groups[idx].Enable()
2024-08-27 03:19:10 +03:00
if err != nil {
2024-08-30 04:30:33 +03:00
handleError(fmt.Errorf("failed to enable group: %w", err))
2024-08-27 03:19:10 +03:00
return errs
}
}
2024-08-26 19:10:40 +03:00
go func() {
if err := a.DNSProxy.Listen(newCtx); err != nil {
handleError(fmt.Errorf("failed to initialize DNS proxy: %v", err))
}
}()
select {
case <-ctx.Done():
case <-isError:
}
2024-08-27 03:19:10 +03:00
for idx, _ := range a.Groups {
2024-08-30 04:30:33 +03:00
err := a.Groups[idx].Disable()
2024-08-27 03:19:10 +03:00
if err != nil {
2024-08-30 04:30:33 +03:00
handleError(fmt.Errorf("failed to disable group: %w", err))
2024-08-27 03:19:10 +03:00
return errs
}
}
2024-08-26 19:10:40 +03:00
if err := a.DNSOverrider.Disable(); err != nil {
handleError(fmt.Errorf("failed to rollback override DNS changes: %w", err))
}
return errs
}
2024-08-27 03:19:10 +03:00
func (a *App) AppendGroup(group *models.Group) error {
if _, exists := a.Groups[group.ID]; exists {
return ErrGroupIDConflict
}
a.Groups[group.ID] = &Group{
2024-08-30 04:40:46 +03:00
Group: group,
ipsetName: fmt.Sprintf("%s%d", a.Config.IpSetPostfix, group.ID),
2024-08-27 03:07:58 +03:00
}
2024-08-30 04:29:05 +03:00
if a.isRunning {
err := a.Groups[group.ID].Enable()
if err != nil {
return fmt.Errorf("failed to enable appended group: %w", err)
}
}
2024-08-27 03:07:58 +03:00
return nil
}
2024-08-30 04:44:08 +03:00
func (a *App) ListInterfaces() ([]net.Interface, error) {
interfaceNames := make([]net.Interface, 0)
interfaces, err := net.Interfaces()
if err != nil {
return nil, fmt.Errorf("failed to get interfaces: %w", err)
}
for _, iface := range interfaces {
if iface.Flags&net.FlagPointToPoint == 0 {
continue
}
interfaceNames = append(interfaceNames, iface)
}
return interfaceNames, nil
}
2024-08-27 01:44:17 +03:00
func (a *App) processARecord(aRecord dnsProxy.Address) {
ttlDuration := time.Duration(aRecord.TTL) * time.Second
if ttlDuration < a.Config.MinimalTTL {
ttlDuration = a.Config.MinimalTTL
}
a.Records.PutARecord(aRecord.Name.String(), aRecord.Address, ttlDuration)
2024-08-30 05:27:52 +03:00
names := append([]string{aRecord.Name.String()}, a.Records.GetCNameRecords(aRecord.Name.String(), true, true)...)
2024-08-27 01:44:17 +03:00
for _, group := range a.Groups {
2024-08-30 05:27:52 +03:00
err := group.HandleIPv4(names, aRecord.Address, ttlDuration)
if err != nil {
// TODO: Error log level
log.Printf("failed to handle address: %v", err)
2024-08-27 01:44:17 +03:00
}
}
}
func (a *App) processCNameRecord(cNameRecord dnsProxy.CName) {
ttlDuration := time.Duration(cNameRecord.TTL) * time.Second
if ttlDuration < a.Config.MinimalTTL {
ttlDuration = a.Config.MinimalTTL
}
a.Records.PutCNameRecord(cNameRecord.Name.String(), cNameRecord.CName.String(), ttlDuration)
}
2024-08-30 03:37:00 +03:00
func (a *App) handleRecord(rr dnsProxy.ResourceRecord) {
switch v := rr.(type) {
case dnsProxy.Address:
a.processARecord(v)
case dnsProxy.CName:
a.processCNameRecord(v)
default:
2024-08-26 19:10:40 +03:00
}
2024-08-30 03:37:00 +03:00
}
2024-08-26 19:10:40 +03:00
2024-08-30 03:37:00 +03:00
func (a *App) handleMessage(msg *dnsProxy.Message) {
for _, rr := range msg.AN {
a.handleRecord(rr)
2024-08-26 19:10:40 +03:00
}
2024-08-30 03:37:00 +03:00
for _, rr := range msg.NS {
a.handleRecord(rr)
2024-08-26 19:10:40 +03:00
}
2024-08-30 03:37:00 +03:00
for _, rr := range msg.AR {
a.handleRecord(rr)
2024-08-26 19:10:40 +03:00
}
}
func New(config Config) (*App, error) {
var err error
app := &App{}
app.Config = config
app.DNSProxy = dnsProxy.New(app.Config.ListenPort, app.Config.TargetDNSServerAddress)
2024-08-30 03:37:00 +03:00
app.DNSProxy.MsgHandler = app.handleMessage
2024-08-26 19:10:40 +03:00
app.Records = NewRecords()
2024-08-30 04:15:38 +03:00
app.DNSOverrider, err = iptablesHelper.NewDNSOverrider(fmt.Sprintf("%sDNSOVERRIDER", app.Config.ChainPostfix), app.Config.ListenPort)
2024-08-26 19:10:40 +03:00
if err != nil {
return nil, fmt.Errorf("failed to initialize DNS overrider: %w", err)
}
2024-08-27 03:19:10 +03:00
app.Groups = make(map[int]*Group)
2024-08-26 19:10:40 +03:00
return app, nil
}