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