X-Git-Url: https://git.proxmox.com/?a=blobdiff_plain;f=src%2FPVE%2FNetwork.pm;h=e44648bb56e48bae40386039200f4e66f9949e7f;hb=d7cafe5124fbfd96a9fa5a01f5a1904c9ccc4850;hp=23206c1d831226e83d63779d39bff970b732d133;hpb=f3f0bc3afd3a1ff21d5fada57522fd8201eb6f06;p=pve-common.git diff --git a/src/PVE/Network.pm b/src/PVE/Network.pm index 23206c1..e44648b 100644 --- a/src/PVE/Network.pm +++ b/src/PVE/Network.pm @@ -2,32 +2,98 @@ package PVE::Network; use strict; use warnings; -use PVE::Tools qw(run_command); -use PVE::ProcFSTools; + use PVE::INotify; +use PVE::ProcFSTools; +use PVE::Tools qw(run_command lock_file); + use File::Basename; +use IO::Socket::IP; +use JSON; +use Net::IP; +use NetAddr::IP qw(:lower); +use POSIX qw(ECONNREFUSED); +use Socket qw(NI_NUMERICHOST NI_NUMERICSERV); # host network related utility functions +our $PHYSICAL_NIC_RE = qr/(?:eth\d+|en[^:.]+|ib[^:.]+)/; + +our $ipv4_reverse_mask = [ + '0.0.0.0', + '128.0.0.0', + '192.0.0.0', + '224.0.0.0', + '240.0.0.0', + '248.0.0.0', + '252.0.0.0', + '254.0.0.0', + '255.0.0.0', + '255.128.0.0', + '255.192.0.0', + '255.224.0.0', + '255.240.0.0', + '255.248.0.0', + '255.252.0.0', + '255.254.0.0', + '255.255.0.0', + '255.255.128.0', + '255.255.192.0', + '255.255.224.0', + '255.255.240.0', + '255.255.248.0', + '255.255.252.0', + '255.255.254.0', + '255.255.255.0', + '255.255.255.128', + '255.255.255.192', + '255.255.255.224', + '255.255.255.240', + '255.255.255.248', + '255.255.255.252', + '255.255.255.254', + '255.255.255.255', +]; + +our $ipv4_mask_hash_localnet = { + '255.0.0.0' => 8, + '255.128.0.0' => 9, + '255.192.0.0' => 10, + '255.224.0.0' => 11, + '255.240.0.0' => 12, + '255.248.0.0' => 13, + '255.252.0.0' => 14, + '255.254.0.0' => 15, + '255.255.0.0' => 16, + '255.255.128.0' => 17, + '255.255.192.0' => 18, + '255.255.224.0' => 19, + '255.255.240.0' => 20, + '255.255.248.0' => 21, + '255.255.252.0' => 22, + '255.255.254.0' => 23, + '255.255.255.0' => 24, + '255.255.255.128' => 25, + '255.255.255.192' => 26, + '255.255.255.224' => 27, + '255.255.255.240' => 28, + '255.255.255.248' => 29, + '255.255.255.252' => 30, + '255.255.255.254' => 31, + '255.255.255.255' => 32, +}; + sub setup_tc_rate_limit { - my ($iface, $rate, $burst, $debug) = @_; + my ($iface, $rate, $burst) = @_; - system("/sbin/tc class del dev $iface parent 1: classid 1:1 >/dev/null 2>&1"); - system("/sbin/tc filter del dev $iface parent ffff: protocol ip prio 50 estimator 1sec 8sec >/dev/null 2>&1"); - system("/sbin/tc qdisc del dev $iface ingress >/dev/null 2>&1"); - system("/sbin/tc qdisc del dev $iface root >/dev/null 2>&1"); + # these are allowed / expected to fail, e.g. when there is no previous rate limit to remove + eval { run_command("/sbin/tc class del dev $iface parent 1: classid 1:1 >/dev/null 2>&1"); }; + eval { run_command("/sbin/tc filter del dev $iface parent ffff: protocol all pref 50 u32 >/dev/null 2>&1"); }; + eval { run_command("/sbin/tc qdisc del dev $iface ingress >/dev/null 2>&1"); }; + eval { run_command("/sbin/tc qdisc del dev $iface root >/dev/null 2>&1"); }; return if !$rate; - run_command("/sbin/tc qdisc add dev $iface handle ffff: ingress"); - - # this does not work wit virtio - don't know why (setting "mtu 64kb" does not help) - #run_command("/sbin/tc filter add dev $iface parent ffff: protocol ip prio 50 u32 match ip src 0.0.0.0/0 police rate ${rate}bps burst ${burst}b drop flowid :1"); - # so we use avrate instead - run_command("/sbin/tc filter add dev $iface parent ffff: " . - "protocol ip prio 50 estimator 1sec 8sec " . - "u32 match ip src 0.0.0.0/0 police avrate ${rate}bps drop flowid :1"); - # tbf does not work for unknown reason #$TC qdisc add dev $DEV root tbf rate $RATE latency 100ms burst $BURST # so we use htb instead @@ -35,25 +101,23 @@ sub setup_tc_rate_limit { run_command("/sbin/tc class add dev $iface parent 1: classid 1:1 " . "htb rate ${rate}bps burst ${burst}b"); - if ($debug) { - print "DEBUG tc settings\n"; - system("/sbin/tc qdisc ls dev $iface"); - system("/sbin/tc class ls dev $iface"); - system("/sbin/tc filter ls dev $iface parent ffff:"); - } + run_command("/sbin/tc qdisc add dev $iface handle ffff: ingress"); + run_command("/sbin/tc filter add dev $iface parent ffff: " . + "prio 50 basic " . + "police rate ${rate}bps burst ${burst}b mtu 64kb " . + "drop"); } sub tap_rate_limit { my ($iface, $rate) = @_; - my $debug = 0; - $rate = int($rate*1024*1024); + $rate = int($rate*1024*1024) if $rate; my $burst = 1024*1024; - setup_tc_rate_limit($iface, $rate, $burst, $debug); + setup_tc_rate_limit($iface, $rate, $burst); } -my $read_bridge_mtu = sub { +sub read_bridge_mtu { my ($bridge) = @_; my $mtu = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/mtu"); @@ -65,7 +129,7 @@ my $read_bridge_mtu = sub { return $mtu; }; -my $parse_tap_devive_name = sub { +my $parse_tap_device_name = sub { my ($iface, $noerr) = @_; my ($vmid, $devid); @@ -73,7 +137,7 @@ my $parse_tap_devive_name = sub { if ($iface =~ m/^tap(\d+)i(\d+)$/) { $vmid = $1; $devid = $2; - } elsif ($iface =~ m/^veth(\d+)\.(\d+)$/) { + } elsif ($iface =~ m/^veth(\d+)i(\d+)$/) { $vmid = $1; $devid = $2; } else { @@ -96,37 +160,113 @@ my $compute_fwbr_names = sub { return ($fwbr, $vethfw, $vethfwpeer, $ovsintport); }; +sub iface_delete($) { + my ($iface) = @_; + run_command(['/sbin/ip', 'link', 'delete', 'dev', $iface], noerr => 1) + == 0 or die "failed to delete interface '$iface'\n"; +} + +sub iface_create($$@) { + my ($iface, $type, @args) = @_; + run_command(['/sbin/ip', 'link', 'add', $iface, 'type', $type, @args], noerr => 1) + == 0 or die "failed to create interface '$iface'\n"; +} + +sub iface_set($@) { + my ($iface, @opts) = @_; + run_command(['/sbin/ip', 'link', 'set', $iface, @opts], noerr => 1) + == 0 or die "failed to set interface options for '$iface' (".join(' ', @opts).")\n"; +} + +# helper for nicer error messages: +sub iface_set_master($$) { + my ($iface, $master) = @_; + if (defined($master)) { + eval { iface_set($iface, 'master', $master) }; + die "can't enslave '$iface' to '$master'\n" if $@; + } else { + eval { iface_set($iface, 'nomaster') }; + die "can't unenslave '$iface'\n" if $@; + } +} + my $cond_create_bridge = sub { my ($bridge) = @_; if (! -d "/sys/class/net/$bridge") { - system("/sbin/brctl addbr $bridge") == 0 || - die "can't add bridge '$bridge'\n"; + iface_create($bridge, 'bridge'); + disable_ipv6($bridge); } }; -my $bridge_add_interface = sub { - my ($bridge, $iface) = @_; +sub disable_ipv6 { + my ($iface) = @_; + return if !-d '/proc/sys/net/ipv6'; # ipv6 might be completely disabled + my $file = "/proc/sys/net/ipv6/conf/$iface/disable_ipv6"; + open(my $fh, '>', $file) or die "failed to open $file for writing: $!\n"; + print {$fh} "1\n" or die "failed to disable link-local ipv6 for $iface\n"; + close($fh); +} - system("/sbin/brctl addif $bridge $iface") == 0 || - die "can't add interface 'iface' to bridge '$bridge'\n"; +my $bridge_add_interface = sub { + my ($bridge, $iface, $tag, $trunks) = @_; + + # drop link local address (it can't be used when on a bridge anyway) + disable_ipv6($iface); + iface_set_master($iface, $bridge); + + my $vlan_aware = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/bridge/vlan_filtering"); + + if ($vlan_aware) { + + eval { run_command(['/sbin/bridge', 'vlan', 'del', 'dev', $iface, 'vid', '1-4094']) }; + die "failed to remove default vlan tags of $iface - $@\n" if $@; + + if ($trunks) { + my @trunks_array = split /;/, $trunks; + foreach my $trunk (@trunks_array) { + eval { run_command(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', $trunk]) }; + die "unable to add vlan $trunk to interface $iface - $@\n" if $@; + } + } elsif (!$tag) { + eval { run_command(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', '2-4094']) }; + die "unable to add default vlan tags to interface $iface - $@\n" if $@; + } + + $tag = 1 if !$tag; + eval { run_command(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', $tag, 'pvid', 'untagged']) }; + die "unable to add vlan $tag to interface $iface - $@\n" if $@; + } }; my $ovs_bridge_add_port = sub { - my ($bridge, $iface, $tag, $internal) = @_; + my ($bridge, $iface, $tag, $internal, $trunks) = @_; + + $trunks =~ s/;/,/g if $trunks; - my $cmd = "/usr/bin/ovs-vsctl add-port $bridge $iface"; - $cmd .= " tag=$tag" if $tag; - $cmd .= " -- set Interface $iface type=internal" if $internal; - system($cmd) == 0 || - die "can't add ovs port '$iface'\n"; + my $cmd = ['/usr/bin/ovs-vsctl']; + # first command + push @$cmd, '--', 'add-port', $bridge, $iface; + push @$cmd, "tag=$tag" if $tag; + push @$cmd, "trunks=". join(',', $trunks) if $trunks; + push @$cmd, "vlan_mode=native-untagged" if $tag && $trunks; + + if ($internal) { + # second command + push @$cmd, '--', 'set', 'Interface', $iface, 'type=internal'; + } + + eval { run_command($cmd) }; + die "can't add ovs port '$iface' - $@\n" if $@; + + disable_ipv6($iface); }; my $activate_interface = sub { my ($iface) = @_; - system("/sbin/ip link set $iface up") == 0 || - die "can't activate interface '$iface'\n"; + eval { run_command(['/sbin/ip', 'link', 'set', $iface, 'up']) }; + die "can't activate interface '$iface' - $@\n" if $@; }; sub tap_create { @@ -134,10 +274,11 @@ sub tap_create { die "unable to get bridge setting\n" if !$bridge; - my $bridgemtu = &$read_bridge_mtu($bridge); + my $bridgemtu = read_bridge_mtu($bridge); - eval { - PVE::Tools::run_command("/sbin/ifconfig $iface 0.0.0.0 promisc up mtu $bridgemtu"); + eval { + disable_ipv6($iface); + PVE::Tools::run_command(['/sbin/ip', 'link', 'set', $iface, 'up', 'promisc', 'on', 'mtu', $bridgemtu]); }; die "interface activation failed\n" if $@; } @@ -147,16 +288,27 @@ sub veth_create { die "unable to get bridge setting\n" if !$bridge; - my $bridgemtu = &$read_bridge_mtu($bridge); + my $bridgemtu = read_bridge_mtu($bridge); # create veth pair if (! -d "/sys/class/net/$veth") { - my $cmd = "/sbin/ip link add name $veth type veth peer name $vethpeer mtu $bridgemtu"; - $cmd .= " addr $mac" if $mac; - system($cmd) == 0 || die "can't create interface $veth\n"; + my $cmd = ['/sbin/ip', 'link', 'add']; + # veth device + MTU + push @$cmd, 'name', $veth; + push @$cmd, 'mtu', $bridgemtu; + push @$cmd, 'type', 'veth'; + # peer device + MTU + push @$cmd, 'peer', 'name', $vethpeer, 'mtu', $bridgemtu; + + push @$cmd, 'addr', $mac if $mac; + + eval { run_command($cmd) }; + die "can't create interface $veth - $@\n" if $@; } # up vethpair + disable_ipv6($veth); + disable_ipv6($vethpeer); &$activate_interface($veth); &$activate_interface($vethpeer); } @@ -165,15 +317,15 @@ sub veth_delete { my ($veth) = @_; if (-d "/sys/class/net/$veth") { - run_command("/sbin/ip link delete dev $veth", outfunc => sub {}, errfunc => sub {}); + iface_delete($veth); } - + eval { tap_unplug($veth) }; } my $create_firewall_bridge_linux = sub { - my ($iface, $bridge) = @_; + my ($iface, $bridge, $tag, $trunks) = @_; - my ($vmid, $devid) = &$parse_tap_devive_name($iface); + my ($vmid, $devid) = &$parse_tap_device_name($iface); my ($fwbr, $vethfw, $vethfwpeer) = &$compute_fwbr_names($vmid, $devid); &$cond_create_bridge($fwbr); @@ -183,38 +335,38 @@ my $create_firewall_bridge_linux = sub { veth_create($vethfw, $vethfwpeer, $bridge); &$bridge_add_interface($fwbr, $vethfw); - &$bridge_add_interface($bridge, $vethfwpeer); + &$bridge_add_interface($bridge, $vethfwpeer, $tag, $trunks); - return $fwbr; + &$bridge_add_interface($fwbr, $iface); }; my $create_firewall_bridge_ovs = sub { - my ($iface, $bridge, $tag) = @_; + my ($iface, $bridge, $tag, $trunks) = @_; - my ($vmid, $devid) = &$parse_tap_devive_name($iface); + my ($vmid, $devid) = &$parse_tap_device_name($iface); my ($fwbr, undef, undef, $ovsintport) = &$compute_fwbr_names($vmid, $devid); - my $bridgemtu = &$read_bridge_mtu($bridge); + my $bridgemtu = read_bridge_mtu($bridge); &$cond_create_bridge($fwbr); &$activate_interface($fwbr); &$bridge_add_interface($fwbr, $iface); - &$ovs_bridge_add_port($bridge, $ovsintport, $tag, 1); + &$ovs_bridge_add_port($bridge, $ovsintport, $tag, 1, $trunks); &$activate_interface($ovsintport); # set the same mtu for ovs int port - PVE::Tools::run_command("/sbin/ifconfig $ovsintport mtu $bridgemtu"); - + PVE::Tools::run_command(['/sbin/ip', 'link', 'set', $ovsintport, 'mtu', $bridgemtu]); + &$bridge_add_interface($fwbr, $ovsintport); }; my $cleanup_firewall_bridge = sub { my ($iface) = @_; - my ($vmid, $devid) = &$parse_tap_devive_name($iface, 1); - return if !defined($vmid); + my ($vmid, $devid) = &$parse_tap_device_name($iface, 1); + return if !defined($vmid); my ($fwbr, $vethfw, $vethfwpeer, $ovsintport) = &$compute_fwbr_names($vmid, $devid); # cleanup old port config from any openvswitch bridge @@ -227,13 +379,12 @@ my $cleanup_firewall_bridge = sub { # cleanup fwbr bridge if (-d "/sys/class/net/$fwbr") { - run_command("/sbin/ip link set dev $fwbr down", outfunc => sub {}, errfunc => sub {}); - run_command("/sbin/brctl delbr $fwbr", outfunc => sub {}, errfunc => sub {}); + iface_delete($fwbr); } }; sub tap_plug { - my ($iface, $bridge, $tag, $firewall) = @_; + my ($iface, $bridge, $tag, $firewall, $trunks, $rate) = @_; #cleanup old port config from any openvswitch bridge eval {run_command("/usr/bin/ovs-vsctl del-port $iface", outfunc => sub {}, errfunc => sub {}) }; @@ -241,21 +392,33 @@ sub tap_plug { if (-d "/sys/class/net/$bridge/bridge") { &$cleanup_firewall_bridge($iface); # remove stale devices - my $newbridge = activate_bridge_vlan($bridge, $tag); - copy_bridge_config($bridge, $newbridge) if $bridge ne $newbridge; + my $vlan_aware = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/bridge/vlan_filtering"); - $newbridge = &$create_firewall_bridge_linux($iface, $newbridge) if $firewall; + if (!$vlan_aware) { + die "vlan aware feature need to be enabled to use trunks" if $trunks; + my $newbridge = activate_bridge_vlan($bridge, $tag); + copy_bridge_config($bridge, $newbridge) if $bridge ne $newbridge; + $bridge = $newbridge; + $tag = undef; + } + + if ($firewall) { + &$create_firewall_bridge_linux($iface, $bridge, $tag, $trunks); + } else { + &$bridge_add_interface($bridge, $iface, $tag, $trunks); + } - &$bridge_add_interface($newbridge, $iface); } else { &$cleanup_firewall_bridge($iface); # remove stale devices if ($firewall) { - &$create_firewall_bridge_ovs($iface, $bridge, $tag); + &$create_firewall_bridge_ovs($iface, $bridge, $tag, $trunks); } else { - &$ovs_bridge_add_port($bridge, $iface, $tag); + &$ovs_bridge_add_port($bridge, $iface, $tag, undef, $trunks); } } + + tap_rate_limit($iface, $rate); } sub tap_unplug { @@ -267,12 +430,12 @@ sub tap_unplug { #avoid insecure dependency; ($bridge) = $bridge =~ /(\S+)/; - system("/sbin/brctl delif $bridge $iface") == 0 || - die "can't del interface '$iface' from bridge '$bridge'\n"; - + iface_set_master($iface, undef); } - + &$cleanup_firewall_bridge($iface); + #cleanup old port config from any openvswitch bridge + eval {run_command("/usr/bin/ovs-vsctl del-port $iface", outfunc => sub {}, errfunc => sub {}) }; } sub copy_bridge_config { @@ -280,7 +443,7 @@ sub copy_bridge_config { return if $br0 eq $br1; - my $br_configs = [ 'ageing_time', 'stp_state', 'priority', 'forward_delay', + my $br_configs = [ 'ageing_time', 'stp_state', 'priority', 'forward_delay', 'hello_time', 'max_age', 'multicast_snooping', 'multicast_querier']; foreach my $sysname (@$br_configs) { @@ -298,11 +461,20 @@ sub copy_bridge_config { sub activate_bridge_vlan_slave { my ($bridgevlan, $iface, $tag) = @_; my $ifacevlan = "${iface}.$tag"; - + # create vlan on $iface is not already exist if (! -d "/sys/class/net/$ifacevlan") { - system("/sbin/vconfig add $iface $tag") == 0 || - die "can't add vlan tag $tag to interface $iface\n"; + eval { + my $cmd = ['/sbin/ip', 'link', 'add']; + push @$cmd, 'link', $iface; + push @$cmd, 'name', $ifacevlan; + push @$cmd, 'type', 'vlan', 'id', $tag; + run_command($cmd); + }; + die "can't add vlan tag $tag to interface $iface - $@\n" if $@; + + # remove ipv6 link-local address before activation + disable_ipv6($ifacevlan); } # be sure to have the $ifacevlan up @@ -339,30 +511,204 @@ sub activate_bridge_vlan { my @ifaces = (); my $dir = "/sys/class/net/$bridge/brif"; - PVE::Tools::dir_glob_foreach($dir, '((eth|bond)\d+)', sub { + PVE::Tools::dir_glob_foreach($dir, '(((eth|bond)\d+|en[^.]+)(\.\d+)?)', sub { push @ifaces, $_[0]; }); die "no physical interface on bridge '$bridge'\n" if scalar(@ifaces) == 0; - # add bridgevlan if it doesn't already exist - if (! -d "/sys/class/net/$bridgevlan") { - system("/sbin/brctl addbr $bridgevlan") == 0 || - die "can't add bridge $bridgevlan\n"; + lock_network(sub { + # add bridgevlan if it doesn't already exist + if (! -d "/sys/class/net/$bridgevlan") { + iface_create($bridgevlan, 'bridge'); + } + + # for each physical interface (eth or bridge) bind them to bridge vlan + foreach my $iface (@ifaces) { + activate_bridge_vlan_slave($bridgevlan, $iface, $tag); + } + + #fixme: set other bridge flags + + # remove ipv6 link-local address before activation + disable_ipv6($bridgevlan); + # be sure to have the bridge up + &$activate_interface($bridgevlan); + }); + return $bridgevlan; +} + +sub tcp_ping { + my ($host, $port, $timeout) = @_; + + my $refused = 1; + + $timeout = 3 if !$timeout; # sane default + if (!$port) { + # Net::Ping defaults to the echo port + $port = 7; + } else { + # Net::Ping's port_number() implies service_check(1) + $refused = 0; } - # for each physical interface (eth or bridge) bind them to bridge vlan - foreach my $iface (@ifaces) { - activate_bridge_vlan_slave($bridgevlan, $iface, $tag); + my ($sock, $result); + eval { + $result = PVE::Tools::run_with_timeout($timeout, sub { + $sock = IO::Socket::IP->new(PeerHost => $host, PeerPort => $port, Type => SOCK_STREAM); + $result = $refused if $! == ECONNREFUSED; + }); + }; + if ($sock) { + $sock->close(); + $result = 1; } + return $result; +} - #fixme: set other bridge flags +sub IP_from_cidr { + my ($cidr, $version) = @_; - # be sure to have the bridge up - system("/sbin/ip link set $bridgevlan up") == 0 || - die "can't up bridge $bridgevlan\n"; - - return $bridgevlan; + return if $cidr !~ m!^(\S+?)/(\S+)$!; + my ($ip, $prefix) = ($1, $2); + + my $ipobj = Net::IP->new($ip, $version); + return if !$ipobj; + + $version = $ipobj->version(); + + my $binmask = Net::IP::ip_get_mask($prefix, $version); + return if !$binmask; + + my $masked_binip = $ipobj->binip() & $binmask; + my $masked_ip = Net::IP::ip_bintoip($masked_binip, $version); + return Net::IP->new("$masked_ip/$prefix"); +} + +sub is_ip_in_cidr { + my ($ip, $cidr, $version) = @_; + + my $cidr_obj = IP_from_cidr($cidr, $version); + return undef if !$cidr_obj; + + my $ip_obj = Net::IP->new($ip, $version); + return undef if !$ip_obj; + + my $overlap = $cidr_obj->overlaps($ip_obj); + + return if !defined($overlap); + + return $overlap == $Net::IP::IP_B_IN_A_OVERLAP || $overlap == $Net::IP::IP_IDENTICAL; +} + +# get all currently configured addresses that have a global scope, i.e., are reachable from the +# outside of the host and thus are neither loopback nor link-local ones +# returns an array ref of: { addr => "IP", cidr => "IP/PREFIXLEN", family => "inet|inet6" } +sub get_reachable_networks { + my $raw = ''; + run_command([qw(ip -j addr show up scope global)], outfunc => sub { $raw .= shift }); + my $addrs = decode_json($raw); + + # sort by family (IPv4/IPv6) and then by addr, just for some stability + my $addrs_sorter = sub { + my ($a, $b) = @_; + my $family = $a->{family} cmp $b->{family}; + return $family if $family != 0; + return $a->{local} cmp $b->{local}; + }; + + my $res = []; + for my $addr ($addrs->@*) { + next if !exists $addr->{addr_info}; + next if grep { $_ eq 'LOOPBACK' } $addr->{flags}->@*; + for my $info (sort $addrs_sorter grep { $_ && $_->{local}} $addr->{addr_info}->@*) { + push $res->@*, { + addr => $info->{local}, + cidr => "$info->{local}/$info->{prefixlen}", + family => $info->{family}, + }; + } + } + + return $res; +} + +sub get_local_ip_from_cidr { + my ($cidr) = @_; + + my $IPs = {}; + my $i = 1; + run_command(['/sbin/ip', 'address', 'show', 'to', $cidr, 'up'], outfunc => sub { + if ($_[0] =~ m!^\s*inet(?:6)?\s+($PVE::Tools::IPRE)(?:/\d+|\s+peer\s+)!) { + $IPs->{$1} = $i++ if !exists($IPs->{$1}); + } + }); + + return [ sort { $IPs->{$a} <=> $IPs->{$b} } keys %{$IPs} ]; +} + +sub addr_to_ip { + my ($addr) = @_; + my ($err, $host, $port) = Socket::getnameinfo($addr, NI_NUMERICHOST | NI_NUMERICSERV); + die "failed to get numerical host address: $err\n" if $err; + return ($host, $port) if wantarray; + return $host; +} + +sub get_ip_from_hostname { + my ($hostname, $noerr) = @_; + + my @res = eval { PVE::Tools::getaddrinfo_all($hostname) }; + if ($@) { + die "hostname lookup '$hostname' failed - $@" if !$noerr; + return undef; + } + + for my $ai (@res) { + my $ip = addr_to_ip($ai->{addr}); + if ($ip !~ m/^127\.|^::1$/) { + return wantarray ? ($ip, $ai->{family}) : $ip; + } + } + # NOTE: we only get here if no WAN/LAN IP was found, so this is now the error path! + die "address lookup for '$hostname' did not find any IP address\n" if !$noerr; + return undef; +} + +sub lock_network { + my ($code, @param) = @_; + my $res = lock_file('/var/lock/pve-network.lck', 10, $code, @param); + die $@ if $@; + return $res; +} + +# the canonical form of the given IP, i.e. dotted quad for IPv4 and RFC 5952 for IPv6 +sub canonical_ip { + my ($ip) = @_; + + my $ip_obj = NetAddr::IP->new($ip) or die "invalid IP string '$ip'\n"; + + return $ip_obj->canon(); +} + +# List of unique, canonical IPs in the provided list. +# Keeps the original order, filtering later duplicates. +sub unique_ips { + my ($ips) = @_; + + my $res = []; + my $seen = {}; + + for my $ip (@{$ips}) { + $ip = canonical_ip($ip); + + next if $seen->{$ip}; + + $seen->{$ip} = 1; + push @{$res}, $ip; + } + + return $res; } 1;