#!/usr/local/bin/perl
# create_forward.cgi
# Create a new forward zone

require './bind8-lib.pl';
&ReadParse();
&error_setup($text{'fcreate_err'});
%access = &get_module_acl();
$access{'forward'} || &error($text{'fcreate_ecannot'});
$access{'ro'} && &error($text{'master_ero'});
$conf = &get_config();
$vconf = $in{'view'} ne '' ? $conf->[$in{'view'}]->{'members'} : $conf;

# validate inputs
if ($in{'rev'}) {
	local($ipv4);
	($ipv4 = &check_net_ip($in{'zone'})) ||
	$config{'support_aaaa'} &&
	(($in{'zone'} =~ /^([\w:]+)(\/\d+)$/) || &check_ip6address($1)) ||
		&error(&text('create_enet', $in{'zone'}));
	if ($ipv4) {
		$in{'zone'} = &ip_to_arpa($in{'zone'});
		}
	else {
		$in{'zone'} = &net_to_ip6int($1, ($2 ? substr($2, 1) : "" ));
		}
	}
else {
	($in{'zone'} =~ /^[\d\.]+$/ || $in{'zone'} =~ /^[\d\:]+(\/[\d]+)?$/) &&
		&error(&text('create_edom2', $in{'zone'}));
	&valdnsname($in{'zone'}, 0, ".") ||
		&error(&text('create_edom', $in{'zone'}));
	}
$in{'zone'} =~ s/\.$//;
@masters = split(/\s+/, $in{'masters'});
foreach $m (@masters) {
	&check_ipaddress($m) ||
		&error(&text('create_emaster', $m));
	}
#if (!@masters) {
#	&error($text{'create_enone'});
#	}
foreach $z (&find("zone", $vconf)) {
	if ($z->{'value'} eq $in{'zone'}) {
		&error($text{'master_etaken'});
		}
	}

# Create zone directive
if ($in{'view'} ne '') {
	$view = $conf->[$in{'view'}];
	&lock_file($config{'chroot'}.$view->{'file'});
	@mdirs = map { { 'name' => $_ } } @masters;
	$dir = { 'name' => 'zone',
		 'values' => [ $in{'zone'} ],
		 'type' => 1,
		 'members' => [ { 'name' => 'type',
				  'values' => [ 'forward' ] },
				{ 'name' => 'forwarders',
				  'type' => 1,
				  'members' => \@mdirs }
			      ]
		};
	&save_directive($view, undef, [ $dir ], 1);
	&flush_file_lines();
	&unlock_file($config{'chroot'}.$view->{'file'});
	}
else {
	$named_conf = $config{'zones_file'} ? $config{'zones_file'}
					    : $config{'named_conf'};
	&lock_file($config{'chroot'}.$named_conf);
	open(CONF, ">>$config{'chroot'}$named_conf");
	print CONF "zone \"$in{'zone'}\" {\n";
	print CONF "\ttype forward;\n";
	print CONF "\tforwarders {\n";
	foreach $m (@masters) { print CONF "\t\t$m;\n"; }
	print CONF "\t\t};\n";
	print CONF "\t};\n";
	print CONF "\n";
	close(CONF);
	&unlock_file($config{'chroot'}.$named_conf);
	}
&webmin_log("create", "forward", $in{'zone'}, \%in);

# Add the new zone to the access list
if ($access{'zones'} ne '*') {
	$access{'zones'} .= " ".$in{'zone'};
	&save_module_acl(\%access);
	}
undef(@get_config_cache);
$conf = &get_config();
foreach $c (@$conf) {
	if ($c->{'name'} eq 'zone' && $c->{'value'} eq $in{'zone'}) {
		$idx = $c->{'index'};
		}
	}
&redirect(defined($idx) ? "edit_forward.cgi?index=$idx" : "index.cgi");

