Skip to content

Commit

Permalink
Unset remaining ifaces when using MdnsLite.InetMonitor (#158)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinschweikert authored Sep 11, 2024
1 parent 5349b4b commit 40bcda1
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
15 changes: 15 additions & 0 deletions lib/mdns_lite/core_monitor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion lib/mdns_lite/inet_monitor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
19 changes: 19 additions & 0 deletions test/mdns_lite/core_monitor_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 40bcda1

Please sign in to comment.