]> git.proxmox.com Git - pve-common.git/blob - src/PVE/Network.pm
netowrk: general perlcritic/style fixes
[pve-common.git] / src / PVE / Network.pm
1 package PVE::Network;
2
3 use strict;
4 use warnings;
5
6 use PVE::INotify;
7 use PVE::ProcFSTools;
8 use PVE::Tools qw(run_command lock_file);
9
10 use File::Basename;
11 use IO::Socket::IP;
12 use JSON;
13 use Net::IP;
14 use NetAddr::IP qw(:lower);
15 use POSIX qw(ECONNREFUSED);
16 use Socket qw(NI_NUMERICHOST NI_NUMERICSERV);
17
18 # host network related utility functions
19
20 our $PHYSICAL_NIC_RE = qr/(?:eth\d+|en[^:.]+|ib[^:.]+)/;
21
22 our $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
58 our $ipv4_mask_hash_localnet = {
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,
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,
82 '255.255.255.254' => 31,
83 '255.255.255.255' => 32,
84 };
85
86 sub setup_tc_rate_limit {
87 my ($iface, $rate, $burst) = @_;
88
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"); };
94
95 return if !$rate;
96
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
104 run_command("/sbin/tc qdisc add dev $iface handle ffff: ingress");
105 run_command(
106 "/sbin/tc filter add dev $iface parent ffff: prio 50 basic police rate ${rate}bps burst ${burst}b mtu 64kb drop");
107
108 return;
109 }
110
111 sub tap_rate_limit {
112 my ($iface, $rate) = @_;
113
114 $rate = int($rate*1024*1024) if $rate;
115 my $burst = 1024*1024;
116
117 setup_tc_rate_limit($iface, $rate, $burst);
118
119 return;
120 }
121
122 sub read_bridge_mtu {
123 my ($bridge) = @_;
124
125 my $mtu = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/mtu");
126 die "bridge '$bridge' does not exist\n" if !$mtu;
127
128 if ($mtu =~ /^(\d+)$/) { # avoid insecure dependency (untaint)
129 $mtu = int($1);
130 } else {
131 die "unexpeted error: unable to parse mtu value '$mtu' as integer\n";
132 }
133
134 return $mtu;
135 }
136
137 my $parse_tap_device_name = sub {
138 my ($iface, $noerr) = @_;
139
140 my ($vmid, $devid);
141
142 if ($iface =~ m/^tap(\d+)i(\d+)$/) {
143 $vmid = $1;
144 $devid = $2;
145 } elsif ($iface =~ m/^veth(\d+)i(\d+)$/) {
146 $vmid = $1;
147 $devid = $2;
148 } else {
149 return if $noerr;
150 die "can't create firewall bridge for random interface name '$iface'\n";
151 }
152
153 return ($vmid, $devid);
154 };
155
156 my $compute_fwbr_names = sub {
157 my ($vmid, $devid) = @_;
158
159 my $fwbr = "fwbr${vmid}i${devid}";
160 # Note: the firewall use 'fwln+' to filter traffic to VMs
161 my $vethfw = "fwln${vmid}i${devid}";
162 my $vethfwpeer = "fwpr${vmid}p${devid}";
163 my $ovsintport = "fwln${vmid}o${devid}";
164
165 return ($fwbr, $vethfw, $vethfwpeer, $ovsintport);
166 };
167
168 sub iface_delete :prototype($) {
169 my ($iface) = @_;
170 run_command(['/sbin/ip', 'link', 'delete', 'dev', $iface], noerr => 1)
171 == 0 or die "failed to delete interface '$iface'\n";
172 return;
173 }
174
175 sub iface_create :prototype($$@) {
176 my ($iface, $type, @args) = @_;
177 run_command(['/sbin/ip', 'link', 'add', $iface, 'type', $type, @args], noerr => 1)
178 == 0 or die "failed to create interface '$iface'\n";
179 return;
180 }
181
182 sub iface_set :prototype($@) {
183 my ($iface, @opts) = @_;
184 run_command(['/sbin/ip', 'link', 'set', $iface, @opts], noerr => 1)
185 == 0 or die "failed to set interface options for '$iface' (".join(' ', @opts).")\n";
186 return;
187 }
188
189 # helper for nicer error messages:
190 sub iface_set_master :prototype($$) {
191 my ($iface, $master) = @_;
192 if (defined($master)) {
193 eval { iface_set($iface, 'master', $master) };
194 die "can't enslave '$iface' to '$master'\n" if $@;
195 } else {
196 eval { iface_set($iface, 'nomaster') };
197 die "can't unenslave '$iface'\n" if $@;
198 }
199 return;
200 }
201
202 my $cond_create_bridge = sub {
203 my ($bridge) = @_;
204
205 if (! -d "/sys/class/net/$bridge") {
206 iface_create($bridge, 'bridge');
207 disable_ipv6($bridge);
208 }
209 };
210
211 sub disable_ipv6 {
212 my ($iface) = @_;
213 return if !-d '/proc/sys/net/ipv6'; # ipv6 might be completely disabled
214 my $file = "/proc/sys/net/ipv6/conf/$iface/disable_ipv6";
215 open(my $fh, '>', $file) or die "failed to open $file for writing: $!\n";
216 print {$fh} "1\n" or die "failed to disable link-local ipv6 for $iface\n";
217 close($fh);
218 return;
219 }
220
221 my $bridge_disable_interface_learning = sub {
222 my ($iface) = @_;
223
224 PVE::ProcFSTools::write_proc_entry("/sys/class/net/$iface/brport/unicast_flood", "0");
225 PVE::ProcFSTools::write_proc_entry("/sys/class/net/$iface/brport/learning", "0");
226
227 };
228
229 my $bridge_add_interface = sub {
230 my ($bridge, $iface, $tag, $trunks) = @_;
231
232 my $bridgemtu = read_bridge_mtu($bridge);
233 eval { run_command(['/sbin/ip', 'link', 'set', $iface, 'mtu', $bridgemtu]) };
234
235 # drop link local address (it can't be used when on a bridge anyway)
236 disable_ipv6($iface);
237 iface_set_master($iface, $bridge);
238
239 my $vlan_aware = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/bridge/vlan_filtering");
240
241 if ($vlan_aware) {
242
243 eval { run_command(['/sbin/bridge', 'vlan', 'del', 'dev', $iface, 'vid', '1-4094']) };
244 die "failed to remove default vlan tags of $iface - $@\n" if $@;
245
246 if ($trunks) {
247 my @trunks_array = split /;/, $trunks;
248 foreach my $trunk (@trunks_array) {
249 eval { run_command(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', $trunk]) };
250 die "unable to add vlan $trunk to interface $iface - $@\n" if $@;
251 }
252 } elsif (!$tag) {
253 eval { run_command(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', '2-4094']) };
254 die "unable to add default vlan tags to interface $iface - $@\n" if $@;
255 }
256
257 $tag = 1 if !$tag;
258 eval { run_command(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', $tag, 'pvid', 'untagged']) };
259 die "unable to add vlan $tag to interface $iface - $@\n" if $@;
260 }
261 };
262
263 my $ovs_bridge_add_port = sub {
264 my ($bridge, $iface, $tag, $internal, $trunks) = @_;
265
266 $trunks =~ s/;/,/g if $trunks;
267
268 my $cmd = ['/usr/bin/ovs-vsctl'];
269 # first command
270 push @$cmd, '--', 'add-port', $bridge, $iface;
271 push @$cmd, "tag=$tag" if $tag;
272 push @$cmd, "trunks=". join(',', $trunks) if $trunks;
273 push @$cmd, "vlan_mode=native-untagged" if $tag && $trunks;
274
275 my $bridgemtu = read_bridge_mtu($bridge);
276 push @$cmd, '--', 'set', 'Interface', $iface, "mtu_request=$bridgemtu";
277
278 if ($internal) {
279 # second command
280 push @$cmd, '--', 'set', 'Interface', $iface, 'type=internal';
281 }
282
283 eval { run_command($cmd) };
284 die "can't add ovs port '$iface' - $@\n" if $@;
285
286 disable_ipv6($iface);
287 };
288
289 my $activate_interface = sub {
290 my ($iface, $mtu) = @_;
291
292 my $cmd = ['/sbin/ip', 'link', 'set', $iface, 'up'];
293 push @$cmd, ('mtu', $mtu) if $mtu;
294
295 eval { run_command($cmd) };
296 die "can't activate interface '$iface' - $@\n" if $@;
297 };
298
299 sub add_bridge_fdb {
300 my ($iface, $mac) = @_;
301
302 my $learning = PVE::Tools::file_read_firstline("/sys/class/net/$iface/brport/learning");
303 return if $learning;
304
305 my ($vmid, $devid) = &$parse_tap_device_name($iface, 1);
306 return if !defined($vmid);
307
308 run_command(['/sbin/bridge', 'fdb', 'append', $mac, 'dev', $iface, 'master', 'static']);
309
310 my ($fwbr, $vethfw, $vethfwpeer, $ovsintport) = &$compute_fwbr_names($vmid, $devid);
311
312 if (-d "/sys/class/net/$vethfwpeer") {
313 run_command(['/sbin/bridge', 'fdb', 'append', $mac, 'dev', $vethfwpeer, 'master', 'static']);
314 }
315
316 return;
317 }
318
319 sub del_bridge_fdb {
320 my ($iface, $mac) = @_;
321
322 my $learning = PVE::Tools::file_read_firstline("/sys/class/net/$iface/brport/learning");
323 return if $learning;
324
325 my ($vmid, $devid) = &$parse_tap_device_name($iface, 1);
326 return if !defined($vmid);
327
328 run_command(['/sbin/bridge', 'fdb', 'del', $mac, 'dev', $iface, 'master', 'static']);
329
330 my ($fwbr, $vethfw, $vethfwpeer, $ovsintport) = &$compute_fwbr_names($vmid, $devid);
331
332 if (-d "/sys/class/net/$vethfwpeer") {
333 run_command(['/sbin/bridge', 'fdb', 'del', $mac, 'dev', $vethfwpeer, 'master', 'static']);
334 }
335
336 return;
337 }
338
339 sub tap_create {
340 my ($iface, $bridge) = @_;
341
342 die "unable to get bridge setting\n" if !$bridge;
343
344 my $bridgemtu = read_bridge_mtu($bridge);
345
346 eval {
347 disable_ipv6($iface);
348 run_command(['/sbin/ip', 'link', 'set', $iface, 'up', 'promisc', 'on', 'mtu', $bridgemtu]);
349 };
350 die "interface activation failed\n" if $@;
351 return;
352 }
353
354 sub veth_create {
355 my ($veth, $vethpeer, $bridge, $mac) = @_;
356
357 die "unable to get bridge setting\n" if !$bridge;
358
359 my $bridgemtu = read_bridge_mtu($bridge);
360
361 # create veth pair
362 if (! -d "/sys/class/net/$veth") {
363 my $cmd = ['/sbin/ip', 'link', 'add'];
364 # veth device + MTU
365 push @$cmd, 'name', $veth;
366 push @$cmd, 'mtu', $bridgemtu;
367 push @$cmd, 'type', 'veth';
368 # peer device + MTU
369 push @$cmd, 'peer', 'name', $vethpeer, 'mtu', $bridgemtu;
370
371 push @$cmd, 'addr', $mac if $mac;
372
373 eval { run_command($cmd) };
374 die "can't create interface $veth - $@\n" if $@;
375 }
376
377 # up vethpair
378 disable_ipv6($veth);
379 disable_ipv6($vethpeer);
380 &$activate_interface($veth, $bridgemtu);
381 &$activate_interface($vethpeer, $bridgemtu);
382
383 return;
384 }
385
386 sub veth_delete {
387 my ($veth) = @_;
388
389 if (-d "/sys/class/net/$veth") {
390 iface_delete($veth);
391 }
392 eval { tap_unplug($veth) };
393 return;
394 }
395
396 my $create_firewall_bridge_linux = sub {
397 my ($iface, $bridge, $tag, $trunks, $no_learning) = @_;
398
399 my ($vmid, $devid) = &$parse_tap_device_name($iface);
400 my ($fwbr, $vethfw, $vethfwpeer) = &$compute_fwbr_names($vmid, $devid);
401
402 my $bridgemtu = read_bridge_mtu($bridge);
403
404 &$cond_create_bridge($fwbr);
405 &$activate_interface($fwbr, $bridgemtu);
406
407 copy_bridge_config($bridge, $fwbr);
408 veth_create($vethfw, $vethfwpeer, $bridge);
409
410 &$bridge_add_interface($bridge, $vethfwpeer, $tag, $trunks);
411 &$bridge_disable_interface_learning($vethfwpeer) if $no_learning;
412 &$bridge_add_interface($fwbr, $vethfw);
413
414 &$bridge_add_interface($fwbr, $iface);
415 };
416
417 my $create_firewall_bridge_ovs = sub {
418 my ($iface, $bridge, $tag, $trunks, $no_learning) = @_;
419
420 my ($vmid, $devid) = &$parse_tap_device_name($iface);
421 my ($fwbr, undef, undef, $ovsintport) = &$compute_fwbr_names($vmid, $devid);
422
423 my $bridgemtu = read_bridge_mtu($bridge);
424
425 &$cond_create_bridge($fwbr);
426 &$activate_interface($fwbr, $bridgemtu);
427
428 &$bridge_add_interface($fwbr, $iface);
429
430 &$ovs_bridge_add_port($bridge, $ovsintport, $tag, 1, $trunks);
431 &$activate_interface($ovsintport, $bridgemtu);
432
433 &$bridge_add_interface($fwbr, $ovsintport);
434 &$bridge_disable_interface_learning($ovsintport) if $no_learning;
435 };
436
437 my $cleanup_firewall_bridge = sub {
438 my ($iface) = @_;
439
440 my ($vmid, $devid) = &$parse_tap_device_name($iface, 1);
441 return if !defined($vmid);
442 my ($fwbr, $vethfw, $vethfwpeer, $ovsintport) = &$compute_fwbr_names($vmid, $devid);
443
444 # cleanup old port config from any openvswitch bridge
445 if (-d "/sys/class/net/$ovsintport") {
446 run_command("/usr/bin/ovs-vsctl del-port $ovsintport", outfunc => sub {}, errfunc => sub {});
447 }
448
449 # delete old vethfw interface
450 veth_delete($vethfw);
451
452 # cleanup fwbr bridge
453 if (-d "/sys/class/net/$fwbr") {
454 iface_delete($fwbr);
455 }
456 };
457
458 sub tap_plug {
459 my ($iface, $bridge, $tag, $firewall, $trunks, $rate, $opts) = @_;
460
461 $opts = {} if !defined($opts);
462
463 my $no_learning = defined($opts->{learning}) && !$opts->{learning}; # default to learning on
464
465 # cleanup old port config from any openvswitch bridge
466 eval {
467 run_command("/usr/bin/ovs-vsctl del-port $iface", outfunc => sub {}, errfunc => sub {});
468 };
469
470 if (-d "/sys/class/net/$bridge/bridge") {
471 &$cleanup_firewall_bridge($iface); # remove stale devices
472
473 my $vlan_aware = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/bridge/vlan_filtering");
474
475 if (!$vlan_aware) {
476 die "vlan aware feature need to be enabled to use trunks" if $trunks;
477 my $newbridge = activate_bridge_vlan($bridge, $tag);
478 copy_bridge_config($bridge, $newbridge) if $bridge ne $newbridge;
479 $bridge = $newbridge;
480 $tag = undef;
481 }
482
483 if ($firewall) {
484 &$create_firewall_bridge_linux($iface, $bridge, $tag, $trunks, $no_learning);
485 } else {
486 &$bridge_add_interface($bridge, $iface, $tag, $trunks);
487 }
488 $bridge_disable_interface_learning->($iface) if $no_learning;
489
490 } else {
491 &$cleanup_firewall_bridge($iface); # remove stale devices
492
493 if ($firewall) {
494 &$create_firewall_bridge_ovs($iface, $bridge, $tag, $trunks, $no_learning);
495 } else {
496 &$ovs_bridge_add_port($bridge, $iface, $tag, undef, $trunks);
497 }
498 }
499
500 tap_rate_limit($iface, $rate);
501
502 return;
503 }
504
505 sub tap_unplug {
506 my ($iface) = @_;
507
508 my $path= "/sys/class/net/$iface/brport/bridge";
509 if (-l $path) {
510 my $bridge = basename(readlink($path));
511 #avoid insecure dependency;
512 ($bridge) = $bridge =~ /(\S+)/;
513
514 iface_set_master($iface, undef);
515 }
516
517 &$cleanup_firewall_bridge($iface);
518 #cleanup old port config from any openvswitch bridge
519 eval { run_command("/usr/bin/ovs-vsctl del-port $iface", outfunc => sub {}, errfunc => sub {}) };
520
521 return;
522 }
523
524 sub copy_bridge_config {
525 my ($br0, $br1) = @_;
526
527 return if $br0 eq $br1;
528
529 my $br_configs = [
530 'ageing_time', 'stp_state', 'priority', 'forward_delay',
531 'hello_time', 'max_age', 'multicast_snooping', 'multicast_querier',
532 ];
533
534 foreach my $sysname (@$br_configs) {
535 eval {
536 my $v0 = PVE::Tools::file_read_firstline("/sys/class/net/$br0/bridge/$sysname");
537 my $v1 = PVE::Tools::file_read_firstline("/sys/class/net/$br1/bridge/$sysname");
538 if ($v0 ne $v1) {
539 PVE::ProcFSTools::write_proc_entry("/sys/class/net/$br1/bridge/$sysname", $v0);
540 }
541 };
542 warn $@ if $@;
543 }
544 return;
545 }
546
547 sub activate_bridge_vlan_slave {
548 my ($bridgevlan, $iface, $tag) = @_;
549 my $ifacevlan = "${iface}.$tag";
550
551 # create vlan on $iface is not already exist
552 if (! -d "/sys/class/net/$ifacevlan") {
553 eval {
554 my $cmd = ['/sbin/ip', 'link', 'add'];
555 push @$cmd, 'link', $iface;
556 push @$cmd, 'name', $ifacevlan;
557 push @$cmd, 'type', 'vlan', 'id', $tag;
558 run_command($cmd);
559 };
560 die "can't add vlan tag $tag to interface $iface - $@\n" if $@;
561
562 # remove ipv6 link-local address before activation
563 disable_ipv6($ifacevlan);
564 }
565
566 # be sure to have the $ifacevlan up
567 &$activate_interface($ifacevlan);
568
569 # test if $vlaniface is already enslaved in another bridge
570 my $path= "/sys/class/net/$ifacevlan/brport/bridge";
571 if (-l $path) {
572 my $tbridge = basename(readlink($path));
573 if ($tbridge ne $bridgevlan) {
574 die "interface $ifacevlan already exist in bridge $tbridge\n";
575 } else {
576 # Port already attached to bridge: do nothing.
577 return;
578 }
579 }
580
581 # add $ifacevlan to the bridge
582 &$bridge_add_interface($bridgevlan, $ifacevlan);
583 return;
584 }
585
586 sub activate_bridge_vlan {
587 my ($bridge, $tag_param) = @_;
588
589 die "bridge '$bridge' is not active\n" if ! -d "/sys/class/net/$bridge";
590
591 return $bridge if !defined($tag_param); # no vlan, simply return
592
593 my $tag = int($tag_param);
594
595 die "got strange vlan tag '$tag_param'\n" if $tag < 1 || $tag > 4094;
596
597 my $bridgevlan = "${bridge}v$tag";
598
599 my @ifaces = ();
600 my $dir = "/sys/class/net/$bridge/brif";
601 PVE::Tools::dir_glob_foreach($dir, '(((eth|bond)\d+|en[^.]+)(\.\d+)?)', sub {
602 push @ifaces, $_[0];
603 });
604
605 die "no physical interface on bridge '$bridge'\n" if scalar(@ifaces) == 0;
606
607 lock_network(sub {
608 # add bridgevlan if it doesn't already exist
609 if (! -d "/sys/class/net/$bridgevlan") {
610 iface_create($bridgevlan, 'bridge');
611 }
612
613 # for each physical interface (eth or bridge) bind them to bridge vlan
614 foreach my $iface (@ifaces) {
615 activate_bridge_vlan_slave($bridgevlan, $iface, $tag);
616 }
617
618 #fixme: set other bridge flags
619
620 # remove ipv6 link-local address before activation
621 disable_ipv6($bridgevlan);
622 # be sure to have the bridge up
623 &$activate_interface($bridgevlan);
624 });
625 return $bridgevlan;
626 }
627
628 sub tcp_ping {
629 my ($host, $port, $timeout) = @_;
630
631 my $refused = 1;
632
633 $timeout = 3 if !$timeout; # sane default
634 if (!$port) {
635 # Net::Ping defaults to the echo port
636 $port = 7;
637 } else {
638 # Net::Ping's port_number() implies service_check(1)
639 $refused = 0;
640 }
641
642 my ($sock, $result);
643 eval {
644 $result = PVE::Tools::run_with_timeout($timeout, sub {
645 $sock = IO::Socket::IP->new(PeerHost => $host, PeerPort => $port, Type => SOCK_STREAM);
646 $result = $refused if $! == ECONNREFUSED;
647 });
648 };
649 if ($sock) {
650 $sock->close();
651 $result = 1;
652 }
653 return $result;
654 }
655
656 sub IP_from_cidr {
657 my ($cidr, $version) = @_;
658
659 my ($ip, $prefix) = $cidr =~ m!^(\S+?)/(\S+)$! or return;
660
661 my $ipobj = Net::IP->new($ip, $version);
662 return if !$ipobj;
663
664 $version = $ipobj->version();
665
666 my $binmask = Net::IP::ip_get_mask($prefix, $version);
667 return if !$binmask;
668
669 my $masked_binip = $ipobj->binip() & $binmask;
670 my $masked_ip = Net::IP::ip_bintoip($masked_binip, $version);
671 return Net::IP->new("$masked_ip/$prefix");
672 }
673
674 sub is_ip_in_cidr {
675 my ($ip, $cidr, $version) = @_;
676
677 my $cidr_obj = IP_from_cidr($cidr, $version);
678 return if !$cidr_obj;
679
680 my $ip_obj = Net::IP->new($ip, $version);
681 return if !$ip_obj;
682
683 my $overlap = $cidr_obj->overlaps($ip_obj);
684 return if !defined($overlap);
685
686 return $overlap == $Net::IP::IP_B_IN_A_OVERLAP || $overlap == $Net::IP::IP_IDENTICAL;
687 }
688
689 # get all currently configured addresses that have a global scope, i.e., are reachable from the
690 # outside of the host and thus are neither loopback nor link-local ones
691 # returns an array ref of: { addr => "IP", cidr => "IP/PREFIXLEN", family => "inet|inet6" }
692 sub get_reachable_networks {
693 my $raw = '';
694 run_command([qw(ip -j addr show up scope global)], outfunc => sub { $raw .= shift });
695 my $decoded = decode_json($raw);
696
697 my $addrs = []; # filter/transform first so that we can sort correctly more easily below
698 for my $e ($decoded->@*) {
699 next if !$e->{addr_info} || grep { $_ eq 'LOOPBACK' } $e->{flags}->@*;
700 push $addrs->@*, grep { scalar(keys $_->%*) } $e->{addr_info}->@*
701 }
702 my $res = [];
703 for my $info (sort { $a->{family} cmp $b->{family} || $a->{local} cmp $b->{local} } $addrs->@*) {
704 push $res->@*, {
705 addr => $info->{local},
706 cidr => "$info->{local}/$info->{prefixlen}",
707 family => $info->{family},
708 };
709 }
710
711 return $res;
712 }
713
714 # get one or all local IPs that are not loopback ones, able to pick up the following ones (in order)
715 # - the hostname primary resolves too, follows gai.conf (admin controlled) and will be prioritised
716 # - all configured in the interfaces configuration
717 # - all currently networks known to the kernel in the current (root) namespace
718 # returns a single address if no parameter is passed, and all found, grouped by type, if `all => 1`
719 # is passed.
720 sub get_local_ip {
721 my (%param) = @_;
722
723 my $nodename = PVE::INotify::nodename();
724 my $resolved_host = eval { get_ip_from_hostname($nodename) };
725
726 return $resolved_host if defined($resolved_host) && !$param{all};
727
728 my $all = { v4 => {}, v6 => {} }; # hash to avoid duplicates and group by type
729
730 my $ifaces = PVE::INotify::read_file('interfaces', 1)->{data}->{ifaces};
731 for my $if (values $ifaces->%*) {
732 next if $if->{type} eq 'loopback' || (!defined($if->{address}) && !defined($if->{address6}));
733 my ($v4, $v6) = ($if->{address}, $if->{address6});
734
735 return ($v4 // $v6) if !$param{all}; # prefer v4, admin can override $resolved_host via hosts/gai.conf
736
737 $all->{v4}->{$v4} = 1 if defined($v4);
738 $all->{v6}->{$v6} = 1 if defined($v6);
739 }
740
741 my $live = eval { get_reachable_networks() } // [];
742 for my $info ($live->@*) {
743 my $addr = $info->{addr};
744
745 return $addr if !$param{all};
746
747 if ($info->{family} eq 'inet') {
748 $all->{v4}->{$addr} = 1;
749 } else {
750 $all->{v6}->{$addr} = 1;
751 }
752 }
753
754 return if !$param{all}; # getting here means no early return above triggered -> no IPs
755
756 my $res = []; # order gai.conf controlled first, then group v4 and v6, simply lexically sorted
757 if ($resolved_host) {
758 push $res->@*, $resolved_host;
759 delete $all->{v4}->{$resolved_host};
760 delete $all->{v6}->{$resolved_host};
761 }
762 push $res->@*, sort { $a cmp $b } keys $all->{v4}->%*;
763 push $res->@*, sort { $a cmp $b } keys $all->{v6}->%*;
764
765 return $res;
766 }
767
768 sub get_local_ip_from_cidr {
769 my ($cidr) = @_;
770
771 my $IPs = {};
772 my $i = 1;
773 run_command(['/sbin/ip', 'address', 'show', 'to', $cidr, 'up'], outfunc => sub {
774 if ($_[0] =~ m!^\s*inet(?:6)?\s+($PVE::Tools::IPRE)(?:/\d+|\s+peer\s+)!) {
775 $IPs->{$1} = $i++ if !exists($IPs->{$1});
776 }
777 });
778
779 return [ sort { $IPs->{$a} <=> $IPs->{$b} } keys %{$IPs} ];
780 }
781
782 sub addr_to_ip {
783 my ($addr) = @_;
784 my ($err, $host, $port) = Socket::getnameinfo($addr, NI_NUMERICHOST | NI_NUMERICSERV);
785 die "failed to get numerical host address: $err\n" if $err;
786 return ($host, $port) if wantarray;
787 return $host;
788 }
789
790 sub get_ip_from_hostname {
791 my ($hostname, $noerr) = @_;
792
793 my @res = eval { PVE::Tools::getaddrinfo_all($hostname) };
794 if ($@) {
795 die "hostname lookup '$hostname' failed - $@" if !$noerr;
796 return;
797 }
798
799 for my $ai (@res) {
800 my $ip = addr_to_ip($ai->{addr});
801 if ($ip !~ m/^127\.|^::1$/) {
802 return wantarray ? ($ip, $ai->{family}) : $ip;
803 }
804 }
805 # NOTE: we only get here if no WAN/LAN IP was found, so this is now the error path!
806 die "address lookup for '$hostname' did not find any IP address\n" if !$noerr;
807 return;
808 }
809
810 sub lock_network {
811 my ($code, @param) = @_;
812 my $res = lock_file('/var/lock/pve-network.lck', 10, $code, @param);
813 die $@ if $@;
814 return $res;
815 }
816
817 # the canonical form of the given IP, i.e. dotted quad for IPv4 and RFC 5952 for IPv6
818 sub canonical_ip {
819 my ($ip) = @_;
820
821 my $ip_obj = NetAddr::IP->new($ip) or die "invalid IP string '$ip'\n";
822
823 return $ip_obj->canon();
824 }
825
826 # List of unique, canonical IPs in the provided list.
827 # Keeps the original order, filtering later duplicates.
828 sub unique_ips {
829 my ($ips) = @_;
830
831 my $res = [];
832 my $seen = {};
833
834 for my $ip (@{$ips}) {
835 $ip = canonical_ip($ip);
836
837 next if $seen->{$ip};
838
839 $seen->{$ip} = 1;
840 push @{$res}, $ip;
841 }
842
843 return $res;
844 }
845
846 1;