]> git.proxmox.com Git - pve-common.git/blame - src/PVE/Network.pm
net: add get_reachable_networks
[pve-common.git] / src / PVE / Network.pm
CommitLineData
b9436cda
DM
1package PVE::Network;
2
3use strict;
c36f332e 4use warnings;
f27d5e6b 5
b9436cda 6use PVE::INotify;
f27d5e6b
TL
7use PVE::ProcFSTools;
8use PVE::Tools qw(run_command lock_file);
9
b9436cda 10use File::Basename;
b6bff92e 11use IO::Socket::IP;
d7cafe51 12use JSON;
bf52d27b 13use Net::IP;
8286ef53 14use NetAddr::IP qw(:lower);
f27d5e6b
TL
15use POSIX qw(ECONNREFUSED);
16use Socket qw(NI_NUMERICHOST NI_NUMERICSERV);
bf52d27b 17
b9436cda
DM
18# host network related utility functions
19
19819404 20our $PHYSICAL_NIC_RE = qr/(?:eth\d+|en[^:.]+|ib[^:.]+)/;
3dabe28a 21
61aa94e4
WB
22our $ipv4_reverse_mask = [
23 '0.0.0.0',
24 '128.0.0.0',
25 '192.0.0.0',
26 '224.0.0.0',
27 '240.0.0.0',
28 '248.0.0.0',
29 '252.0.0.0',
30 '254.0.0.0',
31 '255.0.0.0',
32 '255.128.0.0',
33 '255.192.0.0',
34 '255.224.0.0',
35 '255.240.0.0',
36 '255.248.0.0',
37 '255.252.0.0',
38 '255.254.0.0',
39 '255.255.0.0',
40 '255.255.128.0',
41 '255.255.192.0',
42 '255.255.224.0',
43 '255.255.240.0',
44 '255.255.248.0',
45 '255.255.252.0',
46 '255.255.254.0',
47 '255.255.255.0',
48 '255.255.255.128',
49 '255.255.255.192',
50 '255.255.255.224',
51 '255.255.255.240',
52 '255.255.255.248',
53 '255.255.255.252',
54 '255.255.255.254',
55 '255.255.255.255',
56];
57
58our $ipv4_mask_hash_localnet = {
19e609fd
WB
59 '255.0.0.0' => 8,
60 '255.128.0.0' => 9,
61 '255.192.0.0' => 10,
62 '255.224.0.0' => 11,
63 '255.240.0.0' => 12,
64 '255.248.0.0' => 13,
65 '255.252.0.0' => 14,
66 '255.254.0.0' => 15,
61aa94e4
WB
67 '255.255.0.0' => 16,
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,
e43faad9
WB
82 '255.255.255.254' => 31,
83 '255.255.255.255' => 32,
61aa94e4
WB
84};
85
74d1b045 86sub setup_tc_rate_limit {
6256f2c3 87 my ($iface, $rate, $burst) = @_;
74d1b045 88
2d6b3a90
FG
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"); };
74d1b045 94
d6f2623b 95 return if !$rate;
957753df 96
74d1b045
DM
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");
103
5d35df41
W
104 run_command("/sbin/tc qdisc add dev $iface handle ffff: ingress");
105 run_command("/sbin/tc filter add dev $iface parent ffff: " .
1b915170 106 "prio 50 basic " .
5d35df41 107 "police rate ${rate}bps burst ${burst}b mtu 64kb " .
edbdf0b2 108 "drop");
74d1b045
DM
109}
110
ec9ada18
AD
111sub tap_rate_limit {
112 my ($iface, $rate) = @_;
113
ad066ae2 114 $rate = int($rate*1024*1024) if $rate;
ec9ada18
AD
115 my $burst = 1024*1024;
116
6256f2c3 117 setup_tc_rate_limit($iface, $rate, $burst);
ec9ada18 118}
74d1b045 119
1b6ad61c 120sub read_bridge_mtu {
605bb891
DM
121 my ($bridge) = @_;
122
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+)$/;
127 $mtu = int($1);
128
129 return $mtu;
130};
131
32cb7d27 132my $parse_tap_device_name = sub {
6c80e6d6 133 my ($iface, $noerr) = @_;
605bb891
DM
134
135 my ($vmid, $devid);
136
137 if ($iface =~ m/^tap(\d+)i(\d+)$/) {
138 $vmid = $1;
139 $devid = $2;
32cb7d27 140 } elsif ($iface =~ m/^veth(\d+)i(\d+)$/) {
605bb891
DM
141 $vmid = $1;
142 $devid = $2;
143 } else {
6c80e6d6
DM
144 return undef if $noerr;
145 die "can't create firewall bridge for random interface name '$iface'\n";
605bb891
DM
146 }
147
148 return ($vmid, $devid);
149};
150
70ab4434 151my $compute_fwbr_names = sub {
605bb891
DM
152 my ($vmid, $devid) = @_;
153
154 my $fwbr = "fwbr${vmid}i${devid}";
f193aa74 155 # Note: the firewall use 'fwln+' to filter traffic to VMs
7d78a966
AD
156 my $vethfw = "fwln${vmid}i${devid}";
157 my $vethfwpeer = "fwpr${vmid}p${devid}";
158 my $ovsintport = "fwln${vmid}o${devid}";
605bb891 159
70ab4434 160 return ($fwbr, $vethfw, $vethfwpeer, $ovsintport);
605bb891
DM
161};
162
e9b54cc6
WB
163sub iface_delete($) {
164 my ($iface) = @_;
165 run_command(['/sbin/ip', 'link', 'delete', 'dev', $iface], noerr => 1)
166 == 0 or die "failed to delete interface '$iface'\n";
167}
168
169sub 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";
173}
174
175sub iface_set($@) {
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";
179}
180
181# helper for nicer error messages:
182sub 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 $@;
187 } else {
188 eval { iface_set($iface, 'nomaster') };
189 die "can't unenslave '$iface'\n" if $@;
190 }
191}
192
605bb891
DM
193my $cond_create_bridge = sub {
194 my ($bridge) = @_;
195
196 if (! -d "/sys/class/net/$bridge") {
e9b54cc6 197 iface_create($bridge, 'bridge');
86b84237 198 disable_ipv6($bridge);
605bb891
DM
199 }
200};
201
f3ccd9b4
WB
202sub disable_ipv6 {
203 my ($iface) = @_;
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";
208 close($fh);
209}
210
605bb891 211my $bridge_add_interface = sub {
b0b34ffd 212 my ($bridge, $iface, $tag, $trunks) = @_;
605bb891 213
f3ccd9b4
WB
214 # drop link local address (it can't be used when on a bridge anyway)
215 disable_ipv6($iface);
e9b54cc6 216 iface_set_master($iface, $bridge);
4d25f4aa
AD
217
218 my $vlan_aware = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/bridge/vlan_filtering");
219
220 if ($vlan_aware) {
aa91ae3d
AD
221
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 $@;
224
225 if ($trunks) {
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 $@;
230 }
231 } elsif (!$tag) {
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 $@;
234 }
235
236 $tag = 1 if !$tag;
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 $@;
4d25f4aa 239 }
605bb891
DM
240};
241
70ab4434 242my $ovs_bridge_add_port = sub {
b0b34ffd
AD
243 my ($bridge, $iface, $tag, $internal, $trunks) = @_;
244
245 $trunks =~ s/;/,/g if $trunks;
70ab4434 246
89ea13ef
FG
247 my $cmd = ['/usr/bin/ovs-vsctl'];
248 # first command
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;
253
254 if ($internal) {
255 # second command
256 push @$cmd, '--', 'set', 'Interface', $iface, 'type=internal';
257 }
258
259 eval { run_command($cmd) };
260 die "can't add ovs port '$iface' - $@\n" if $@;
b0b34ffd 261
f3ccd9b4 262 disable_ipv6($iface);
70ab4434
DM
263};
264
605bb891
DM
265my $activate_interface = sub {
266 my ($iface) = @_;
267
89ea13ef
FG
268 eval { run_command(['/sbin/ip', 'link', 'set', $iface, 'up']) };
269 die "can't activate interface '$iface' - $@\n" if $@;
605bb891
DM
270};
271
3aa99c70
AD
272sub tap_create {
273 my ($iface, $bridge) = @_;
274
275 die "unable to get bridge setting\n" if !$bridge;
276
1b6ad61c 277 my $bridgemtu = read_bridge_mtu($bridge);
3aa99c70 278
9bbc4e17 279 eval {
f3ccd9b4 280 disable_ipv6($iface);
86330049 281 PVE::Tools::run_command(['/sbin/ip', 'link', 'set', $iface, 'up', 'promisc', 'on', 'mtu', $bridgemtu]);
098795e0
DM
282 };
283 die "interface activation failed\n" if $@;
3aa99c70
AD
284}
285
35efc4eb
AD
286sub veth_create {
287 my ($veth, $vethpeer, $bridge, $mac) = @_;
288
289 die "unable to get bridge setting\n" if !$bridge;
290
1b6ad61c 291 my $bridgemtu = read_bridge_mtu($bridge);
35efc4eb
AD
292
293 # create veth pair
294 if (! -d "/sys/class/net/$veth") {
89ea13ef
FG
295 my $cmd = ['/sbin/ip', 'link', 'add'];
296 # veth device + MTU
297 push @$cmd, 'name', $veth;
298 push @$cmd, 'mtu', $bridgemtu;
299 push @$cmd, 'type', 'veth';
300 # peer device + MTU
301 push @$cmd, 'peer', 'name', $vethpeer, 'mtu', $bridgemtu;
302
303 push @$cmd, 'addr', $mac if $mac;
304
305 eval { run_command($cmd) };
306 die "can't create interface $veth - $@\n" if $@;
35efc4eb
AD
307 }
308
309 # up vethpair
f3ccd9b4
WB
310 disable_ipv6($veth);
311 disable_ipv6($vethpeer);
35efc4eb
AD
312 &$activate_interface($veth);
313 &$activate_interface($vethpeer);
314}
315
f3f0bc3a
AD
316sub veth_delete {
317 my ($veth) = @_;
318
319 if (-d "/sys/class/net/$veth") {
e9b54cc6 320 iface_delete($veth);
f3f0bc3a 321 }
e0a862e2 322 eval { tap_unplug($veth) };
f3f0bc3a 323}
35efc4eb 324
605bb891 325my $create_firewall_bridge_linux = sub {
b0b34ffd 326 my ($iface, $bridge, $tag, $trunks) = @_;
605bb891 327
32cb7d27 328 my ($vmid, $devid) = &$parse_tap_device_name($iface);
70ab4434 329 my ($fwbr, $vethfw, $vethfwpeer) = &$compute_fwbr_names($vmid, $devid);
605bb891 330
605bb891
DM
331 &$cond_create_bridge($fwbr);
332 &$activate_interface($fwbr);
333
334 copy_bridge_config($bridge, $fwbr);
35efc4eb 335 veth_create($vethfw, $vethfwpeer, $bridge);
605bb891 336
7d78a966 337 &$bridge_add_interface($fwbr, $vethfw);
b0b34ffd 338 &$bridge_add_interface($bridge, $vethfwpeer, $tag, $trunks);
605bb891 339
4d25f4aa 340 &$bridge_add_interface($fwbr, $iface);
605bb891
DM
341};
342
70ab4434 343my $create_firewall_bridge_ovs = sub {
b0b34ffd 344 my ($iface, $bridge, $tag, $trunks) = @_;
70ab4434 345
32cb7d27 346 my ($vmid, $devid) = &$parse_tap_device_name($iface);
70ab4434
DM
347 my ($fwbr, undef, undef, $ovsintport) = &$compute_fwbr_names($vmid, $devid);
348
1b6ad61c 349 my $bridgemtu = read_bridge_mtu($bridge);
70ab4434
DM
350
351 &$cond_create_bridge($fwbr);
352 &$activate_interface($fwbr);
353
354 &$bridge_add_interface($fwbr, $iface);
355
b0b34ffd 356 &$ovs_bridge_add_port($bridge, $ovsintport, $tag, 1, $trunks);
ac3a04b8 357 &$activate_interface($ovsintport);
70ab4434
DM
358
359 # set the same mtu for ovs int port
86330049 360 PVE::Tools::run_command(['/sbin/ip', 'link', 'set', $ovsintport, 'mtu', $bridgemtu]);
9bbc4e17 361
70ab4434
DM
362 &$bridge_add_interface($fwbr, $ovsintport);
363};
364
365my $cleanup_firewall_bridge = sub {
605bb891
DM
366 my ($iface) = @_;
367
32cb7d27 368 my ($vmid, $devid) = &$parse_tap_device_name($iface, 1);
9bbc4e17 369 return if !defined($vmid);
70ab4434
DM
370 my ($fwbr, $vethfw, $vethfwpeer, $ovsintport) = &$compute_fwbr_names($vmid, $devid);
371
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 {});
375 }
605bb891
DM
376
377 # delete old vethfw interface
f3f0bc3a 378 veth_delete($vethfw);
605bb891
DM
379
380 # cleanup fwbr bridge
381 if (-d "/sys/class/net/$fwbr") {
e9b54cc6 382 iface_delete($fwbr);
605bb891
DM
383 }
384};
385
f0c190ee 386sub tap_plug {
bce2a5b3 387 my ($iface, $bridge, $tag, $firewall, $trunks, $rate) = @_;
f0c190ee 388
4cbabd40
AD
389 #cleanup old port config from any openvswitch bridge
390 eval {run_command("/usr/bin/ovs-vsctl del-port $iface", outfunc => sub {}, errfunc => sub {}) };
391
098795e0 392 if (-d "/sys/class/net/$bridge/bridge") {
70ab4434 393 &$cleanup_firewall_bridge($iface); # remove stale devices
605bb891 394
4d25f4aa 395 my $vlan_aware = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/bridge/vlan_filtering");
098795e0 396
4d25f4aa 397 if (!$vlan_aware) {
b0b34ffd 398 die "vlan aware feature need to be enabled to use trunks" if $trunks;
4d25f4aa
AD
399 my $newbridge = activate_bridge_vlan($bridge, $tag);
400 copy_bridge_config($bridge, $newbridge) if $bridge ne $newbridge;
ff042056 401 $bridge = $newbridge;
4d25f4aa
AD
402 $tag = undef;
403 }
404
405 if ($firewall) {
b0b34ffd 406 &$create_firewall_bridge_linux($iface, $bridge, $tag, $trunks);
4d25f4aa 407 } else {
b0b34ffd 408 &$bridge_add_interface($bridge, $iface, $tag, $trunks);
4d25f4aa 409 }
605bb891 410
098795e0 411 } else {
70ab4434
DM
412 &$cleanup_firewall_bridge($iface); # remove stale devices
413
414 if ($firewall) {
b0b34ffd 415 &$create_firewall_bridge_ovs($iface, $bridge, $tag, $trunks);
70ab4434 416 } else {
b0b34ffd 417 &$ovs_bridge_add_port($bridge, $iface, $tag, undef, $trunks);
70ab4434 418 }
4cbabd40 419 }
bce2a5b3
WB
420
421 tap_rate_limit($iface, $rate);
f0c190ee
AD
422}
423
a84b65c0 424sub tap_unplug {
2db1cc0d 425 my ($iface) = @_;
a84b65c0 426
2db1cc0d
DM
427 my $path= "/sys/class/net/$iface/brport/bridge";
428 if (-l $path) {
429 my $bridge = basename(readlink($path));
430 #avoid insecure dependency;
431 ($bridge) = $bridge =~ /(\S+)/;
4cbabd40 432
e9b54cc6 433 iface_set_master($iface, undef);
4cbabd40 434 }
9bbc4e17 435
70ab4434 436 &$cleanup_firewall_bridge($iface);
dd44486e
WB
437 #cleanup old port config from any openvswitch bridge
438 eval {run_command("/usr/bin/ovs-vsctl del-port $iface", outfunc => sub {}, errfunc => sub {}) };
a84b65c0
AD
439}
440
b9436cda
DM
441sub copy_bridge_config {
442 my ($br0, $br1) = @_;
443
444 return if $br0 eq $br1;
445
9bbc4e17 446 my $br_configs = [ 'ageing_time', 'stp_state', 'priority', 'forward_delay',
ba4af65b 447 'hello_time', 'max_age', 'multicast_snooping', 'multicast_querier'];
b9436cda
DM
448
449 foreach my $sysname (@$br_configs) {
450 eval {
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");
453 if ($v0 ne $v1) {
aec04803 454 PVE::ProcFSTools::write_proc_entry("/sys/class/net/$br1/bridge/$sysname", $v0);
b9436cda
DM
455 }
456 };
457 warn $@ if $@;
458 }
459}
460
70d89745
PRG
461sub activate_bridge_vlan_slave {
462 my ($bridgevlan, $iface, $tag) = @_;
b9436cda 463 my $ifacevlan = "${iface}.$tag";
9bbc4e17 464
b9436cda
DM
465 # create vlan on $iface is not already exist
466 if (! -d "/sys/class/net/$ifacevlan") {
89ea13ef
FG
467 eval {
468 my $cmd = ['/sbin/ip', 'link', 'add'];
469 push @$cmd, 'link', $iface;
470 push @$cmd, 'name', $ifacevlan;
471 push @$cmd, 'type', 'vlan', 'id', $tag;
472 run_command($cmd);
473 };
474 die "can't add vlan tag $tag to interface $iface - $@\n" if $@;
b9436cda 475
86b84237
WB
476 # remove ipv6 link-local address before activation
477 disable_ipv6($ifacevlan);
478 }
f3ccd9b4 479
b9436cda 480 # be sure to have the $ifacevlan up
605bb891 481 &$activate_interface($ifacevlan);
b9436cda
DM
482
483 # test if $vlaniface is already enslaved in another bridge
484 my $path= "/sys/class/net/$ifacevlan/brport/bridge";
485 if (-l $path) {
486 my $tbridge = basename(readlink($path));
70d89745 487 if ($tbridge ne $bridgevlan) {
b9436cda 488 die "interface $ifacevlan already exist in bridge $tbridge\n";
eee4b32a
PRG
489 } else {
490 # Port already attached to bridge: do nothing.
491 return;
b9436cda
DM
492 }
493 }
494
70d89745 495 # add $ifacevlan to the bridge
605bb891 496 &$bridge_add_interface($bridgevlan, $ifacevlan);
70d89745
PRG
497}
498
499sub activate_bridge_vlan {
500 my ($bridge, $tag_param) = @_;
501
502 die "bridge '$bridge' is not active\n" if ! -d "/sys/class/net/$bridge";
503
504 return $bridge if !defined($tag_param); # no vlan, simply return
505
506 my $tag = int($tag_param);
507
508 die "got strange vlan tag '$tag_param'\n" if $tag < 1 || $tag > 4094;
509
510 my $bridgevlan = "${bridge}v$tag";
511
c9030d97
PRG
512 my @ifaces = ();
513 my $dir = "/sys/class/net/$bridge/brif";
899f8c4a 514 PVE::Tools::dir_glob_foreach($dir, '(((eth|bond)\d+|en[^.]+)(\.\d+)?)', sub {
5ffa7628 515 push @ifaces, $_[0];
c9030d97
PRG
516 });
517
5ffa7628 518 die "no physical interface on bridge '$bridge'\n" if scalar(@ifaces) == 0;
c9030d97 519
a712bf6e
WB
520 lock_network(sub {
521 # add bridgevlan if it doesn't already exist
522 if (! -d "/sys/class/net/$bridgevlan") {
e9b54cc6 523 iface_create($bridgevlan, 'bridge');
a712bf6e 524 }
b9436cda 525
a712bf6e
WB
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);
529 }
70d89745 530
a712bf6e 531 #fixme: set other bridge flags
b9436cda 532
f3ccd9b4
WB
533 # remove ipv6 link-local address before activation
534 disable_ipv6($bridgevlan);
a712bf6e 535 # be sure to have the bridge up
f3ccd9b4 536 &$activate_interface($bridgevlan);
a712bf6e 537 });
b9436cda
DM
538 return $bridgevlan;
539}
540
b6bff92e
WB
541sub tcp_ping {
542 my ($host, $port, $timeout) = @_;
543
544 my $refused = 1;
545
546 $timeout = 3 if !$timeout; # sane default
547 if (!$port) {
548 # Net::Ping defaults to the echo port
549 $port = 7;
550 } else {
551 # Net::Ping's port_number() implies service_check(1)
552 $refused = 0;
553 }
554
555 my ($sock, $result);
556 eval {
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;
560 });
561 };
562 if ($sock) {
563 $sock->close();
564 $result = 1;
565 }
566 return $result;
567}
568
bf52d27b
WB
569sub IP_from_cidr {
570 my ($cidr, $version) = @_;
571
572 return if $cidr !~ m!^(\S+?)/(\S+)$!;
573 my ($ip, $prefix) = ($1, $2);
574
575 my $ipobj = Net::IP->new($ip, $version);
576 return if !$ipobj;
577
578 $version = $ipobj->version();
579
580 my $binmask = Net::IP::ip_get_mask($prefix, $version);
581 return if !$binmask;
582
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");
586}
587
588sub is_ip_in_cidr {
589 my ($ip, $cidr, $version) = @_;
590
591 my $cidr_obj = IP_from_cidr($cidr, $version);
592 return undef if !$cidr_obj;
593
594 my $ip_obj = Net::IP->new($ip, $version);
595 return undef if !$ip_obj;
596
123c3104
FE
597 my $overlap = $cidr_obj->overlaps($ip_obj);
598
b0e3bcc1
FE
599 return if !defined($overlap);
600
123c3104 601 return $overlap == $Net::IP::IP_B_IN_A_OVERLAP || $overlap == $Net::IP::IP_IDENTICAL;
bf52d27b
WB
602}
603
d7cafe51
TL
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" }
607sub get_reachable_networks {
608 my $raw = '';
609 run_command([qw(ip -j addr show up scope global)], outfunc => sub { $raw .= shift });
610 my $addrs = decode_json($raw);
611
612 # sort by family (IPv4/IPv6) and then by addr, just for some stability
613 my $addrs_sorter = sub {
614 my ($a, $b) = @_;
615 my $family = $a->{family} cmp $b->{family};
616 return $family if $family != 0;
617 return $a->{local} cmp $b->{local};
618 };
619
620 my $res = [];
621 for my $addr ($addrs->@*) {
622 next if !exists $addr->{addr_info};
623 next if grep { $_ eq 'LOOPBACK' } $addr->{flags}->@*;
624 for my $info (sort $addrs_sorter grep { $_ && $_->{local}} $addr->{addr_info}->@*) {
625 push $res->@*, {
626 addr => $info->{local},
627 cidr => "$info->{local}/$info->{prefixlen}",
628 family => $info->{family},
629 };
630 }
631 }
632
633 return $res;
634}
beb9820f
TL
635
636sub get_local_ip_from_cidr {
637 my ($cidr) = @_;
638
1e55a6cd 639 my $IPs = {};
ef737f0b 640 my $i = 1;
b15e50dd
TL
641 run_command(['/sbin/ip', 'address', 'show', 'to', $cidr, 'up'], outfunc => sub {
642 if ($_[0] =~ m!^\s*inet(?:6)?\s+($PVE::Tools::IPRE)(?:/\d+|\s+peer\s+)!) {
ef737f0b 643 $IPs->{$1} = $i++ if !exists($IPs->{$1});
beb9820f 644 }
b15e50dd 645 });
beb9820f 646
ef737f0b 647 return [ sort { $IPs->{$a} <=> $IPs->{$b} } keys %{$IPs} ];
beb9820f
TL
648}
649
87aa00de
TL
650sub addr_to_ip {
651 my ($addr) = @_;
652 my ($err, $host, $port) = Socket::getnameinfo($addr, NI_NUMERICHOST | NI_NUMERICSERV);
653 die "failed to get numerical host address: $err\n" if $err;
654 return ($host, $port) if wantarray;
655 return $host;
656}
657
658sub get_ip_from_hostname {
659 my ($hostname, $noerr) = @_;
660
5bd1e56b 661 my @res = eval { PVE::Tools::getaddrinfo_all($hostname) };
87aa00de 662 if ($@) {
4ed6974a 663 die "hostname lookup '$hostname' failed - $@" if !$noerr;
87aa00de
TL
664 return undef;
665 }
666
5bd1e56b 667 for my $ai (@res) {
29dde5f4
TL
668 my $ip = addr_to_ip($ai->{addr});
669 if ($ip !~ m/^127\.|^::1$/) {
670 return wantarray ? ($ip, $ai->{family}) : $ip;
5bd1e56b
TL
671 }
672 }
29dde5f4
TL
673 # NOTE: we only get here if no WAN/LAN IP was found, so this is now the error path!
674 die "address lookup for '$hostname' did not find any IP address\n" if !$noerr;
675 return undef;
87aa00de
TL
676}
677
a712bf6e
WB
678sub lock_network {
679 my ($code, @param) = @_;
680 my $res = lock_file('/var/lock/pve-network.lck', 10, $code, @param);
681 die $@ if $@;
682 return $res;
683}
684
8286ef53
FE
685# the canonical form of the given IP, i.e. dotted quad for IPv4 and RFC 5952 for IPv6
686sub canonical_ip {
687 my ($ip) = @_;
688
689 my $ip_obj = NetAddr::IP->new($ip) or die "invalid IP string '$ip'\n";
690
691 return $ip_obj->canon();
692}
693
8f75194c
FE
694# List of unique, canonical IPs in the provided list.
695# Keeps the original order, filtering later duplicates.
696sub unique_ips {
697 my ($ips) = @_;
698
699 my $res = [];
700 my $seen = {};
701
702 for my $ip (@{$ips}) {
703 $ip = canonical_ip($ip);
704
705 next if $seen->{$ip};
706
707 $seen->{$ip} = 1;
708 push @{$res}, $ip;
709 }
710
711 return $res;
712}
713
b9436cda 7141;