#!/usr/local/bin/perl
# save_stunnel.cgi
# Save, create or delete an SSL tunnel

require './stunnel-lib.pl';
&ReadParse();
&error_setup($text{'save_err'});

if ($in{'idx'} ne '') {
	@stunnels = &list_stunnels();
	$st = $stunnels[$in{'idx'}];
	%old = %$st;
	}

if ($in{'delete'}) {
	# Just delete from inetd.conf and xinetd.conf
	&lock_file($st->{'file'});
	&delete_stunnel($st);
	}
else {
	# Validate and store inputs
	if ($in{'new'}) {
		$st = { 'args' => $stunnel_shortname,
			'command' => $config{'stunnel_path'},
			'type' => $in{'type'} };
		}
	else {
		$st->{'args'} = $in{'args'};
		}
	$in{'name'} =~ /^[A-z][A-z0-9\_\-]+$/ || &error($text{'save_ename'});
	$st->{'name'} = $in{'name'};
	$in{'port'} =~ /^\d+$/ || &error($text{'save_eport'});
	$st->{'port'} = $in{'port'};
	$st->{'active'} = $in{'active'};
	if ($in{'pmode'} == 1) {
		$st->{'args'} .= " -p $webmin_pem";
		}
	elsif ($in{'pmode'} == 2) {
		-r $in{'pem'} || &error(&text('save_epem', $in{'pem'}));
		$st->{'args'} .= " -p $in{'pem'}";
		}
	if ($in{'cmode'}) {
		$st->{'args'} .= " -c";
		}
	if (!$in{'tcpw_def'}) {
		$in{'tcpw'} =~ /^\S+$/ || &error($text{'save_etcpw'});
		$st->{'args'} .= " -N $in{'tcpw'}";
		}
	if (!$in{'iface_def'}) {
		gethostbyname($in{'iface'}) || &check_ipaddress($in{'iface'}) ||
			&error($text{'save_eiface'});
		$st->{'args'} .= " -I $in{'iface'}";
		}
	if ($in{'mode'} == 0 || $in{'mode'} == 1) {
		# Running a command
		local $cmd = $in{'mode'} == 0 ? $in{'cmd0'} : $in{'cmd1'};
		local $args = $in{'mode'} == 0 ? $in{'args0'} : $in{'args1'};
		&has_command($cmd) || &error($text{'save_ecmd'});
		if ($in{'mode'} == 0) {
			$st->{'args'} .= " -l $cmd";
			}
		else {
			$st->{'args'} .= " -L $cmd";
			}
		if ($args) {
			$st->{'args'} .= " -- $args";
			}
		}
	else {
		# Connecting to remote host and port
		gethostbyname($in{'rhost'}) || &check_ipaddress($in{'rhost'}) ||
			&error($text{'save_erhost'});
		$in{'rport'} =~ /^\d+$/ || &error($text{'save_erport'});
		if ($in{'rhost'} eq 'localhost') {
			$st->{'args'} .= " -r $in{'rport'}";
			}
		else {
			$st->{'args'} .= " -r $in{'rhost'}:$in{'rport'}";
			}
		}

	if ($in{'new'}) {
		&lock_create_file();
		&create_stunnel($st);
		}
	else {
		&lock_file($old{'file'});
		&modify_stunnel(\%old, $st);
		}
	}
&unlock_all_files();
&webmin_log($in{'delete'} ? "delete" : $in{'new'} ? "create" : "modify",
	    "stunnel", $st->{'name'}, $st);
&redirect("");

