From 40bcda1d74386ee361d7039d75e3ab1e57e78536 Mon Sep 17 00:00:00 2001 From: Kevin Schweikert <54439512+kevinschweikert@users.noreply.github.com> Date: Wed, 11 Sep 2024 03:44:21 +0200 Subject: [PATCH] Unset remaining ifaces when using `MdnsLite.InetMonitor` (#158) --- lib/mdns_lite/core_monitor.ex | 15 +++++++++++++++ lib/mdns_lite/inet_monitor.ex | 10 +++++++++- test/mdns_lite/core_monitor_test.exs | 19 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/lib/mdns_lite/core_monitor.ex b/lib/mdns_lite/core_monitor.ex index d0250ea..35c9602 100644 --- a/lib/mdns_lite/core_monitor.ex +++ b/lib/mdns_lite/core_monitor.ex @@ -65,6 +65,21 @@ defmodule MdnsLite.CoreMonitor do %{state | todo: []} end + @spec unset_remaining_ifnames(state(), [String.t()]) :: state() + def unset_remaining_ifnames(state, new_ifnames) do + Enum.reduce(known_ifnames(state), state, fn ifname, state -> + if ifname in new_ifnames do + state + else + set_ip_list(state, ifname, []) + end + end) + end + + defp known_ifnames(state) do + Map.keys(state.ip_list) + end + defp compute_delta(old_list, new_list) do {old_list -- new_list, new_list -- old_list} end diff --git a/lib/mdns_lite/inet_monitor.ex b/lib/mdns_lite/inet_monitor.ex index ccbdd76..746cfcf 100644 --- a/lib/mdns_lite/inet_monitor.ex +++ b/lib/mdns_lite/inet_monitor.ex @@ -36,10 +36,14 @@ defmodule MdnsLite.InetMonitor do end defp update(state) do - get_all_ip_addrs() + ifname_addresses = get_all_ip_addrs() + ifnames = only_ifnames(ifname_addresses) + + ifname_addresses |> Enum.reduce(state, fn {ifname, ip_list}, state -> CoreMonitor.set_ip_list(state, ifname, ip_list) end) + |> CoreMonitor.unset_remaining_ifnames(ifnames) |> CoreMonitor.flush_todo_list() end @@ -57,4 +61,8 @@ defmodule MdnsLite.InetMonitor do addrs = for addr <- Keyword.get_values(info, :addr), do: addr {to_string(ifname), addrs} end + + defp only_ifnames(ifname_addresses) do + Enum.map(ifname_addresses, &elem(&1, 0)) |> Enum.uniq() + end end diff --git a/test/mdns_lite/core_monitor_test.exs b/test/mdns_lite/core_monitor_test.exs index 1b184e7..5c4cf33 100644 --- a/test/mdns_lite/core_monitor_test.exs +++ b/test/mdns_lite/core_monitor_test.exs @@ -68,4 +68,23 @@ defmodule MdnsLite.CoreMonitorTest do {MdnsLite.ResponderSupervisor, :start_child, ["eth0", {1, 2, 3, 4, 5, 6, 7, 8}]} ] end + + test "remove unset ifnames" do + state = + CoreMonitor.init([]) + |> CoreMonitor.set_ip_list("eth0", [{1, 2, 3, 4}, {1, 2, 3, 4, 5, 6, 7, 8}]) + |> CoreMonitor.set_ip_list("wlan0", [{10, 11, 12, 13}, {14, 15, 16, 17}]) + |> CoreMonitor.flush_todo_list() + + state = + state + |> CoreMonitor.set_ip_list("wlan0", [{10, 11, 12, 13}]) + |> CoreMonitor.unset_remaining_ifnames(["wlan0"]) + + # IPv4 filtering is on by default + assert state.todo == [ + {MdnsLite.ResponderSupervisor, :stop_child, ["wlan0", {14, 15, 16, 17}]}, + {MdnsLite.ResponderSupervisor, :stop_child, ["eth0", {1, 2, 3, 4}]} + ] + end end