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