]> git.proxmox.com Git - pve-common.git/blob - src/PVE/Network.pm
network: bridge add IF: do not add all VLANs if $trunks are passed
[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 Net::IP;
13 use POSIX qw(ECONNREFUSED);
14 use Socket qw(NI_NUMERICHOST NI_NUMERICSERV);
15
16 # host network related utility functions
17
18 our $PHYSICAL_NIC_RE = qr/(?:eth\d+|en[^:.]+|ib\d+)/;
19
20 our $ipv4_reverse_mask = [
21 '0.0.0.0',
22 '128.0.0.0',
23 '192.0.0.0',
24 '224.0.0.0',
25 '240.0.0.0',
26 '248.0.0.0',
27 '252.0.0.0',
28 '254.0.0.0',
29 '255.0.0.0',
30 '255.128.0.0',
31 '255.192.0.0',
32 '255.224.0.0',
33 '255.240.0.0',
34 '255.248.0.0',
35 '255.252.0.0',
36 '255.254.0.0',
37 '255.255.0.0',
38 '255.255.128.0',
39 '255.255.192.0',
40 '255.255.224.0',
41 '255.255.240.0',
42 '255.255.248.0',
43 '255.255.252.0',
44 '255.255.254.0',
45 '255.255.255.0',
46 '255.255.255.128',
47 '255.255.255.192',
48 '255.255.255.224',
49 '255.255.255.240',
50 '255.255.255.248',
51 '255.255.255.252',
52 '255.255.255.254',
53 '255.255.255.255',
54 ];
55
56 our $ipv4_mask_hash_localnet = {
57 '255.0.0.0' => 8,
58 '255.128.0.0' => 9,
59 '255.192.0.0' => 10,
60 '255.224.0.0' => 11,
61 '255.240.0.0' => 12,
62 '255.248.0.0' => 13,
63 '255.252.0.0' => 14,
64 '255.254.0.0' => 15,
65 '255.255.0.0' => 16,
66 '255.255.128.0' => 17,
67 '255.255.192.0' => 18,
68 '255.255.224.0' => 19,
69 '255.255.240.0' => 20,
70 '255.255.248.0' => 21,
71 '255.255.252.0' => 22,
72 '255.255.254.0' => 23,
73 '255.255.255.0' => 24,
74 '255.255.255.128' => 25,
75 '255.255.255.192' => 26,
76 '255.255.255.224' => 27,
77 '255.255.255.240' => 28,
78 '255.255.255.248' => 29,
79 '255.255.255.252' => 30,
80 '255.255.255.254' => 31,
81 '255.255.255.255' => 32,
82 };
83
84 sub setup_tc_rate_limit {
85 my ($iface, $rate, $burst) = @_;
86
87 # these are allowed / expected to fail, e.g. when there is no previous rate limit to remove
88 eval { run_command("/sbin/tc class del dev $iface parent 1: classid 1:1 >/dev/null 2>&1"); };
89 eval { run_command("/sbin/tc filter del dev $iface parent ffff: protocol all pref 50 u32 >/dev/null 2>&1"); };
90 eval { run_command("/sbin/tc qdisc del dev $iface ingress >/dev/null 2>&1"); };
91 eval { run_command("/sbin/tc qdisc del dev $iface root >/dev/null 2>&1"); };
92
93 return if !$rate;
94
95 # tbf does not work for unknown reason
96 #$TC qdisc add dev $DEV root tbf rate $RATE latency 100ms burst $BURST
97 # so we use htb instead
98 run_command("/sbin/tc qdisc add dev $iface root handle 1: htb default 1");
99 run_command("/sbin/tc class add dev $iface parent 1: classid 1:1 " .
100 "htb rate ${rate}bps burst ${burst}b");
101
102 run_command("/sbin/tc qdisc add dev $iface handle ffff: ingress");
103 run_command("/sbin/tc filter add dev $iface parent ffff: " .
104 "prio 50 basic " .
105 "police rate ${rate}bps burst ${burst}b mtu 64kb " .
106 "drop");
107 }
108
109 sub tap_rate_limit {
110 my ($iface, $rate) = @_;
111
112 $rate = int($rate*1024*1024) if $rate;
113 my $burst = 1024*1024;
114
115 setup_tc_rate_limit($iface, $rate, $burst);
116 }
117
118 my $read_bridge_mtu = sub {
119 my ($bridge) = @_;
120
121 my $mtu = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/mtu");
122 die "bridge '$bridge' does not exist\n" if !$mtu;
123 # avoid insecure dependency;
124 die "unable to parse mtu value" if $mtu !~ /^(\d+)$/;
125 $mtu = int($1);
126
127 return $mtu;
128 };
129
130 my $parse_tap_device_name = sub {
131 my ($iface, $noerr) = @_;
132
133 my ($vmid, $devid);
134
135 if ($iface =~ m/^tap(\d+)i(\d+)$/) {
136 $vmid = $1;
137 $devid = $2;
138 } elsif ($iface =~ m/^veth(\d+)i(\d+)$/) {
139 $vmid = $1;
140 $devid = $2;
141 } else {
142 return undef if $noerr;
143 die "can't create firewall bridge for random interface name '$iface'\n";
144 }
145
146 return ($vmid, $devid);
147 };
148
149 my $compute_fwbr_names = sub {
150 my ($vmid, $devid) = @_;
151
152 my $fwbr = "fwbr${vmid}i${devid}";
153 # Note: the firewall use 'fwln+' to filter traffic to VMs
154 my $vethfw = "fwln${vmid}i${devid}";
155 my $vethfwpeer = "fwpr${vmid}p${devid}";
156 my $ovsintport = "fwln${vmid}o${devid}";
157
158 return ($fwbr, $vethfw, $vethfwpeer, $ovsintport);
159 };
160
161 sub iface_delete($) {
162 my ($iface) = @_;
163 run_command(['/sbin/ip', 'link', 'delete', 'dev', $iface], noerr => 1)
164 == 0 or die "failed to delete interface '$iface'\n";
165 }
166
167 sub iface_create($$@) {
168 my ($iface, $type, @args) = @_;
169 run_command(['/sbin/ip', 'link', 'add', $iface, 'type', $type, @args], noerr => 1)
170 == 0 or die "failed to create interface '$iface'\n";
171 }
172
173 sub iface_set($@) {
174 my ($iface, @opts) = @_;
175 run_command(['/sbin/ip', 'link', 'set', $iface, @opts], noerr => 1)
176 == 0 or die "failed to set interface options for '$iface' (".join(' ', @opts).")\n";
177 }
178
179 # helper for nicer error messages:
180 sub iface_set_master($$) {
181 my ($iface, $master) = @_;
182 if (defined($master)) {
183 eval { iface_set($iface, 'master', $master) };
184 die "can't enslave '$iface' to '$master'\n" if $@;
185 } else {
186 eval { iface_set($iface, 'nomaster') };
187 die "can't unenslave '$iface'\n" if $@;
188 }
189 }
190
191 my $cond_create_bridge = sub {
192 my ($bridge) = @_;
193
194 if (! -d "/sys/class/net/$bridge") {
195 iface_create($bridge, 'bridge');
196 disable_ipv6($bridge);
197 }
198 };
199
200 sub disable_ipv6 {
201 my ($iface) = @_;
202 return if !-d '/proc/sys/net/ipv6'; # ipv6 might be completely disabled
203 my $file = "/proc/sys/net/ipv6/conf/$iface/disable_ipv6";
204 open(my $fh, '>', $file) or die "failed to open $file for writing: $!\n";
205 print {$fh} "1\n" or die "failed to disable link-local ipv6 for $iface\n";
206 close($fh);
207 }
208
209 my $bridge_add_interface = sub {
210 my ($bridge, $iface, $tag, $trunks) = @_;
211
212 # drop link local address (it can't be used when on a bridge anyway)
213 disable_ipv6($iface);
214 iface_set_master($iface, $bridge);
215
216 my $vlan_aware = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/bridge/vlan_filtering");
217
218 if ($vlan_aware) {
219 if ($tag) {
220 eval { run_command(['/sbin/bridge', 'vlan', 'del', 'dev', $iface, 'vid', '1-4094']) };
221 die "failed to remove default vlan tags of $iface - $@\n" if $@;
222
223 eval { run_command(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', $tag, 'pvid', 'untagged']) };
224 die "unable to add vlan $tag to interface $iface - $@\n" if $@;
225
226 warn "Caution: Setting VLAN ID 1 on a VLAN aware bridge may be dangerous\n" if $tag == 1;
227 } elsif (!$trunks) {
228 eval { run_command(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', '2-4094']) };
229 die "unable to add default vlan tags to interface $iface - $@\n" if $@;
230 }
231
232 if ($trunks) {
233 my @trunks_array = split /;/, $trunks;
234 foreach my $trunk (@trunks_array) {
235 eval { run_command(['/sbin/bridge', 'vlan', 'add', 'dev', $iface, 'vid', $trunk]) };
236 die "unable to add vlan $trunk to interface $iface - $@\n" if $@;
237 }
238 }
239 }
240 };
241
242 my $ovs_bridge_add_port = sub {
243 my ($bridge, $iface, $tag, $internal, $trunks) = @_;
244
245 $trunks =~ s/;/,/g if $trunks;
246
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 $@;
261
262 disable_ipv6($iface);
263 };
264
265 my $activate_interface = sub {
266 my ($iface) = @_;
267
268 eval { run_command(['/sbin/ip', 'link', 'set', $iface, 'up']) };
269 die "can't activate interface '$iface' - $@\n" if $@;
270 };
271
272 sub tap_create {
273 my ($iface, $bridge) = @_;
274
275 die "unable to get bridge setting\n" if !$bridge;
276
277 my $bridgemtu = &$read_bridge_mtu($bridge);
278
279 eval {
280 disable_ipv6($iface);
281 PVE::Tools::run_command(['/sbin/ip', 'link', 'set', $iface, 'up', 'promisc', 'on', 'mtu', $bridgemtu]);
282 };
283 die "interface activation failed\n" if $@;
284 }
285
286 sub veth_create {
287 my ($veth, $vethpeer, $bridge, $mac) = @_;
288
289 die "unable to get bridge setting\n" if !$bridge;
290
291 my $bridgemtu = &$read_bridge_mtu($bridge);
292
293 # create veth pair
294 if (! -d "/sys/class/net/$veth") {
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 $@;
307 }
308
309 # up vethpair
310 disable_ipv6($veth);
311 disable_ipv6($vethpeer);
312 &$activate_interface($veth);
313 &$activate_interface($vethpeer);
314 }
315
316 sub veth_delete {
317 my ($veth) = @_;
318
319 if (-d "/sys/class/net/$veth") {
320 iface_delete($veth);
321 }
322 eval { tap_unplug($veth) };
323 }
324
325 my $create_firewall_bridge_linux = sub {
326 my ($iface, $bridge, $tag, $trunks) = @_;
327
328 my ($vmid, $devid) = &$parse_tap_device_name($iface);
329 my ($fwbr, $vethfw, $vethfwpeer) = &$compute_fwbr_names($vmid, $devid);
330
331 &$cond_create_bridge($fwbr);
332 &$activate_interface($fwbr);
333
334 copy_bridge_config($bridge, $fwbr);
335 veth_create($vethfw, $vethfwpeer, $bridge);
336
337 &$bridge_add_interface($fwbr, $vethfw);
338 &$bridge_add_interface($bridge, $vethfwpeer, $tag, $trunks);
339
340 &$bridge_add_interface($fwbr, $iface);
341 };
342
343 my $create_firewall_bridge_ovs = sub {
344 my ($iface, $bridge, $tag, $trunks) = @_;
345
346 my ($vmid, $devid) = &$parse_tap_device_name($iface);
347 my ($fwbr, undef, undef, $ovsintport) = &$compute_fwbr_names($vmid, $devid);
348
349 my $bridgemtu = &$read_bridge_mtu($bridge);
350
351 &$cond_create_bridge($fwbr);
352 &$activate_interface($fwbr);
353
354 &$bridge_add_interface($fwbr, $iface);
355
356 &$ovs_bridge_add_port($bridge, $ovsintport, $tag, 1, $trunks);
357 &$activate_interface($ovsintport);
358
359 # set the same mtu for ovs int port
360 PVE::Tools::run_command(['/sbin/ip', 'link', 'set', $ovsintport, 'mtu', $bridgemtu]);
361
362 &$bridge_add_interface($fwbr, $ovsintport);
363 };
364
365 my $cleanup_firewall_bridge = sub {
366 my ($iface) = @_;
367
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);
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 }
376
377 # delete old vethfw interface
378 veth_delete($vethfw);
379
380 # cleanup fwbr bridge
381 if (-d "/sys/class/net/$fwbr") {
382 iface_delete($fwbr);
383 }
384 };
385
386 sub tap_plug {
387 my ($iface, $bridge, $tag, $firewall, $trunks, $rate) = @_;
388
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
392 if (-d "/sys/class/net/$bridge/bridge") {
393 &$cleanup_firewall_bridge($iface); # remove stale devices
394
395 my $vlan_aware = PVE::Tools::file_read_firstline("/sys/class/net/$bridge/bridge/vlan_filtering");
396
397 if (!$vlan_aware) {
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;
402 $tag = undef;
403 }
404
405 if ($firewall) {
406 &$create_firewall_bridge_linux($iface, $bridge, $tag, $trunks);
407 } else {
408 &$bridge_add_interface($bridge, $iface, $tag, $trunks);
409 }
410
411 } else {
412 &$cleanup_firewall_bridge($iface); # remove stale devices
413
414 if ($firewall) {
415 &$create_firewall_bridge_ovs($iface, $bridge, $tag, $trunks);
416 } else {
417 &$ovs_bridge_add_port($bridge, $iface, $tag, undef, $trunks);
418 }
419 }
420
421 tap_rate_limit($iface, $rate);
422 }
423
424 sub tap_unplug {
425 my ($iface) = @_;
426
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+)/;
432
433 iface_set_master($iface, undef);
434 }
435
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 {}) };
439 }
440
441 sub copy_bridge_config {
442 my ($br0, $br1) = @_;
443
444 return if $br0 eq $br1;
445
446 my $br_configs = [ 'ageing_time', 'stp_state', 'priority', 'forward_delay',
447 'hello_time', 'max_age', 'multicast_snooping', 'multicast_querier'];
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) {
454 PVE::ProcFSTools::write_proc_entry("/sys/class/net/$br1/bridge/$sysname", $v0);
455 }
456 };
457 warn $@ if $@;
458 }
459 }
460
461 sub activate_bridge_vlan_slave {
462 my ($bridgevlan, $iface, $tag) = @_;
463 my $ifacevlan = "${iface}.$tag";
464
465 # create vlan on $iface is not already exist
466 if (! -d "/sys/class/net/$ifacevlan") {
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 $@;
475
476 # remove ipv6 link-local address before activation
477 disable_ipv6($ifacevlan);
478 }
479
480 # be sure to have the $ifacevlan up
481 &$activate_interface($ifacevlan);
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));
487 if ($tbridge ne $bridgevlan) {
488 die "interface $ifacevlan already exist in bridge $tbridge\n";
489 } else {
490 # Port already attached to bridge: do nothing.
491 return;
492 }
493 }
494
495 # add $ifacevlan to the bridge
496 &$bridge_add_interface($bridgevlan, $ifacevlan);
497 }
498
499 sub 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
512 my @ifaces = ();
513 my $dir = "/sys/class/net/$bridge/brif";
514 PVE::Tools::dir_glob_foreach($dir, '(((eth|bond)\d+|en[^.]+)(\.\d+)?)', sub {
515 push @ifaces, $_[0];
516 });
517
518 die "no physical interface on bridge '$bridge'\n" if scalar(@ifaces) == 0;
519
520 lock_network(sub {
521 # add bridgevlan if it doesn't already exist
522 if (! -d "/sys/class/net/$bridgevlan") {
523 iface_create($bridgevlan, 'bridge');
524 }
525
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 }
530
531 #fixme: set other bridge flags
532
533 # remove ipv6 link-local address before activation
534 disable_ipv6($bridgevlan);
535 # be sure to have the bridge up
536 &$activate_interface($bridgevlan);
537 });
538 return $bridgevlan;
539 }
540
541 sub 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
569 sub 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
588 sub 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
597 return $cidr_obj->overlaps($ip_obj) == $Net::IP::IP_B_IN_A_OVERLAP;
598 }
599
600
601 sub get_local_ip_from_cidr {
602 my ($cidr) = @_;
603
604 my $IPs = [];
605 run_command(['/sbin/ip', 'address', 'show', 'to', $cidr, 'up'], outfunc => sub {
606 if ($_[0] =~ m!^\s*inet(?:6)?\s+($PVE::Tools::IPRE)(?:/\d+|\s+peer\s+)!) {
607 push @$IPs, $1;
608 }
609 });
610
611 return $IPs;
612 }
613
614 sub addr_to_ip {
615 my ($addr) = @_;
616 my ($err, $host, $port) = Socket::getnameinfo($addr, NI_NUMERICHOST | NI_NUMERICSERV);
617 die "failed to get numerical host address: $err\n" if $err;
618 return ($host, $port) if wantarray;
619 return $host;
620 }
621
622 sub get_ip_from_hostname {
623 my ($hostname, $noerr) = @_;
624
625 my @res = eval { PVE::Tools::getaddrinfo_all($hostname) };
626 if ($@) {
627 die "hostname lookup '$hostname' failed - $@" if !$noerr;
628 return undef;
629 }
630
631 my ($ip, $family);
632 for my $ai (@res) {
633 $family = $ai->{family};
634 my $tmpip = addr_to_ip($ai->{addr});
635 if ($tmpip !~ m/^127\.|^::1$/) {
636 $ip = $tmpip;
637 last;
638 }
639 }
640 if (!defined($ip) ) {
641 die "hostname lookup '$hostname' failed - got local IP address '$ip'\n" if !$noerr;
642 return undef;
643 }
644
645 return wantarray ? ($ip, $family) : $ip;
646 }
647
648 sub lock_network {
649 my ($code, @param) = @_;
650 my $res = lock_file('/var/lock/pve-network.lck', 10, $code, @param);
651 die $@ if $@;
652 return $res;
653 }
654
655 1;