Skip to content

Commit

Permalink
- Add -fail-if-nothing-to-apply option
Browse files Browse the repository at this point in the history
- Update config examples
  • Loading branch information
maksimkurb committed Jan 4, 2025
1 parent dea1119 commit d5892c2
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 6 deletions.
12 changes: 12 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,18 @@ flush_before_applying = true # Clear ipset each time before filling it
table = 1001 # Routing table number (ip route table); a default gateway to the specified interface above will be added there
priority = 1001 # Routing rule priority (ip rule priority); the lower the number, the higher the priority

# Advanced settings: you can specify custom iptables rules that will be applied for the ipset.
# Available variables:
# {{ipset_name}} - name of the ipset
# {{fwmark}} - fwmark
# {{table}} - number of the routing table
# {{priority}} - priority of the routing rule
#
#[[ipset.iptables_rule]]
#chain = "PREROUTING"
#table = "mangle"
#rule = ["-m", "set", "--match-set", "{{ipset_name}}", "dst,src", "-j", "MARK", "--set-mark", "{{fwmark}}"]

# List 1 (manual address entry)
[[ipset.list]]
name = "local"
Expand Down
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,19 @@ flush_before_applying = true # Очищать ipset каждый раз пе
fwmark = 1001 # Этот fwmark будет применяться к пакетам, попавшим под критерии списков
table = 1001 # Номер таблицы маршрутизации (ip route table), туда будет добавляться default gateway на интерфейс, указанный выше
priority = 1001 # Приоритет правила маршрутизации (ip rule priority), чем число меньше, тем выше приоритет


# Настройки для продвинутых: можно указывать собственные правила iptables, которые будут применяться для ipset.
# Доступные переменные:
# {{ipset_name}} - название ipset
# {{fwmark}} - fwmark
# {{table}} - номер таблицы маршрутизации
# {{priority}} - приоритет правила маршрутизации
#
#[[ipset.iptables_rule]]
#chain = "PREROUTING"
#table = "mangle"
#rule = ["-m", "set", "--match-set", "{{ipset_name}}", "dst,src", "-j", "MARK", "--set-mark", "{{fwmark}}"]

# Список 1 (ручное перечисление адресов)
[[ipset.list]]
name = "local"
Expand Down
12 changes: 12 additions & 0 deletions keenetic-pbr.example.conf
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ ip_version = 4
# iptables routing rule priority
priority = 1001

# Advanced settings: you can specify custom iptables rules that will be applied for the ipset.
# Available variables:
# {{ipset_name}} - name of the ipset
# {{fwmark}} - fwmark
# {{table}} - number of the routing table
# {{priority}} - priority of the routing rule
#
#[[ipset.iptables_rule]]
#chain = "PREROUTING"
#table = "mangle"
#rule = ["-m", "set", "--match-set", "{{ipset_name}}", "dst,src", "-j", "MARK", "--set-mark", "{{fwmark}}"]

[[ipset.list]]
# Name of the domains/ips list
name = "local"
Expand Down
17 changes: 15 additions & 2 deletions lib/commands/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"fmt"
"github.com/maksimkurb/keenetic-pbr/lib/config"
"github.com/maksimkurb/keenetic-pbr/lib/lists"
"github.com/maksimkurb/keenetic-pbr/lib/log"
"github.com/maksimkurb/keenetic-pbr/lib/networking"
"os"
)

func CreateApplyCommand() *ApplyCommand {
Expand All @@ -17,6 +19,7 @@ func CreateApplyCommand() *ApplyCommand {
gc.fs.BoolVar(&gc.SkipIpset, "skip-ipset", false, "Skip ipset filling")
gc.fs.BoolVar(&gc.SkipRouting, "skip-routing", false, "Skip ip routes and ip rules applying")
gc.fs.StringVar(&gc.OnlyRoutingForInterface, "only-routing-for-interface", "", "Only apply ip routes/rules for the specified interface (if it is present in keenetic-pbr config)")
gc.fs.BoolVar(&gc.FailIfNothingToApply, "fail-if-nothing-to-apply", false, "If there is routing configuration to apply, exit with error code (5)")

return gc
}
Expand All @@ -29,6 +32,7 @@ type ApplyCommand struct {
SkipIpset bool
SkipRouting bool
OnlyRoutingForInterface string
FailIfNothingToApply bool
}

func (g *ApplyCommand) Name() string {
Expand Down Expand Up @@ -58,15 +62,24 @@ func (g *ApplyCommand) Init(args []string, ctx *AppContext) error {
}

func (g *ApplyCommand) Run() error {
if !g.SkipIpset || !g.SkipDnsmasq {
if (!g.SkipIpset || !g.SkipDnsmasq) && g.OnlyRoutingForInterface == "" {
if err := lists.ApplyLists(g.cfg, g.SkipDnsmasq, g.SkipIpset); err != nil {
return fmt.Errorf("failed to apply configuration: %v", err)
}
}

if !g.SkipRouting {
if err := networking.ApplyNetworkConfiguration(g.cfg, &g.OnlyRoutingForInterface); err != nil {
if appliedAtLeastOnce, err := networking.ApplyNetworkConfiguration(g.cfg, &g.OnlyRoutingForInterface); err != nil {
return fmt.Errorf("failed to apply configuration: %v", err)
} else {
if !appliedAtLeastOnce {
if g.FailIfNothingToApply {
log.Warnf("Nothing to apply, exiting with error code (5)")
os.Exit(5)
} else {
log.Warnf("Nothing to apply")
}
}
}
}

Expand Down
9 changes: 6 additions & 3 deletions lib/networking/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ import (
"net"
)

func ApplyNetworkConfiguration(config *config.Config, onlyRoutingForInterface *string) error {
func ApplyNetworkConfiguration(config *config.Config, onlyRoutingForInterface *string) (bool, error) {
log.Infof("Applying network configuration.")

appliedAtLeastOnce := false

for _, ipset := range config.Ipset {
shouldRoute := false
if onlyRoutingForInterface == nil || *onlyRoutingForInterface == "" {
Expand All @@ -29,12 +31,13 @@ func ApplyNetworkConfiguration(config *config.Config, onlyRoutingForInterface *s
continue
}

appliedAtLeastOnce = true
if err := applyIpsetNetworkConfiguration(ipset, *config.General.UseKeeneticAPI); err != nil {
return err
return false, err
}
}

return nil
return appliedAtLeastOnce, nil
}

func applyIpsetNetworkConfiguration(ipset *config.IpsetConfig, useKeeneticAPI bool) error {
Expand Down

0 comments on commit d5892c2

Please sign in to comment.