]> git.proxmox.com Git - pve-common.git/blob - src/PVE/INotify.pm
dbc986841529daf100ec6b6a0a214ba7b2ef8a1d
[pve-common.git] / src / PVE / INotify.pm
1 package PVE::INotify;
2
3 # todo: maybe we do not need update_file() ?
4
5 use strict;
6 use warnings;
7
8 use POSIX;
9 use IO::File;
10 use IO::Dir;
11 use File::stat;
12 use File::Basename;
13 use Fcntl qw(:DEFAULT :flock);
14 use PVE::SafeSyslog;
15 use PVE::Exception qw(raise_param_exc);
16 use PVE::Network;
17 use PVE::Tools;
18 use PVE::ProcFSTools;
19 use Clone qw(clone);
20 use Linux::Inotify2;
21 use base 'Exporter';
22 use JSON;
23
24 our @EXPORT_OK = qw(read_file write_file register_file);
25
26 my $ccache;
27 my $ccachemap;
28 my $ccacheregex;
29 my $inotify;
30 my $inotify_pid = 0;
31 my $versions;
32 my $shadowfiles = {
33 '/etc/network/interfaces' => '/etc/network/interfaces.new',
34 };
35
36 # to enable cached operation, you need to call 'inotify_init'
37 # inotify handles are a limited resource, so use with care (only
38 # enable the cache if you really need it)
39
40 # Note: please close the inotify handle after you fork
41
42 sub ccache_default_writer {
43 my ($filename, $data) = @_;
44
45 die "undefined config writer for '$filename' :ERROR";
46 }
47
48 sub ccache_default_parser {
49 my ($filename, $srcfd) = @_;
50
51 die "undefined config reader for '$filename' :ERROR";
52 }
53
54 sub ccache_compute_diff {
55 my ($filename, $shadow) = @_;
56
57 my $diff = '';
58
59 open (TMP, "diff -b -N -u '$filename' '$shadow'|");
60
61 while (my $line = <TMP>) {
62 $diff .= $line;
63 }
64
65 close (TMP);
66
67 $diff = undef if !$diff;
68
69 return $diff;
70 }
71
72 sub ccache_info {
73 my ($filename) = @_;
74
75 foreach my $uid (keys %$ccacheregex) {
76 my $ccinfo = $ccacheregex->{$uid};
77 my $dir = $ccinfo->{dir};
78 my $regex = $ccinfo->{regex};
79 if ($filename =~ m|^$dir/+$regex$|) {
80 if (!$ccache->{$filename}) {
81 my $cp = {};
82 while (my ($k, $v) = each %$ccinfo) {
83 $cp->{$k} = $v;
84 }
85 $ccache->{$filename} = $cp;
86 }
87 return ($ccache->{$filename}, $filename);
88 }
89 }
90
91 $filename = $ccachemap->{$filename} if defined ($ccachemap->{$filename});
92
93 die "file '$filename' not added :ERROR" if !defined ($ccache->{$filename});
94
95 return ($ccache->{$filename}, $filename);
96 }
97
98 sub write_file {
99 my ($fileid, $data, $full) = @_;
100
101 my ($ccinfo, $filename) = ccache_info($fileid);
102
103 my $writer = $ccinfo->{writer};
104
105 my $realname = $filename;
106
107 my $shadow;
108 if ($shadow = $shadowfiles->{$filename}) {
109 $realname = $shadow;
110 }
111
112 my $perm = $ccinfo->{perm} || 0644;
113
114 my $tmpname = "$realname.tmp.$$";
115
116 my $res;
117 eval {
118 my $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT, $perm);
119 die "unable to open file '$tmpname' - $!\n" if !$fh;
120
121 $res = &$writer($filename, $fh, $data);
122
123 die "closing file '$tmpname' failed - $!\n" unless close $fh;
124 };
125 my $err = $@;
126
127 $ccinfo->{version} = undef;
128
129 if ($err) {
130 unlink $tmpname;
131 die $err;
132 }
133
134 if (!rename($tmpname, $realname)) {
135 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
136 unlink $tmpname;
137 die $msg;
138 }
139
140 my $diff;
141 if ($shadow && $full) {
142 $diff = ccache_compute_diff ($filename, $shadow);
143 }
144
145 if ($full) {
146 return { data => $res, changes => $diff };
147 }
148
149 return $res;
150 }
151
152 sub update_file {
153 my ($fileid, $data, @args) = @_;
154
155 my ($ccinfo, $filename) = ccache_info($fileid);
156
157 my $update = $ccinfo->{update};
158
159 die "unable to update/merge data" if !$update;
160
161 my $lkfn = "$filename.lock";
162
163 my $timeout = 10;
164
165 my $fd;
166
167 my $code = sub {
168
169 $fd = IO::File->new ($filename, "r");
170
171 my $new = &$update($filename, $fd, $data, @args);
172
173 if (defined($new)) {
174 PVE::Tools::file_set_contents($filename, $new, $ccinfo->{perm});
175 } else {
176 unlink $filename;
177 }
178 };
179
180 PVE::Tools::lock_file($lkfn, $timeout, $code);
181 my $err = $@;
182
183 close($fd) if defined($fd);
184
185 die $err if $err;
186
187 return undef;
188 }
189
190 sub discard_changes {
191 my ($fileid, $full) = @_;
192
193 my ($ccinfo, $filename) = ccache_info($fileid);
194
195 if (my $copy = $shadowfiles->{$filename}) {
196 unlink $copy;
197 }
198
199 return read_file ($filename, $full);
200 }
201
202 sub poll_changes {
203 my ($filename) = @_;
204
205 poll() if $inotify; # read new inotify events
206
207 $versions->{$filename} = 0 if !defined ($versions->{$filename});
208
209 return $versions->{$filename};
210 }
211
212 sub read_file {
213 my ($fileid, $full) = @_;
214
215 my $parser;
216
217 my ($ccinfo, $filename) = ccache_info($fileid);
218
219 $parser = $ccinfo->{parser};
220
221 my $fd;
222 my $shadow;
223
224 my $cver = poll_changes($filename);
225
226 if (my $copy = $shadowfiles->{$filename}) {
227 if ($fd = IO::File->new ($copy, "r")) {
228 $shadow = $copy;
229 } else {
230 $fd = IO::File->new ($filename, "r");
231 }
232 } else {
233 $fd = IO::File->new ($filename, "r");
234 }
235
236 my $acp = $ccinfo->{always_call_parser};
237
238 if (!$fd) {
239 $ccinfo->{version} = undef;
240 $ccinfo->{data} = undef;
241 $ccinfo->{diff} = undef;
242 return undef if !$acp;
243 }
244
245 my $noclone = $ccinfo->{noclone};
246
247 # file unchanged?
248 if (!$ccinfo->{nocache} &&
249 $inotify && $cver &&
250 defined ($ccinfo->{data}) &&
251 defined ($ccinfo->{version}) &&
252 ($ccinfo->{readonce} ||
253 ($ccinfo->{version} == $cver))) {
254
255 my $ret;
256 if (!$noclone && ref ($ccinfo->{data})) {
257 $ret->{data} = clone ($ccinfo->{data});
258 } else {
259 $ret->{data} = $ccinfo->{data};
260 }
261 $ret->{changes} = $ccinfo->{diff};
262
263 return $full ? $ret : $ret->{data};
264 }
265
266 my $diff;
267
268 if ($shadow) {
269 $diff = ccache_compute_diff ($filename, $shadow);
270 }
271
272 my $res = &$parser($filename, $fd);
273
274 if (!$ccinfo->{nocache}) {
275 $ccinfo->{version} = $cver;
276 }
277
278 # we cache data with references, so we always need to
279 # clone this data. Else the original data may get
280 # modified.
281 $ccinfo->{data} = $res;
282
283 # also store diff
284 $ccinfo->{diff} = $diff;
285
286 my $ret;
287 if (!$noclone && ref ($ccinfo->{data})) {
288 $ret->{data} = clone ($ccinfo->{data});
289 } else {
290 $ret->{data} = $ccinfo->{data};
291 }
292 $ret->{changes} = $ccinfo->{diff};
293
294 return $full ? $ret : $ret->{data};
295 }
296
297 sub parse_ccache_options {
298 my ($ccinfo, %options) = @_;
299
300 foreach my $opt (keys %options) {
301 my $v = $options{$opt};
302 if ($opt eq 'readonce') {
303 $ccinfo->{$opt} = $v;
304 } elsif ($opt eq 'nocache') {
305 $ccinfo->{$opt} = $v;
306 } elsif ($opt eq 'shadow') {
307 $ccinfo->{$opt} = $v;
308 } elsif ($opt eq 'perm') {
309 $ccinfo->{$opt} = $v;
310 } elsif ($opt eq 'noclone') {
311 # noclone flag for large read-only data chunks like aplinfo
312 $ccinfo->{$opt} = $v;
313 } elsif ($opt eq 'always_call_parser') {
314 # when set, we call parser even when the file does not exists.
315 # this allows the parser to return some default
316 $ccinfo->{$opt} = $v;
317 } else {
318 die "internal error - unsupported option '$opt'";
319 }
320 }
321 }
322
323 sub register_file {
324 my ($id, $filename, $parser, $writer, $update, %options) = @_;
325
326 die "can't register file '$filename' after inotify_init" if $inotify;
327
328 die "file '$filename' already added :ERROR" if defined ($ccache->{$filename});
329 die "ID '$id' already used :ERROR" if defined ($ccachemap->{$id});
330
331 my $ccinfo = {};
332
333 $ccinfo->{id} = $id;
334 $ccinfo->{parser} = $parser || \&ccache_default_parser;
335 $ccinfo->{writer} = $writer || \&ccache_default_writer;
336 $ccinfo->{update} = $update;
337
338 parse_ccache_options($ccinfo, %options);
339
340 if ($options{shadow}) {
341 $shadowfiles->{$filename} = $options{shadow};
342 }
343
344 $ccachemap->{$id} = $filename;
345 $ccache->{$filename} = $ccinfo;
346 }
347
348 sub register_regex {
349 my ($dir, $regex, $parser, $writer, $update, %options) = @_;
350
351 die "can't register regex after inotify_init" if $inotify;
352
353 my $uid = "$dir/$regex";
354 die "regular expression '$uid' already added :ERROR" if defined ($ccacheregex->{$uid});
355
356 my $ccinfo = {};
357
358 $ccinfo->{dir} = $dir;
359 $ccinfo->{regex} = $regex;
360 $ccinfo->{parser} = $parser || \&ccache_default_parser;
361 $ccinfo->{writer} = $writer || \&ccache_default_writer;
362 $ccinfo->{update} = $update;
363
364 parse_ccache_options($ccinfo, %options);
365
366 $ccacheregex->{$uid} = $ccinfo;
367 }
368
369 sub poll {
370 return if !$inotify;
371
372 if ($inotify_pid != $$) {
373 syslog ('err', "got inotify poll request in wrong process - disabling inotify");
374 $inotify = undef;
375 } else {
376 1 while $inotify && $inotify->poll;
377 }
378 }
379
380 sub flushcache {
381 foreach my $filename (keys %$ccache) {
382 $ccache->{$filename}->{version} = undef;
383 $ccache->{$filename}->{data} = undef;
384 $ccache->{$filename}->{diff} = undef;
385 }
386 }
387
388 sub inotify_close {
389 $inotify = undef;
390 }
391
392 sub inotify_init {
393
394 die "only one inotify instance allowed" if $inotify;
395
396 $inotify = Linux::Inotify2->new()
397 || die "Unable to create new inotify object: $!";
398
399 $inotify->blocking (0);
400
401 $versions = {};
402
403 my $dirhash = {};
404 foreach my $fn (keys %$ccache) {
405 my $dir = dirname ($fn);
406 my $base = basename ($fn);
407
408 $dirhash->{$dir}->{$base} = $fn;
409
410 if (my $sf = $shadowfiles->{$fn}) {
411 $base = basename ($sf);
412 $dir = dirname ($sf);
413 $dirhash->{$dir}->{$base} = $fn; # change version of original file!
414 }
415 }
416
417 foreach my $uid (keys %$ccacheregex) {
418 my $ccinfo = $ccacheregex->{$uid};
419 $dirhash->{$ccinfo->{dir}}->{_regex} = 1;
420 }
421
422 $inotify_pid = $$;
423
424 foreach my $dir (keys %$dirhash) {
425
426 my $evlist = IN_MODIFY|IN_ATTRIB|IN_MOVED_FROM|IN_MOVED_TO|IN_DELETE|IN_CREATE;
427 $inotify->watch ($dir, $evlist, sub {
428 my $e = shift;
429 my $name = $e->name;
430
431 if ($inotify_pid != $$) {
432 syslog ('err', "got inotify event in wrong process");
433 }
434
435 if ($e->IN_ISDIR || !$name) {
436 return;
437 }
438
439 if ($e->IN_Q_OVERFLOW) {
440 syslog ('info', "got inotify overflow - flushing cache");
441 flushcache();
442 return;
443 }
444
445 if ($e->IN_UNMOUNT) {
446 syslog ('err', "got 'unmount' event on '$name' - disabling inotify");
447 $inotify = undef;
448 }
449 if ($e->IN_IGNORED) {
450 syslog ('err', "got 'ignored' event on '$name' - disabling inotify");
451 $inotify = undef;
452 }
453
454 if ($dirhash->{$dir}->{_regex}) {
455 foreach my $uid (keys %$ccacheregex) {
456 my $ccinfo = $ccacheregex->{$uid};
457 next if $dir ne $ccinfo->{dir};
458 my $regex = $ccinfo->{regex};
459 if ($regex && ($name =~ m|^$regex$|)) {
460
461 my $fn = "$dir/$name";
462 $versions->{$fn}++;
463 #print "VERSION:$fn:$versions->{$fn}\n";
464 }
465 }
466 } elsif (my $fn = $dirhash->{$dir}->{$name}) {
467
468 $versions->{$fn}++;
469 #print "VERSION:$fn:$versions->{$fn}\n";
470 }
471 });
472 }
473
474 foreach my $dir (keys %$dirhash) {
475 foreach my $name (keys %{$dirhash->{$dir}}) {
476 if ($name eq '_regex') {
477 foreach my $uid (keys %$ccacheregex) {
478 my $ccinfo = $ccacheregex->{$uid};
479 next if $dir ne $ccinfo->{dir};
480 my $re = $ccinfo->{regex};
481 if (my $fd = IO::Dir->new ($dir)) {
482 while (defined(my $de = $fd->read)) {
483 if ($de =~ m/^$re$/) {
484 my $fn = "$dir/$de";
485 $versions->{$fn}++; # init with version
486 #print "init:$fn:$versions->{$fn}\n";
487 }
488 }
489 }
490 }
491 } else {
492 my $fn = $dirhash->{$dir}->{$name};
493 $versions->{$fn}++; # init with version
494 #print "init:$fn:$versions->{$fn}\n";
495 }
496 }
497 }
498 }
499
500 my $cached_nodename;
501
502 sub nodename {
503
504 return $cached_nodename if $cached_nodename;
505
506 my ($sysname, $nodename) = POSIX::uname();
507
508 $nodename =~ s/\..*$//; # strip domain part, if any
509
510 die "unable to read node name\n" if !$nodename;
511
512 $cached_nodename = $nodename;
513
514 return $cached_nodename;
515 }
516
517 sub read_etc_hostname {
518 my ($filename, $fd) = @_;
519
520 my $hostname = <$fd>;
521
522 chomp $hostname;
523
524 $hostname =~ s/\..*$//; # strip domain part, if any
525
526 return $hostname;
527 }
528
529 sub write_etc_hostname {
530 my ($filename, $fh, $hostname) = @_;
531
532 die "write failed: $!" unless print $fh "$hostname\n";
533
534 return $hostname;
535 }
536
537 register_file('hostname', "/etc/hostname",
538 \&read_etc_hostname,
539 \&write_etc_hostname);
540
541 sub read_etc_resolv_conf {
542 my ($filename, $fh) = @_;
543
544 my $res = {};
545
546 my $nscount = 0;
547 while (my $line = <$fh>) {
548 chomp $line;
549 if ($line =~ m/^(search|domain)\s+(\S+)\s*/) {
550 $res->{search} = $2;
551 } elsif ($line =~ m/^\s*nameserver\s+($PVE::Tools::IPRE)\s*/) {
552 $nscount++;
553 if ($nscount <= 3) {
554 $res->{"dns$nscount"} = $1;
555 }
556 }
557 }
558
559 return $res;
560 }
561
562 sub update_etc_resolv_conf {
563 my ($filename, $fh, $resolv, @args) = @_;
564
565 my $data = "";
566
567 $data = "search $resolv->{search}\n"
568 if $resolv->{search};
569
570 my $written = {};
571 foreach my $k ("dns1", "dns2", "dns3") {
572 my $ns = $resolv->{$k};
573 if ($ns && $ns ne '0.0.0.0' && !$written->{$ns}) {
574 $written->{$ns} = 1;
575 $data .= "nameserver $ns\n";
576 }
577 }
578
579 while (my $line = <$fh>) {
580 next if $line =~ m/^(search|domain|nameserver)\s+/;
581 $data .= $line
582 }
583
584 return $data;
585 }
586
587 register_file('resolvconf', "/etc/resolv.conf",
588 \&read_etc_resolv_conf, undef,
589 \&update_etc_resolv_conf);
590
591 sub read_etc_timezone {
592 my ($filename, $fd) = @_;
593
594 my $timezone = <$fd>;
595
596 chomp $timezone;
597
598 return $timezone;
599 }
600
601 sub write_etc_timezone {
602 my ($filename, $fh, $timezone) = @_;
603
604 my $tzinfo = "/usr/share/zoneinfo/$timezone";
605
606 raise_param_exc({ 'timezone' => "No such timezone" })
607 if (! -f $tzinfo);
608
609 ($timezone) = $timezone =~ m/^(.*)$/; # untaint
610
611 print $fh "$timezone\n";
612
613 unlink ("/etc/localtime");
614 symlink ("/usr/share/zoneinfo/$timezone", "/etc/localtime");
615
616 }
617
618 register_file('timezone', "/etc/timezone",
619 \&read_etc_timezone,
620 \&write_etc_timezone);
621
622 sub read_active_workers {
623 my ($filename, $fh) = @_;
624
625 return [] if !$fh;
626
627 my $res = [];
628 while (defined (my $line = <$fh>)) {
629 if ($line =~ m/^(\S+)\s(0|1)(\s([0-9A-Za-z]{8})(\s(\s*\S.*))?)?$/) {
630 my $upid = $1;
631 my $saved = $2;
632 my $endtime = $4;
633 my $status = $6;
634 if ((my $task = PVE::Tools::upid_decode($upid, 1))) {
635 $task->{upid} = $upid;
636 $task->{saved} = $saved;
637 $task->{endtime} = hex($endtime) if $endtime;
638 $task->{status} = $status if $status;
639 push @$res, $task;
640 }
641 } else {
642 warn "unable to parse line: $line";
643 }
644 }
645
646 return $res;
647
648 }
649
650 sub write_active_workers {
651 my ($filename, $fh, $tasklist) = @_;
652
653 my $raw = '';
654 foreach my $task (@$tasklist) {
655 my $upid = $task->{upid};
656 my $saved = $task->{saved} ? 1 : 0;
657 if ($task->{endtime}) {
658 if ($task->{status}) {
659 $raw .= sprintf("%s %s %08X %s\n", $upid, $saved, $task->{endtime}, $task->{status});
660 } else {
661 $raw .= sprintf("%s %s %08X\n", $upid, $saved, $task->{endtime});
662 }
663 } else {
664 $raw .= "$upid $saved\n";
665 }
666 }
667
668 PVE::Tools::safe_print($filename, $fh, $raw) if $raw;
669 }
670
671 register_file('active', "/var/log/pve/tasks/active",
672 \&read_active_workers,
673 \&write_active_workers);
674
675
676 our $bond_modes = { 'balance-rr' => 0,
677 'active-backup' => 1,
678 'balance-xor' => 2,
679 'broadcast' => 3,
680 '802.3ad' => 4,
681 'balance-tlb' => 5,
682 'balance-alb' => 6,
683 };
684
685 my $ovs_bond_modes = {
686 'active-backup' => 1,
687 'balance-slb' => 1,
688 'lacp-balance-slb' => 1,
689 'lacp-balance-tcp' => 1,
690 };
691
692 #sub get_bond_modes {
693 # return $bond_modes;
694 #}
695
696 my $parse_ovs_option = sub {
697 my ($data) = @_;
698
699 my $opts = {};
700 foreach my $kv (split (/\s+/, $data || '')) {
701 my ($k, $v) = split('=', $kv, 2);
702 $opts->{$k} = $v if $k && $v;
703 }
704 return $opts;
705 };
706
707 my $set_ovs_option = sub {
708 my ($d, %params) = @_;
709
710 my $opts = &$parse_ovs_option($d->{ovs_options});
711
712 foreach my $k (keys %params) {
713 my $v = $params{$k};
714 if ($v) {
715 $opts->{$k} = $v;
716 } else {
717 delete $opts->{$k};
718 }
719 }
720
721 my $res = [];
722 foreach my $k (keys %$opts) {
723 push @$res, "$k=$opts->{$k}";
724 }
725
726 if (my $new = join(' ', @$res)) {
727 $d->{ovs_options} = $new;
728 return $d->{ovs_options};
729 } else {
730 delete $d->{ovs_options};
731 return undef;
732 }
733 };
734
735 my $extract_ovs_option = sub {
736 my ($d, $name) = @_;
737
738 my $opts = &$parse_ovs_option($d->{ovs_options});
739
740 my $v = delete $opts->{$name};
741
742 my $res = [];
743 foreach my $k (keys %$opts) {
744 push @$res, "$k=$opts->{$k}";
745 }
746
747 if (my $new = join(' ', @$res)) {
748 $d->{ovs_options} = $new;
749 } else {
750 delete $d->{ovs_options};
751 }
752
753 return $v;
754 };
755
756 # config => {
757 # ifaces => {
758 # $ifname => {
759 # <optional> exists => BOOL,
760 # <optional> active => BOOL,
761 # <optional> autostart => BOOL,
762 # <auto> priority => INT,
763 #
764 # type => "eth" | "bridge" | "bond" | "loopback" | "OVS*" | ... ,
765 #
766 # families => ["inet", "inet6", ...],
767 #
768 # method => "manual" | "static" | "dhcp" | ... ,
769 # address => IP,
770 # netmask => SUBNET,
771 # broadcast => IP,
772 # gateway => IP,
773 # comments => [ "..." ],
774 #
775 # method6 => "manual" | "static" | "dhcp" | ... ,
776 # address6 => IP,
777 # netmask6 => SUBNET,
778 # gateway6 => IP,
779 # comments6 => [ "..." ],
780 #
781 # <known options>, # like bridge_ports, ovs_*
782 #
783 # # extra/unknown options stored by-family:
784 # options => { <inet options>... }
785 # options6 => { <inet6 options>... }
786 # }
787 # },
788 # options => [
789 # # mappings end up here as well, as we don't need to understand them
790 # [priority,line]
791 # ]
792 # }
793 sub read_etc_network_interfaces {
794 my ($filename, $fh) = @_;
795 my $proc_net_dev = IO::File->new('/proc/net/dev', 'r');
796 my $active = PVE::ProcFSTools::get_active_network_interfaces();
797 return __read_etc_network_interfaces($fh, $proc_net_dev, $active);
798 }
799
800 sub __read_etc_network_interfaces {
801 my ($fh, $proc_net_dev, $active_ifaces) = @_;
802
803 my $config = {};
804 my $ifaces = $config->{ifaces} = {};
805 my $options = $config->{options} = [];
806
807 my $options_alternatives = {
808 'bond-slaves' => 'slaves',
809 'bond_slaves' => 'slaves',
810 'bond-xmit-hash-policy' => 'bond_xmit_hash_policy',
811 'bond-mode' => 'bond_mode',
812 'bond-miimon' =>'bond_miimon',
813 'bridge-vlan-aware' => 'bridge_vlan_aware',
814 'bridge-fd' => 'bridge_fd',
815 'bridge-stp' => 'bridge_stp',
816 'bridge-ports' => 'bridge_ports',
817 'bridge-vids' => 'bridge_vids'
818 };
819
820 my $line;
821
822 if ($proc_net_dev) {
823 while (defined ($line = <$proc_net_dev>)) {
824 if ($line =~ m/^\s*($PVE::Network::PHYSICAL_NIC_RE):.*/) {
825 $ifaces->{$1}->{exists} = 1;
826 }
827 }
828 close($proc_net_dev);
829 }
830
831 # we try to keep order inside the file
832 my $priority = 2; # 1 is reserved for lo
833
834 SECTION: while (defined ($line = <$fh>)) {
835 chomp ($line);
836 next if $line =~ m/^\s*#/;
837
838 if ($line =~ m/^\s*auto\s+(.*)$/) {
839 my @aa = split (/\s+/, $1);
840
841 foreach my $a (@aa) {
842 $ifaces->{$a}->{autostart} = 1;
843 }
844
845 } elsif ($line =~ m/^\s*iface\s+(\S+)\s+(inet6?)\s+(\S+)\s*$/) {
846 my $i = $1;
847 my $family = $2;
848 my $f = { method => $3 }; # by family, merged to $d with a $suffix
849 (my $suffix = $family) =~ s/^inet//;
850
851 my $d = $ifaces->{$i} ||= {};
852 $d->{priority} = $priority++ if !$d->{priority};
853 push @{$d->{families}}, $family;
854
855 while (defined ($line = <$fh>)) {
856 chomp $line;
857 if ($line =~ m/^\s*#(.*?)\s*$/) {
858 # NOTE: we use 'comments' instead of 'comment' to
859 # avoid automatic utf8 conversion
860 $f->{comments} = '' if !$f->{comments};
861 $f->{comments} .= "$1\n";
862 } elsif ($line =~ m/^\s*(?:iface\s
863 |mapping\s
864 |auto\s
865 |allow-
866 |source\s
867 |source-directory\s
868 )/x) {
869 last;
870 } elsif ($line =~ m/^\s*((\S+)\s+(.+))$/) {
871 my $option = $1;
872 my ($id, $value) = ($2, $3);
873
874 $id = $options_alternatives->{$id} if $options_alternatives->{$id};
875
876 if (($id eq 'address') || ($id eq 'netmask') || ($id eq 'broadcast') || ($id eq 'gateway')) {
877 $f->{$id} = $value;
878 } elsif ($id eq 'ovs_type' || $id eq 'ovs_options'|| $id eq 'ovs_bridge' ||
879 $id eq 'ovs_bonds' || $id eq 'ovs_ports') {
880 $d->{$id} = $value;
881 } elsif ($id eq 'slaves' || $id eq 'bridge_ports') {
882 my $devs = {};
883 foreach my $p (split (/\s+/, $value)) {
884 next if $p eq 'none';
885 $devs->{$p} = 1;
886 }
887 my $str = join (' ', sort keys %{$devs});
888 if ($d->{$id}) {
889 $d->{$id} .= ' ' . $str if $str;
890 } else {
891 $d->{$id} = $str || '';
892 }
893 } elsif ($id eq 'bridge_stp') {
894 if ($value =~ m/^\s*(on|yes)\s*$/i) {
895 $d->{$id} = 'on';
896 } else {
897 $d->{$id} = 'off';
898 }
899 } elsif ($id eq 'bridge_fd' || $id eq 'bridge_vids') {
900 $d->{$id} = $value;
901 } elsif ($id eq 'bridge_vlan_aware') {
902 $d->{$id} = 1;
903 } elsif ($id eq 'bond_miimon') {
904 $d->{$id} = $value;
905 } elsif ($id eq 'bond_xmit_hash_policy') {
906 $d->{$id} = $value;
907 } elsif ($id eq 'bond_mode') {
908 # always use names
909 foreach my $bm (keys %$bond_modes) {
910 my $id = $bond_modes->{$bm};
911 if ($id eq $value) {
912 $value = $bm;
913 last;
914 }
915 }
916 $d->{$id} = $value;
917 } elsif ($id eq 'vxlan-id' || $id eq 'vxlan-svcnodeip' ||
918 $id eq 'vxlan-physdev' || $id eq 'vxlan-local-tunnelip') {
919 $d->{$id} = $value;
920 } elsif ($id eq 'vxlan-remoteip') {
921 push @{$d->{$id}}, $value;
922 } else {
923 push @{$f->{options}}, $option;
924 }
925 } else {
926 last;
927 }
928 }
929 $d->{"$_$suffix"} = $f->{$_} foreach (keys %$f);
930 last SECTION if !defined($line);
931 redo SECTION;
932 } elsif ($line =~ /\w/) {
933 push @$options, [$priority++, $line];
934 }
935 }
936
937 foreach my $ifname (@$active_ifaces) {
938 if (my $iface = $ifaces->{$ifname}) {
939 $iface->{active} = 1;
940 }
941 }
942
943 if (!$ifaces->{lo}) {
944 $ifaces->{lo}->{priority} = 1;
945 $ifaces->{lo}->{method} = 'loopback';
946 $ifaces->{lo}->{type} = 'loopback';
947 $ifaces->{lo}->{autostart} = 1;
948 }
949
950 foreach my $iface (keys %$ifaces) {
951 my $d = $ifaces->{$iface};
952 if ($iface =~ m/^bond\d+$/) {
953 if (!$d->{ovs_type}) {
954 $d->{type} = 'bond';
955 } elsif ($d->{ovs_type} eq 'OVSBond') {
956 $d->{type} = $d->{ovs_type};
957 # translate: ovs_options => bond_mode
958 $d->{'bond_mode'} = &$extract_ovs_option($d, 'bond_mode');
959 my $lacp = &$extract_ovs_option($d, 'lacp');
960 if ($lacp && $lacp eq 'active') {
961 if ($d->{'bond_mode'} eq 'balance-slb') {
962 $d->{'bond_mode'} = 'lacp-balance-slb';
963 }
964 }
965 # Note: balance-tcp needs lacp
966 if ($d->{'bond_mode'} eq 'balance-tcp') {
967 $d->{'bond_mode'} = 'lacp-balance-tcp';
968 }
969 my $tag = &$extract_ovs_option($d, 'tag');
970 $d->{ovs_tag} = $tag if defined($tag);
971 } else {
972 $d->{type} = 'unknown';
973 }
974 } elsif ($iface =~ m/^vmbr\d+$/) {
975 if (!$d->{ovs_type}) {
976 $d->{type} = 'bridge';
977
978 if (!defined ($d->{bridge_fd})) {
979 $d->{bridge_fd} = 0;
980 }
981 if (!defined ($d->{bridge_stp})) {
982 $d->{bridge_stp} = 'off';
983 }
984 } elsif ($d->{ovs_type} eq 'OVSBridge') {
985 $d->{type} = $d->{ovs_type};
986 } else {
987 $d->{type} = 'unknown';
988 }
989 } elsif ($iface =~ m/^(\S+):\d+$/) {
990 $d->{type} = 'alias';
991 if (defined ($ifaces->{$1})) {
992 $d->{exists} = $ifaces->{$1}->{exists};
993 } else {
994 $ifaces->{$1}->{exists} = 0;
995 $d->{exists} = 0;
996 }
997 } elsif ($iface =~ m/^(\S+)\.\d+$/) {
998 $d->{type} = 'vlan';
999 if (defined ($ifaces->{$1})) {
1000 $d->{exists} = $ifaces->{$1}->{exists};
1001 } else {
1002 $ifaces->{$1}->{exists} = 0;
1003 $d->{exists} = 0;
1004 }
1005 } elsif ($iface =~ m/^$PVE::Network::PHYSICAL_NIC_RE$/) {
1006 if (!$d->{ovs_type}) {
1007 $d->{type} = 'eth';
1008 } elsif ($d->{ovs_type} eq 'OVSPort') {
1009 $d->{type} = $d->{ovs_type};
1010 my $tag = &$extract_ovs_option($d, 'tag');
1011 $d->{ovs_tag} = $tag if defined($tag);
1012 } else {
1013 $d->{type} = 'unknown';
1014 }
1015 } elsif ($iface =~ m/^lo$/) {
1016 $d->{type} = 'loopback';
1017 } else {
1018 if ($d->{'vxlan-id'}) {
1019 $d->{type} = 'vxlan';
1020 } elsif (!$d->{ovs_type}) {
1021 $d->{type} = 'unknown';
1022 } elsif ($d->{ovs_type} eq 'OVSIntPort') {
1023 $d->{type} = $d->{ovs_type};
1024 my $tag = &$extract_ovs_option($d, 'tag');
1025 $d->{ovs_tag} = $tag if defined($tag);
1026 }
1027 }
1028
1029 $d->{method} = 'manual' if !$d->{method};
1030 $d->{method6} = 'manual' if !$d->{method6};
1031
1032 $d->{families} ||= ['inet'];
1033 }
1034
1035 # OVS bridges create "allow-$BRIDGE $IFACE" lines which we need to remove
1036 # from the {options} hash for them to be removed correctly.
1037 @$options = grep {defined($_)} map {
1038 my ($pri, $line) = @$_;
1039 if ($line =~ /^allow-(\S+)\s+(.*)$/) {
1040 my $bridge = $1;
1041 my @ports = split(/\s+/, $2);
1042 if (defined(my $br = $ifaces->{$bridge})) {
1043 # if this port is part of a bridge, remove it
1044 my %in_ovs_ports = map {$_=>1} split(/\s+/, $br->{ovs_ports});
1045 @ports = grep { not $in_ovs_ports{$_} } @ports;
1046 }
1047 # create the allow line for the remaining ports, or delete if empty
1048 if (@ports) {
1049 [$pri, "allow-$bridge " . join(' ', @ports)];
1050 } else {
1051 undef;
1052 }
1053 } else {
1054 # don't modify other lines
1055 $_;
1056 }
1057 } @$options;
1058
1059 return $config;
1060 }
1061
1062 sub __interface_to_string {
1063 my ($iface, $d, $family, $first_block, $ifupdown2) = @_;
1064
1065 (my $suffix = $family) =~ s/^inet//;
1066
1067 return '' if !($d && $d->{"method$suffix"});
1068
1069 my $raw = '';
1070
1071 $raw .= "iface $iface $family " . $d->{"method$suffix"} . "\n";
1072 $raw .= "\taddress " . $d->{"address$suffix"} . "\n" if $d->{"address$suffix"};
1073 $raw .= "\tnetmask " . $d->{"netmask$suffix"} . "\n" if $d->{"netmask$suffix"};
1074 $raw .= "\tgateway " . $d->{"gateway$suffix"} . "\n" if $d->{"gateway$suffix"};
1075 $raw .= "\tbroadcast " . $d->{"broadcast$suffix"} . "\n" if $d->{"broadcast$suffix"};
1076
1077 my $done = { type => 1, priority => 1, method => 1, active => 1, exists => 1,
1078 comments => 1, autostart => 1, options => 1,
1079 address => 1, netmask => 1, gateway => 1, broadcast => 1,
1080 method6 => 1, families => 1, options6 => 1,
1081 address6 => 1, netmask6 => 1, gateway6 => 1, broadcast6 => 1 };
1082
1083 if (!$first_block) {
1084 # not printing out options
1085 } elsif ($d->{type} eq 'bridge') {
1086
1087 $d->{bridge_ports} =~ s/[;,\s]+/ /g;
1088 my $ports = $d->{bridge_ports} || 'none';
1089 $raw .= "\tbridge-ports $ports\n";
1090 $done->{bridge_ports} = 1;
1091
1092 my $v = defined($d->{bridge_stp}) ? $d->{bridge_stp} : 'off';
1093 $raw .= "\tbridge-stp $v\n";
1094 $done->{bridge_stp} = 1;
1095
1096 $v = defined($d->{bridge_fd}) ? $d->{bridge_fd} : 0;
1097 $raw .= "\tbridge-fd $v\n";
1098 $done->{bridge_fd} = 1;
1099
1100 if( defined($d->{bridge_vlan_aware})) {
1101 $raw .= "\tbridge-vlan-aware yes\n";
1102 $v = defined($d->{bridge_vids}) ? $d->{bridge_vids} : "2-4094";
1103 $raw .= "\tbridge-vids $v\n";
1104 }
1105 $done->{bridge_vlan_aware} = 1;
1106 $done->{bridge_vids} = 1;
1107
1108 } elsif ($d->{type} eq 'bond') {
1109
1110 $d->{slaves} =~ s/[;,\s]+/ /g;
1111 my $slaves = $d->{slaves} || 'none';
1112 $raw .= "\tbond-slaves $slaves\n";
1113 $done->{slaves} = 1;
1114
1115 my $v = defined ($d->{'bond_miimon'}) ? $d->{'bond_miimon'} : 100;
1116 $raw .= "\tbond-miimon $v\n";
1117 $done->{'bond_miimon'} = 1;
1118
1119 $v = defined ($d->{'bond_mode'}) ? $d->{'bond_mode'} : 'balance-rr';
1120 $raw .= "\tbond-mode $v\n";
1121 $done->{'bond_mode'} = 1;
1122
1123 if ($d->{'bond_mode'} && $d->{'bond_xmit_hash_policy'} &&
1124 ($d->{'bond_mode'} eq 'balance-xor' || $d->{'bond_mode'} eq '802.3ad')) {
1125 $raw .= "\tbond-xmit-hash-policy $d->{'bond_xmit_hash_policy'}\n";
1126 }
1127 $done->{'bond_xmit_hash_policy'} = 1;
1128 } elsif ($d->{type} eq 'vxlan') {
1129
1130 foreach my $k (qw(vxlan-id vxlan-svcnodeip vxlan-physdev vxlan-local-tunnelip)) {
1131 $raw .= "\t$k $d->{$k}\n" if $d->{$k};
1132 $done->{$k} = 1;
1133 }
1134
1135 if ($d->{'vxlan-remoteip'}) {
1136 foreach my $remoteip (@{$d->{'vxlan-remoteip'}}) {
1137 $raw .= "\tvxlan-remoteip $remoteip\n";
1138 }
1139 $done->{'vxlan-remoteip'} = 1;
1140 }
1141
1142 } elsif ($d->{type} eq 'OVSBridge') {
1143
1144 $raw .= "\tovs_type $d->{type}\n";
1145 $done->{ovs_type} = 1;
1146
1147 $raw .= "\tovs_ports $d->{ovs_ports}\n" if $d->{ovs_ports};
1148 $done->{ovs_ports} = 1;
1149 } elsif ($d->{type} eq 'OVSPort' || $d->{type} eq 'OVSIntPort' ||
1150 $d->{type} eq 'OVSBond') {
1151
1152 $d->{autostart} = 0; # started by the bridge
1153
1154 if (defined($d->{ovs_tag})) {
1155 &$set_ovs_option($d, tag => $d->{ovs_tag});
1156 }
1157 $done->{ovs_tag} = 1;
1158
1159 if ($d->{type} eq 'OVSBond') {
1160
1161 $d->{bond_mode} = 'active-backup' if !$d->{bond_mode};
1162
1163 $ovs_bond_modes->{$d->{bond_mode}} ||
1164 die "OVS does not support bond mode '$d->{bond_mode}\n";
1165
1166 if ($d->{bond_mode} eq 'lacp-balance-slb') {
1167 &$set_ovs_option($d, lacp => 'active');
1168 &$set_ovs_option($d, bond_mode => 'balance-slb');
1169 } elsif ($d->{bond_mode} eq 'lacp-balance-tcp') {
1170 &$set_ovs_option($d, lacp => 'active');
1171 &$set_ovs_option($d, bond_mode => 'balance-tcp');
1172 } else {
1173 &$set_ovs_option($d, lacp => undef);
1174 &$set_ovs_option($d, bond_mode => $d->{bond_mode});
1175 }
1176 $done->{bond_mode} = 1;
1177
1178 $raw .= "\tovs_bonds $d->{ovs_bonds}\n" if $d->{ovs_bonds};
1179 $done->{ovs_bonds} = 1;
1180 }
1181
1182 $raw .= "\tovs_type $d->{type}\n";
1183 $done->{ovs_type} = 1;
1184
1185 if ($d->{ovs_bridge}) {
1186
1187 if ($ifupdown2) {
1188 $raw = "auto $iface\n$raw";
1189 } else {
1190 $raw = "allow-$d->{ovs_bridge} $iface\n$raw";
1191 }
1192
1193 $raw .= "\tovs_bridge $d->{ovs_bridge}\n";
1194 $done->{ovs_bridge} = 1;
1195 }
1196 }
1197
1198 if ($first_block) {
1199 # print other settings
1200 foreach my $k (keys %$d) {
1201 next if $done->{$k};
1202 next if !$d->{$k};
1203 $raw .= "\t$k $d->{$k}\n";
1204 }
1205 }
1206
1207 foreach my $option (@{$d->{"options$suffix"}}) {
1208 $raw .= "\t$option\n";
1209 }
1210
1211 # add comments
1212 my $comments = $d->{"comments$suffix"} || '';
1213 foreach my $cl (split(/\n/, $comments)) {
1214 $raw .= "#$cl\n";
1215 }
1216
1217 $raw .= "\n";
1218
1219 return $raw;
1220 }
1221
1222
1223 sub write_etc_network_interfaces {
1224 my ($filename, $fh, $config) = @_;
1225 my $ifupdown2 = -e '/usr/share/ifupdown2';
1226 my $raw = __write_etc_network_interfaces($config, $ifupdown2);
1227 PVE::Tools::safe_print($filename, $fh, $raw);
1228 }
1229 sub __write_etc_network_interfaces {
1230 my ($config, $ifupdown2) = @_;
1231
1232 my $ifaces = $config->{ifaces};
1233 my @options = @{$config->{options}};
1234
1235 my $used_ports = {};
1236
1237 foreach my $iface (keys %$ifaces) {
1238 my $d = $ifaces->{$iface};
1239
1240 my $ports = '';
1241 foreach my $k (qw(bridge_ports ovs_ports slaves ovs_bonds)) {
1242 $ports .= " $d->{$k}" if $d->{$k};
1243 }
1244
1245 foreach my $p (PVE::Tools::split_list($ports)) {
1246 die "port '$p' is already used on interface '$used_ports->{$p}'\n"
1247 if $used_ports->{$p} && $used_ports->{$p} ne $iface;
1248 $used_ports->{$p} = $iface;
1249 }
1250 }
1251
1252 # delete unused OVS ports
1253 foreach my $iface (keys %$ifaces) {
1254 my $d = $ifaces->{$iface};
1255 if ($d->{type} eq 'OVSPort' || $d->{type} eq 'OVSIntPort' ||
1256 $d->{type} eq 'OVSBond') {
1257 my $brname = $used_ports->{$iface};
1258 if (!$brname || !$ifaces->{$brname}) {
1259 if ($iface =~ /^$PVE::Network::PHYSICAL_NIC_RE/) {
1260 $ifaces->{$iface} = { type => 'eth',
1261 exists => 1,
1262 method => 'manual',
1263 families => ['inet'] };
1264 } else {
1265 delete $ifaces->{$iface};
1266 }
1267 next;
1268 }
1269 my $bd = $ifaces->{$brname};
1270 if ($bd->{type} ne 'OVSBridge') {
1271 delete $ifaces->{$iface};
1272 next;
1273 }
1274 }
1275 }
1276
1277 # create OVS bridge ports
1278 foreach my $iface (keys %$ifaces) {
1279 my $d = $ifaces->{$iface};
1280 if ($d->{type} eq 'OVSBridge' && $d->{ovs_ports}) {
1281 foreach my $p (split (/\s+/, $d->{ovs_ports})) {
1282 my $n = $ifaces->{$p};
1283 die "OVS bridge '$iface' - unable to find port '$p'\n"
1284 if !$n;
1285 $n->{autostart} = 0;
1286 if ($n->{type} eq 'eth') {
1287 $n->{type} = 'OVSPort';
1288 $n->{ovs_bridge} = $iface;
1289 } elsif ($n->{type} eq 'OVSBond' || $n->{type} eq 'OVSPort' ||
1290 $n->{type} eq 'OVSIntPort') {
1291 $n->{ovs_bridge} = $iface;
1292 } else {
1293 die "interface '$p' is not defined as OVS port/bond\n";
1294 }
1295 }
1296 }
1297 }
1298
1299 # check OVS bond ports
1300 foreach my $iface (keys %$ifaces) {
1301 my $d = $ifaces->{$iface};
1302 if ($d->{type} eq 'OVSBond' && $d->{ovs_bonds}) {
1303 foreach my $p (split (/\s+/, $d->{ovs_bonds})) {
1304 my $n = $ifaces->{$p};
1305 die "OVS bond '$iface' - unable to find slave '$p'\n"
1306 if !$n;
1307 die "OVS bond '$iface' - wrong interface type on slave '$p' " .
1308 "('$n->{type}' != 'eth')\n" if $n->{type} ne 'eth';
1309 }
1310 }
1311 }
1312
1313 # check vxlan
1314 my $vxlans = {};
1315 foreach my $iface (keys %$ifaces) {
1316 my $d = $ifaces->{$iface};
1317
1318 if ($d->{type} eq 'vxlan' && $d->{'vxlan-id'}) {
1319 my $vxlanid = $d->{'vxlan-id'};
1320 die "iface $iface : duplicate vxlan-id $vxlanid already used in $vxlans->{$vxlanid}\n" if $vxlans->{$vxlanid};
1321 $vxlans->{$vxlanid} = $iface;
1322 }
1323
1324 my $ips = 0;
1325 ++$ips if defined $d->{'vxlan-svcnodeip'};
1326 ++$ips if defined $d->{'vxlan-remoteip'};
1327 ++$ips if defined $d->{'vxlan-local-tunnelip'};
1328 if ($ips > 1) {
1329 die "ifac $iface : vxlan-svcnodeip, vxlan-remoteip and vxlan-localtunnelip are mutually exclusive\n";
1330 }
1331
1332 if (defined($d->{'vxlan-svcnodeip'}) != defined($d->{'vxlan-physdev'})) {
1333 die "iface $iface : vxlan-svcnodeip and vxlan-physdev must be define together\n";
1334 }
1335 }
1336
1337 my $raw = <<'NETWORKDOC';
1338 # network interface settings; autogenerated
1339 # Please do NOT modify this file directly, unless you know what
1340 # you're doing.
1341 #
1342 # If you want to manage part of the network configuration manually,
1343 # please utilize the 'source' or 'source-directory' directives to do
1344 # so.
1345 # PVE will preserve these directives, but will NOT its network
1346 # configuration from sourced files, so do not attempt to move any of
1347 # the PVE managed interfaces into external files!
1348
1349 NETWORKDOC
1350
1351 my $printed = {};
1352
1353 my $if_type_hash = {
1354 loopback => 100000,
1355 eth => 200000,
1356 bond => 300000,
1357 bridge => 400000,
1358 vxlan => 500000,
1359 };
1360
1361 my $lookup_type_prio = sub {
1362 my $iface = shift;
1363
1364 my $child = 0;
1365 if ($iface =~ m/^(\S+)(\.|:)\d+$/) {
1366 $iface = $1;
1367 $child = 1;
1368 }
1369
1370 my $pri;
1371 if ($iface eq 'lo') {
1372 $pri = $if_type_hash->{loopback};
1373 } elsif ($iface =~ m/^$PVE::Network::PHYSICAL_NIC_RE$/) {
1374 $pri = $if_type_hash->{eth} + $child;
1375 } elsif ($iface =~ m/^bond\d+$/) {
1376 $pri = $if_type_hash->{bond} + $child;
1377 } elsif ($iface =~ m/^vmbr\d+$/) {
1378 $pri = $if_type_hash->{bridge} + $child;
1379 }
1380
1381 return $pri;
1382 };
1383
1384 foreach my $iface (sort {
1385 my $ref1 = $ifaces->{$a};
1386 my $ref2 = $ifaces->{$b};
1387 my $tp1 = &$lookup_type_prio($a);
1388 my $tp2 = &$lookup_type_prio($b);
1389
1390 # Only recognized types are in relation to each other. If one type
1391 # is unknown then only consider the interfaces' priority attributes.
1392 $tp1 = $tp2 = 0 if !defined($tp1) || !defined($tp2);
1393
1394 my $p1 = $tp1 + ($ref1->{priority} // 50000);
1395 my $p2 = $tp2 + ($ref2->{priority} // 50000);
1396
1397 return $p1 <=> $p2 if $p1 != $p2;
1398
1399 return $a cmp $b;
1400 } keys %$ifaces) {
1401 next if $printed->{$iface};
1402
1403 my $d = $ifaces->{$iface};
1404 my $pri = $d->{priority} // 0;
1405 if (@options && $options[0]->[0] < $pri) {
1406 do {
1407 $raw .= (shift @options)->[1] . "\n";
1408 } while (@options && $options[0]->[0] < $pri);
1409 $raw .= "\n";
1410 }
1411
1412 $printed->{$iface} = 1;
1413 $raw .= "auto $iface\n" if $d->{autostart};
1414 my $i = 0; # some options should be printed only once
1415 $raw .= __interface_to_string($iface, $d, $_, !$i++, $ifupdown2) foreach @{$d->{families}};
1416 }
1417
1418 $raw .= $_->[1] . "\n" foreach @options;
1419 return $raw;
1420 }
1421
1422 register_file('interfaces', "/etc/network/interfaces",
1423 \&read_etc_network_interfaces,
1424 \&write_etc_network_interfaces);
1425
1426
1427 sub read_iscsi_initiatorname {
1428 my ($filename, $fd) = @_;
1429
1430 while (defined(my $line = <$fd>)) {
1431 if ($line =~ m/^InitiatorName=(\S+)$/) {
1432 return $1;
1433 }
1434 }
1435
1436 return 'undefined';
1437 }
1438
1439 register_file('initiatorname', "/etc/iscsi/initiatorname.iscsi",
1440 \&read_iscsi_initiatorname);
1441
1442 sub read_apt_auth {
1443 my ($filename, $fd) = @_;
1444
1445 local $/;
1446
1447 my $raw = defined($fd) ? <$fd> : '';
1448
1449 $raw =~ s/^\s+//;
1450
1451
1452 my @tokens = split(/\s+/, $raw);
1453
1454 my $data = {};
1455
1456 my $machine;
1457 while (defined(my $tok = shift @tokens)) {
1458
1459 $machine = shift @tokens if $tok eq 'machine';
1460 next if !$machine;
1461 $data->{$machine} = {} if !$data->{$machine};
1462
1463 $data->{$machine}->{login} = shift @tokens if $tok eq 'login';
1464 $data->{$machine}->{password} = shift @tokens if $tok eq 'password';
1465 };
1466
1467 return $data;
1468 }
1469
1470 my $format_apt_auth_data = sub {
1471 my $data = shift;
1472
1473 my $raw = '';
1474
1475 foreach my $machine (sort keys %$data) {
1476 my $d = $data->{$machine};
1477 $raw .= "machine $machine\n";
1478 $raw .= " login $d->{login}\n" if $d->{login};
1479 $raw .= " password $d->{password}\n" if $d->{password};
1480 $raw .= "\n";
1481 }
1482
1483 return $raw;
1484 };
1485
1486 sub write_apt_auth {
1487 my ($filename, $fh, $data) = @_;
1488
1489 my $raw = &$format_apt_auth_data($data);
1490
1491 die "write failed: $!" unless print $fh "$raw\n";
1492
1493 return $data;
1494 }
1495
1496 sub update_apt_auth {
1497 my ($filename, $fh, $data) = @_;
1498
1499 my $orig = read_apt_auth($filename, $fh);
1500
1501 foreach my $machine (keys %$data) {
1502 $orig->{$machine} = $data->{$machine};
1503 }
1504
1505 return &$format_apt_auth_data($orig);
1506 }
1507
1508 register_file('apt-auth', "/etc/apt/auth.conf",
1509 \&read_apt_auth, \&write_apt_auth,
1510 \&update_apt_auth, perm => 0640);
1511
1512 1;