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

Thomas Lamprecht t.lamprecht at proxmox.com
Wed Sep 12 11:14:11 CEST 2018


On 9/12/18 10:24 AM, Dominik Csapak wrote:
> Signed-off-by: Dominik Csapak <d.csapak at proxmox.com>
> ---
> changes from v2:
> * also encode during write
> * remove digest check code (done in api call)
> * better regex for comments (leading whitespace)
>  src/PVE/INotify.pm | 49 +++++++++++++++++++++++++++++++++++++++++++++++++
>  1 file changed, 49 insertions(+)
> 
> diff --git a/src/PVE/INotify.pm b/src/PVE/INotify.pm
> index 8b5544e..f837596 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);
> @@ -537,6 +538,54 @@ register_file('hostname', "/etc/hostname",
>  	      \&read_etc_hostname, 
>  	      \&write_etc_hostname);
>  
> +sub read_etc_hosts {
> +    my ($filename, $fh) = @_;
> +
> +    my $raw = '';
> +    my $data = '';
> +
> +    while (my $line = <$fh>) {
> +	$raw .= $line;
> +	if ($line =~ m/^\s*#/) {
> +	    $line = decode('UTF-8', $line);
> +	}
> +	$data .= $line;
> +    }
> +
> +    return {
> +	digest => Digest::SHA::sha1_hex($raw),
> +	data => $data,
> +    }

why not just returning the raw data here like all other read methods
in this module do and handle digest fully (generation and checking) in
the API (or where it's actually needed)?

> +}
> +
> +sub write_etc_hosts {
> +    my ($filename, $fh, $hosts, @args) = @_;
> +
> +    # check validity of ips/names
> +    for my $line (split("\n", $hosts)) {
> +	next if $line =~ m/^\s*#/; # 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 encode('UTF-8', $hosts);
> +
> +    return $hosts;
> +}
> +
> +register_file('etchosts', "/etc/hosts",
> +	      \&read_etc_hosts,
> +	      \&write_etc_hosts);
> +
>  sub read_etc_resolv_conf {
>      my ($filename, $fh) = @_;
>  
> 





More information about the pve-devel mailing list