#!/usr/local/bin/perl
# save_host.cgi
# Create, modify or delete an allowed host record

require './postgresql-lib.pl';
&ReadParse();
&lock_file($config{'hba_conf'});
@all = &get_hba_config();
$host = $all[$in{'idx'}] if (!$in{'new'});
&error_setup($text{'host_err'});

if ($in{'delete'}) {
	# delete one host
	&delete_hba($host);
	}
else {
	# validate and parse inputs
	if ($in{'addr_mode'} == 0) {
		$host->{'address'} = '0.0.0.0' if (!$host->{'address'});
		$object = $host->{'netmask'} = '0.0.0.0';
		$host->{'type'} = 'host';
		}
	elsif ($in{'addr_mode'} == 1) {
		&check_ipaddress($in{'host'}) ||
			&error($text{'host_ehost'});
		$object = $host->{'address'} = $in{'host'};
		$host->{'netmask'} = '255.255.255.255';
		$host->{'type'} = 'host';
		}
	elsif ($in{'addr_mode'} == 2) {
		&check_ipaddress($in{'network'}) ||
			&error($text{'host_enetwork'});
		&check_ipaddress($in{'netmask'}) ||
			&error($text{'host_enetmask'});
		$host->{'address'} = $in{'network'};
		$host->{'netmask'} = $in{'netmask'};
		$host->{'type'} = 'host';
		$object = "$in{'network'}/$in{'netmask'}";
		}
	else {
		$object = $host->{'type'} = 'local';
		}
	$host->{'db'} = $in{'db'};
	$host->{'auth'} = $in{'auth'};
	if ($in{'auth'} eq 'password' && $in{'passwordarg'}) {
		$in{'password'} =~ /^\S+$/ || &error($text{'host_epassword'});
		$host->{'arg'} = $in{'password'};
		}
	elsif ($in{'auth'} eq 'ident' && $in{'identarg'}) {
		$in{'ident'} =~ /^\S+$/ || &error($text{'host_eident'});
		$host->{'arg'} = $in{'ident'};
		}
	else {
		$host->{'arg'} = undef;
		}

	if ($in{'new'}) {
		&create_hba($host);
		}
	else {
		&modify_hba($host);
		}
	}
&unlock_file($config{'hba_conf'});
&webmin_log($in{'new'} ? 'create' : $in{'delete'} ? 'delete' : 'modify',
	    'hba', $host->{'type'} eq 'local' ? 'local' :
		   $host->{'netmask'} eq '0.0.0.0' ? 'all' :
		   $host->{'netmask'} eq '255.255.255.255' ? $host->{'address'}:
		   "$host->{'address'}/$host->{'netmask'}", $host);
&redirect("list_hosts.cgi");

