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