[pve-devel] [PATCH common 3/3] INotify.pm: add methods for reading/writing /etc/hosts

Dominik Csapak d.csapak at proxmox.com
Fri Aug 24 12:34:09 CEST 2018


Signed-off-by: Dominik Csapak <d.csapak at proxmox.com>
---
 src/PVE/INotify.pm | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)

diff --git a/src/PVE/INotify.pm b/src/PVE/INotify.pm
index cadd78f..dba4993 100644
--- a/src/PVE/INotify.pm
+++ b/src/PVE/INotify.pm
@@ -20,6 +20,7 @@ use Clone qw(clone);
 use Linux::Inotify2;
 use base 'Exporter';
 use JSON;
+use Digest::SHA;
 use Encode qw(encode decode);
 
 our @EXPORT_OK = qw(read_file write_file register_file);
@@ -539,6 +540,51 @@ register_file('hostname', "/etc/hostname",
 	      \&read_etc_hostname, 
 	      \&write_etc_hostname);
 
+sub read_etc_hosts {
+    my ($filename, $fh) = @_;
+
+    local $/ =  undef;
+
+    my $raw = <$fh>;
+
+    return {
+	digest => Digest::SHA::sha1_hex(encode('UTF-8', $raw)),
+	data => $raw,
+    }
+}
+
+sub write_etc_hosts {
+    my ($filename, $fh, $hosts, @args) = @_;
+
+    my $digest = Digest::SHA::sha1_hex(PVE::Tools::file_get_contents($filename));
+
+    PVE::Tools::assert_if_modified($hosts->{digest}, $digest);
+
+    # check validity of ips/names
+    for my $line (split("\n", $hosts->{data})) {
+	next if $line =~ m/^#/; # comments
+	next if $line =~ m/^\s*$/; # whitespace/empty lines
+
+	my ($ip, @names) = split(/\s+/, $line);
+
+	raise_param_exc({ 'data' => "Invalid IP '$ip'" })
+	    if $ip !~ m/^$PVE::Tools::IPRE$/;
+
+	for my $name (@names) {
+	    raise_param_exc({ 'data' => "Invalid Hostname '$name'" })
+		if $name !~ m/^[.\-a-zA-Z0-9]+$/;
+	}
+    }
+
+    die "write failed: $!" if !print $fh $hosts->{data};
+
+    return $hosts->{data};
+}
+
+register_file('etchosts', "/etc/hosts",
+	      \&read_etc_hosts,
+	      \&write_etc_hosts);
+
 sub read_etc_resolv_conf {
     my ($filename, $fh) = @_;
 
-- 
2.11.0





More information about the pve-devel mailing list