8 use PVE
::Tools
qw(run_command lock_file);
14 use NetAddr
::IP
qw(:lower);
15 use POSIX
qw(ECONNREFUSED);
16 use Socket
qw(NI_NUMERICHOST NI_NUMERICSERV);
18 # host network related utility functions
20 our $PHYSICAL_NIC_RE = qr/(?:eth\d+|en[^:.]+|ib[^:.]+)/;
22 our $ipv4_reverse_mask = [
58 our $ipv4_mask_hash_localnet = {
68 '255.255.128.0' => 17,
69 '255.255.192.0' => 18,
70 '255.255.224.0' => 19,
71 '255.255.240.0' => 20,
72 '255.255.248.0' => 21,
73 '255.255.252.0' => 22,
74 '255.255.254.0' => 23,
75 '255.255.255.0' => 24,
76 '255.255.255.128' => 25,
77 '255.255.255.192' => 26,
78 '255.255.255.224' => 27,
79 '255.255.255.240' => 28,
80 '255.255.255.248' => 29,
81 '255.255.255.252' => 30,
82 '255.255.255.254' => 31,
83 '255.255.255.255' => 32,
86 sub setup_tc_rate_limit
{
87 my ($iface, $rate, $burst) = @_;
89 # these are allowed / expected to fail, e.g. when there is no previous rate limit to remove
90 eval { run_command
("/sbin/tc class del dev $iface parent 1: classid 1:1 >/dev/null 2>&1"); };
91 eval { run_command
("/sbin/tc filter del dev $iface parent ffff: protocol all pref 50 u32 >/dev/null 2>&1"); };
92 eval { run_command
("/sbin/tc qdisc del dev $iface ingress >/dev/null 2>&1"); };
93 eval { run_command
("/sbin/tc qdisc del dev $iface root >/dev/null 2>&1"); };
97 # tbf does not work for unknown reason
98 #$TC qdisc add dev $DEV root tbf rate $RATE latency 100ms burst $BURST
99 # so we use htb instead
100 run_command
("/sbin/tc qdisc add dev $iface root handle 1: htb default 1");
101 run_command
("/sbin/tc class add dev $iface parent 1: classid 1:1 " .
102 "htb rate ${rate}bps burst ${burst}b");
104 run_command
("/sbin/tc qdisc add dev $iface handle ffff: ingress");
105 run_command
("/sbin/tc filter add dev $iface parent ffff: " .
107 "police rate ${rate}bps burst ${burst}b mtu 64kb " .
112 my ($iface, $rate) = @_;
114 $rate = int($rate*1024*1024) if $rate;
115 my $burst = 1024*1024;
117 setup_tc_rate_limit
($iface, $rate, $burst);
120 sub read_bridge_mtu
{
123 my $mtu = PVE
::Tools
::file_read_firstline
("/sys/class/net/$bridge/mtu");
124 die "bridge '$bridge' does not exist\n" if !$mtu;
125 # avoid insecure dependency;
126 die "unable to parse mtu value" if $mtu !~ /^(\d+)$/;
132 my $parse_tap_device_name = sub {
133 my ($iface, $noerr) = @_;
137 if ($iface =~ m/^tap(\d+)i(\d+)$/) {
140 } elsif ($iface =~ m/^veth(\d+)i(\d+)$/) {
144 return undef if $noerr;
145 die "can't create firewall bridge for random interface name '$iface'\n";
148 return ($vmid, $devid);
151 my $compute_fwbr_names = sub {
152 my ($vmid, $devid) = @_;
154 my $fwbr = "fwbr${vmid}i${devid}";
155 # Note: the firewall use 'fwln+' to filter traffic to VMs
156 my $vethfw = "fwln${vmid}i${devid}";
157 my $vethfwpeer = "fwpr${vmid}p${devid}";
158 my $ovsintport = "fwln${vmid}o${devid}";
160 return ($fwbr, $vethfw, $vethfwpeer, $ovsintport);
163 sub iface_delete
($) {
165 run_command
(['/sbin/ip', 'link', 'delete', 'dev', $iface], noerr
=> 1)
166 == 0 or die "failed to delete interface '$iface'\n";
169 sub iface_create
($$@) {
170 my ($iface, $type, @args) = @_;
171 run_command
(['/sbin/ip', 'link', 'add', $iface, 'type', $type, @args], noerr
=> 1)
172 == 0 or die "failed to create interface '$iface'\n";
176 my ($iface, @opts) = @_;
177 run_command
(['/sbin/ip', 'link', 'set', $iface, @opts], noerr
=> 1)
178 == 0 or die "failed to set interface options for '$iface' (".join(' ', @opts).")\n";
181 # helper for nicer error messages:
182 sub iface_set_master
($$) {
183 my ($iface, $master) = @_;
184 if (defined($master)) {
185 eval { iface_set
($iface, 'master', $master) };
186 die "can't enslave '$iface' to '$master'\n" if $@;
188 eval { iface_set
($iface, 'nomaster') };
189 die "can't unenslave '$iface'\n" if $@;
193 my $cond_create_bridge = sub {
196 if (! -d
"/sys/class/net/$bridge") {
197 iface_create
($bridge, 'bridge');
198 disable_ipv6
($bridge);
204 return if !-d
'/proc/sys/net/ipv6'; # ipv6 might be completely disabled
205 my $file = "/proc/sys/net/ipv6/conf/$iface/disable_ipv6";
206 open(my $fh, '>', $file) or die "failed to open $file for writing: $!\n";
207 print {$fh} "1\n" or die "failed to disable link-local ipv6 for $iface\n";
211 my $bridge_add_interface = sub {
212 my ($bridge, $iface, $tag, $trunks) = @_;
214 # drop link local address (it can't be used when on a bridge anyway)
215 disable_ipv6
($iface);
216 iface_set_master
($iface, $bridge);
218 my $vlan_aware = PVE
::Tools
::file_read_firstline
("/sys/class/net/$bridge/bridge/vlan_filtering");
222 eval { run_command
(['/sbin/bridge', 'vlan', 'del', 'dev', $iface, 'vid', '1-4094']) };
223 die "failed to remove default vlan tags of $iface - $@\n" if $@;
226 my @trunks_array = split /;/, $trunks;
227 foreach my $trunk (@trunks_array) {
228 eval { run_command
(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', $trunk]) };
229 die "unable to add vlan $trunk to interface $iface - $@\n" if $@;
232 eval { run_command
(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', '2-4094']) };
233 die "unable to add default vlan tags to interface $iface - $@\n" if $@;
237 eval { run_command
(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', $tag, 'pvid', 'untagged']) };
238 die "unable to add vlan $tag to interface $iface - $@\n" if $@;
242 my $ovs_bridge_add_port = sub {
243 my ($bridge, $iface, $tag, $internal, $trunks) = @_;
245 $trunks =~ s/;/,/g if $trunks;
247 my $cmd = ['/usr/bin/ovs-vsctl'];
249 push @$cmd, '--', 'add-port', $bridge, $iface;
250 push @$cmd, "tag=$tag" if $tag;
251 push @$cmd, "trunks=". join(',', $trunks) if $trunks;
252 push @$cmd, "vlan_mode=native-untagged" if $tag && $trunks;
256 push @$cmd, '--', 'set', 'Interface', $iface, 'type=internal';
259 eval { run_command
($cmd) };
260 die "can't add ovs port '$iface' - $@\n" if $@;
262 disable_ipv6
($iface);
265 my $activate_interface = sub {
268 eval { run_command
(['/sbin/ip', 'link', 'set', $iface, 'up']) };
269 die "can't activate interface '$iface' - $@\n" if $@;
273 my ($iface, $bridge) = @_;
275 die "unable to get bridge setting\n" if !$bridge;
277 my $bridgemtu = read_bridge_mtu
($bridge);
280 disable_ipv6
($iface);
281 PVE
::Tools
::run_command
(['/sbin/ip', 'link', 'set', $iface, 'up', 'promisc', 'on', 'mtu', $bridgemtu]);
283 die "interface activation failed\n" if $@;
287 my ($veth, $vethpeer, $bridge, $mac) = @_;
289 die "unable to get bridge setting\n" if !$bridge;
291 my $bridgemtu = read_bridge_mtu
($bridge);
294 if (! -d
"/sys/class/net/$veth") {
295 my $cmd = ['/sbin/ip', 'link', 'add'];
297 push @$cmd, 'name', $veth;
298 push @$cmd, 'mtu', $bridgemtu;
299 push @$cmd, 'type', 'veth';
301 push @$cmd, 'peer', 'name', $vethpeer, 'mtu', $bridgemtu;
303 push @$cmd, 'addr', $mac if $mac;
305 eval { run_command
($cmd) };
306 die "can't create interface $veth - $@\n" if $@;
311 disable_ipv6
($vethpeer);
312 &$activate_interface($veth);
313 &$activate_interface($vethpeer);
319 if (-d
"/sys/class/net/$veth") {
322 eval { tap_unplug
($veth) };
325 my $create_firewall_bridge_linux = sub {
326 my ($iface, $bridge, $tag, $trunks) = @_;
328 my ($vmid, $devid) = &$parse_tap_device_name($iface);
329 my ($fwbr, $vethfw, $vethfwpeer) = &$compute_fwbr_names($vmid, $devid);
331 &$cond_create_bridge($fwbr);
332 &$activate_interface($fwbr);
334 copy_bridge_config
($bridge, $fwbr);
335 veth_create
($vethfw, $vethfwpeer, $bridge);
337 &$bridge_add_interface($fwbr, $vethfw);
338 &$bridge_add_interface($bridge, $vethfwpeer, $tag, $trunks);
340 &$bridge_add_interface($fwbr, $iface);
343 my $create_firewall_bridge_ovs = sub {
344 my ($iface, $bridge, $tag, $trunks) = @_;
346 my ($vmid, $devid) = &$parse_tap_device_name($iface);
347 my ($fwbr, undef, undef, $ovsintport) = &$compute_fwbr_names($vmid, $devid);
349 my $bridgemtu = read_bridge_mtu
($bridge);
351 &$cond_create_bridge($fwbr);
352 &$activate_interface($fwbr);
354 &$bridge_add_interface($fwbr, $iface);
356 &$ovs_bridge_add_port($bridge, $ovsintport, $tag, 1, $trunks);
357 &$activate_interface($ovsintport);
359 # set the same mtu for ovs int port
360 PVE
::Tools
::run_command
(['/sbin/ip', 'link', 'set', $ovsintport, 'mtu', $bridgemtu]);
362 &$bridge_add_interface($fwbr, $ovsintport);
365 my $cleanup_firewall_bridge = sub {
368 my ($vmid, $devid) = &$parse_tap_device_name($iface, 1);
369 return if !defined($vmid);
370 my ($fwbr, $vethfw, $vethfwpeer, $ovsintport) = &$compute_fwbr_names($vmid, $devid);
372 # cleanup old port config from any openvswitch bridge
373 if (-d
"/sys/class/net/$ovsintport") {
374 run_command
("/usr/bin/ovs-vsctl del-port $ovsintport", outfunc
=> sub {}, errfunc
=> sub {});
377 # delete old vethfw interface
378 veth_delete
($vethfw);
380 # cleanup fwbr bridge
381 if (-d
"/sys/class/net/$fwbr") {
387 my ($iface, $bridge, $tag, $firewall, $trunks, $rate) = @_;
389 #cleanup old port config from any openvswitch bridge
390 eval {run_command
("/usr/bin/ovs-vsctl del-port $iface", outfunc
=> sub {}, errfunc
=> sub {}) };
392 if (-d
"/sys/class/net/$bridge/bridge") {
393 &$cleanup_firewall_bridge($iface); # remove stale devices
395 my $vlan_aware = PVE
::Tools
::file_read_firstline
("/sys/class/net/$bridge/bridge/vlan_filtering");
398 die "vlan aware feature need to be enabled to use trunks" if $trunks;
399 my $newbridge = activate_bridge_vlan
($bridge, $tag);
400 copy_bridge_config
($bridge, $newbridge) if $bridge ne $newbridge;
401 $bridge = $newbridge;
406 &$create_firewall_bridge_linux($iface, $bridge, $tag, $trunks);
408 &$bridge_add_interface($bridge, $iface, $tag, $trunks);
412 &$cleanup_firewall_bridge($iface); # remove stale devices
415 &$create_firewall_bridge_ovs($iface, $bridge, $tag, $trunks);
417 &$ovs_bridge_add_port($bridge, $iface, $tag, undef, $trunks);
421 tap_rate_limit
($iface, $rate);
427 my $path= "/sys/class/net/$iface/brport/bridge";
429 my $bridge = basename
(readlink($path));
430 #avoid insecure dependency;
431 ($bridge) = $bridge =~ /(\S+)/;
433 iface_set_master
($iface, undef);
436 &$cleanup_firewall_bridge($iface);
437 #cleanup old port config from any openvswitch bridge
438 eval {run_command
("/usr/bin/ovs-vsctl del-port $iface", outfunc
=> sub {}, errfunc
=> sub {}) };
441 sub copy_bridge_config
{
442 my ($br0, $br1) = @_;
444 return if $br0 eq $br1;
446 my $br_configs = [ 'ageing_time', 'stp_state', 'priority', 'forward_delay',
447 'hello_time', 'max_age', 'multicast_snooping', 'multicast_querier'];
449 foreach my $sysname (@$br_configs) {
451 my $v0 = PVE
::Tools
::file_read_firstline
("/sys/class/net/$br0/bridge/$sysname");
452 my $v1 = PVE
::Tools
::file_read_firstline
("/sys/class/net/$br1/bridge/$sysname");
454 PVE
::ProcFSTools
::write_proc_entry
("/sys/class/net/$br1/bridge/$sysname", $v0);
461 sub activate_bridge_vlan_slave
{
462 my ($bridgevlan, $iface, $tag) = @_;
463 my $ifacevlan = "${iface}.$tag";
465 # create vlan on $iface is not already exist
466 if (! -d
"/sys/class/net/$ifacevlan") {
468 my $cmd = ['/sbin/ip', 'link', 'add'];
469 push @$cmd, 'link', $iface;
470 push @$cmd, 'name', $ifacevlan;
471 push @$cmd, 'type', 'vlan', 'id', $tag;
474 die "can't add vlan tag $tag to interface $iface - $@\n" if $@;
476 # remove ipv6 link-local address before activation
477 disable_ipv6
($ifacevlan);
480 # be sure to have the $ifacevlan up
481 &$activate_interface($ifacevlan);
483 # test if $vlaniface is already enslaved in another bridge
484 my $path= "/sys/class/net/$ifacevlan/brport/bridge";
486 my $tbridge = basename
(readlink($path));
487 if ($tbridge ne $bridgevlan) {
488 die "interface $ifacevlan already exist in bridge $tbridge\n";
490 # Port already attached to bridge: do nothing.
495 # add $ifacevlan to the bridge
496 &$bridge_add_interface($bridgevlan, $ifacevlan);
499 sub activate_bridge_vlan
{
500 my ($bridge, $tag_param) = @_;
502 die "bridge '$bridge' is not active\n" if ! -d
"/sys/class/net/$bridge";
504 return $bridge if !defined($tag_param); # no vlan, simply return
506 my $tag = int($tag_param);
508 die "got strange vlan tag '$tag_param'\n" if $tag < 1 || $tag > 4094;
510 my $bridgevlan = "${bridge}v$tag";
513 my $dir = "/sys/class/net/$bridge/brif";
514 PVE
::Tools
::dir_glob_foreach
($dir, '(((eth|bond)\d+|en[^.]+)(\.\d+)?)', sub {
518 die "no physical interface on bridge '$bridge'\n" if scalar(@ifaces) == 0;
521 # add bridgevlan if it doesn't already exist
522 if (! -d
"/sys/class/net/$bridgevlan") {
523 iface_create
($bridgevlan, 'bridge');
526 # for each physical interface (eth or bridge) bind them to bridge vlan
527 foreach my $iface (@ifaces) {
528 activate_bridge_vlan_slave
($bridgevlan, $iface, $tag);
531 #fixme: set other bridge flags
533 # remove ipv6 link-local address before activation
534 disable_ipv6
($bridgevlan);
535 # be sure to have the bridge up
536 &$activate_interface($bridgevlan);
542 my ($host, $port, $timeout) = @_;
546 $timeout = 3 if !$timeout; # sane default
548 # Net::Ping defaults to the echo port
551 # Net::Ping's port_number() implies service_check(1)
557 $result = PVE
::Tools
::run_with_timeout
($timeout, sub {
558 $sock = IO
::Socket
::IP-
>new(PeerHost
=> $host, PeerPort
=> $port, Type
=> SOCK_STREAM
);
559 $result = $refused if $! == ECONNREFUSED
;
570 my ($cidr, $version) = @_;
572 return if $cidr !~ m!^(\S+?)/(\S+)$!;
573 my ($ip, $prefix) = ($1, $2);
575 my $ipobj = Net
::IP-
>new($ip, $version);
578 $version = $ipobj->version();
580 my $binmask = Net
::IP
::ip_get_mask
($prefix, $version);
583 my $masked_binip = $ipobj->binip() & $binmask;
584 my $masked_ip = Net
::IP
::ip_bintoip
($masked_binip, $version);
585 return Net
::IP-
>new("$masked_ip/$prefix");
589 my ($ip, $cidr, $version) = @_;
591 my $cidr_obj = IP_from_cidr
($cidr, $version);
592 return undef if !$cidr_obj;
594 my $ip_obj = Net
::IP-
>new($ip, $version);
595 return undef if !$ip_obj;
597 my $overlap = $cidr_obj->overlaps($ip_obj);
599 return if !defined($overlap);
601 return $overlap == $Net::IP
::IP_B_IN_A_OVERLAP
|| $overlap == $Net::IP
::IP_IDENTICAL
;
604 # get all currently configured addresses that have a global scope, i.e., are reachable from the
605 # outside of the host and thus are neither loopback nor link-local ones
606 # returns an array ref of: { addr => "IP", cidr => "IP/PREFIXLEN", family => "inet|inet6" }
607 sub get_reachable_networks
{
609 run_command
([qw(ip -j addr show up scope global)], outfunc
=> sub { $raw .= shift });
610 my $decoded = decode_json
($raw);
612 my $addrs = []; # filter/transform first so that we can sort correctly more easily below
613 for my $e ($decoded->@*) {
614 next if !$e->{addr_info
} || grep { $_ eq 'LOOPBACK' } $e->{flags
}->@*;
615 push $addrs->@*, grep { scalar(keys $_->%*) } $e->{addr_info
}->@*
618 for my $info (sort { $a->{family
} cmp $b->{family
} || $a->{local} cmp $b->{local} } $addrs->@*) {
620 addr
=> $info->{local},
621 cidr
=> "$info->{local}/$info->{prefixlen}",
622 family
=> $info->{family
},
629 # get one or all local IPs that are not loopback ones, able to pick up the following ones (in order)
630 # - the hostname primary resolves too, follows gai.conf (admin controlled) and will be prioritised
631 # - all configured in the interfaces configuration
632 # - all currently networks known to the kernel in the current (root) namespace
633 # returns a single address if no parameter is passed, and all found, grouped by type, if `all => 1`
638 my $nodename = PVE
::INotify
::nodename
();
639 my $resolved_host = eval { get_ip_from_hostname
($nodename) };
641 return $resolved_host if defined($resolved_host) && !$param{all
};
643 my $all = { v4
=> {}, v6
=> {} }; # hash to avoid duplicates and group by type
645 my $ifaces = PVE
::INotify
::read_file
('interfaces', 1)->{data
}->{ifaces
};
646 for my $if (values $ifaces->%*) {
647 next if $if->{type
} eq 'loopback' || (!defined($if->{address
}) && !defined($if->{address6
}));
648 my ($v4, $v6) = ($if->{address
}, $if->{address6
});
650 return ($v4 // $v6) if !$param{all
}; # prefer v4, admin can override $resolved_host via hosts/gai.conf
652 $all->{v4
}->{$v4} = 1 if defined($v4);
653 $all->{v6
}->{$v6} = 1 if defined($v6);
656 my $live = eval { get_reachable_networks
() } // [];
657 for my $info ($live->@*) {
658 my $addr = $info->{addr
};
660 return $addr if !$param{all
};
662 if ($info->{family
} eq 'inet') {
663 $all->{v4
}->{$addr} = 1;
665 $all->{v6
}->{$addr} = 1;
669 return undef if !$param{all
}; # getting here means no early return above triggered -> no IPs
671 my $res = []; # order gai.conf controlled first, then group v4 and v6, simply lexically sorted
672 if ($resolved_host) {
673 push $res->@*, $resolved_host;
674 delete $all->{v4
}->{$resolved_host};
675 delete $all->{v6
}->{$resolved_host};
677 push $res->@*, sort { $a cmp $b } keys $all->{v4
}->%*;
678 push $res->@*, sort { $a cmp $b } keys $all->{v6
}->%*;
683 sub get_local_ip_from_cidr
{
688 run_command
(['/sbin/ip', 'address', 'show', 'to', $cidr, 'up'], outfunc
=> sub {
689 if ($_[0] =~ m!^\s*inet(?:6)?\s+($PVE::Tools::IPRE)(?:/\d+|\s+peer\s+)!) {
690 $IPs->{$1} = $i++ if !exists($IPs->{$1});
694 return [ sort { $IPs->{$a} <=> $IPs->{$b} } keys %{$IPs} ];
699 my ($err, $host, $port) = Socket
::getnameinfo
($addr, NI_NUMERICHOST
| NI_NUMERICSERV
);
700 die "failed to get numerical host address: $err\n" if $err;
701 return ($host, $port) if wantarray;
705 sub get_ip_from_hostname
{
706 my ($hostname, $noerr) = @_;
708 my @res = eval { PVE
::Tools
::getaddrinfo_all
($hostname) };
710 die "hostname lookup '$hostname' failed - $@" if !$noerr;
715 my $ip = addr_to_ip
($ai->{addr
});
716 if ($ip !~ m/^127\.|^::1$/) {
717 return wantarray ?
($ip, $ai->{family
}) : $ip;
720 # NOTE: we only get here if no WAN/LAN IP was found, so this is now the error path!
721 die "address lookup for '$hostname' did not find any IP address\n" if !$noerr;
726 my ($code, @param) = @_;
727 my $res = lock_file
('/var/lock/pve-network.lck', 10, $code, @param);
732 # the canonical form of the given IP, i.e. dotted quad for IPv4 and RFC 5952 for IPv6
736 my $ip_obj = NetAddr
::IP-
>new($ip) or die "invalid IP string '$ip'\n";
738 return $ip_obj->canon();
741 # List of unique, canonical IPs in the provided list.
742 # Keeps the original order, filtering later duplicates.
749 for my $ip (@{$ips}) {
750 $ip = canonical_ip
($ip);
752 next if $seen->{$ip};