<?php
/*
	siproxd.inc
	Copyright (C) 2006 Scott Ullrich
	Copyright (C) 2010 Jim Pingle
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	1. Redistributions of source code must retain the above copyright notice,
	   this list of conditions and the following disclaimer.

	2. Redistributions in binary form must reproduce the above copyright
	   notice, this list of conditions and the following disclaimer in the
	   documentation and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.
*/

if(!function_exists("filter_configure"))
	require_once("filter.inc");

// Check to find out on which system the package is running
if (substr(trim(file_get_contents("/etc/version")),0,3) == "2.0") {
	define('SIPROXD', '/usr/local');
} else {
	define('SIPROXD', '/usr/pbi/siproxd-' . php_uname("m"));
}
// End of system check

function sync_package_sipproxd_users() {
	conf_mount_rw();

	// put the constant to a variable
	$varSIPROXD = SIPROXD;

	global $config;
	$fout = fopen("$varSIPROXD/etc/siproxd_passwd.cfg","w");
	fwrite($fout, "# This file was automatically generated by the pfSense\n# package management system.\n\n");
	if($config['installedpackages']['siproxdusers']['config'] != "") {
		foreach($config['installedpackages']['siproxdusers']['config'] as $rowhelper) {
			fwrite($fout, $rowhelper['username'] . " " . $rowhelper['password'] . "\n");
		}
	}
	fclose($fout);
	conf_mount_ro();
	system("/usr/bin/killall -HUP siproxd");
}

function siproxd_generate_rules($type) {
	global $config;

	// put the constant to a variable
	$varSIPROXD = SIPROXD;

	$siproxd_conf = &$config['installedpackages']['siproxdsettings']['config'][0];
	if (!is_service_running('siproxd')) {
		log_error("Sipproxd is installed but not started.  Not installing redirect rules.");
		return;
	}

	/* proxy is turned off in package settings */
	if($siproxd_conf['sipenable'] == "0") {
		log_error("WARNING: siproxd proxy has not been enabled.  Not installing rules.");
		return "\n";
	}

	$ifaces = explode(",", $siproxd_conf['if_inbound']);
	$ifaces = array_map('convert_friendly_interface_to_real_interface_name', $ifaces);
	$rtplower = ($siproxd_conf['rtplower'] ? $siproxd_conf['rtplower'] : 7070);
	$rtpupper = ($siproxd_conf['rtpupper'] ? $siproxd_conf['rtpupper'] : 7079);
	$port = ($siproxd_conf['proxy_port'] ? $siproxd_conf['proxy_port'] : 5060);

	switch($type) {
	case 'nat':
		$rules .= "\n# Setup Sipproxd proxy redirect\n";
		foreach ($ifaces as $iface) {
			if($iface <> "")
				$rules .= "rdr on {$iface} proto udp from any to !($iface) port {$port} -> 127.0.0.1 port {$port}\n";
		}
		break;
	case 'filter':
	case 'rule':
		foreach ($ifaces as $iface) {
			if($iface <> "") {
				$rules .= "# allow SIP signaling and RTP traffic\n";
				$rules .= "pass in on {$iface} proto udp from any to any port = {$port}\n";
				if($siproxd_conf['rtpenable'] == "1") {
					$rules .= "pass in on {$iface} proto udp from any to any port {$rtplower}:{$rtpupper}\n";
				}
			}
		}
		break;
	}

	return $rules;
}

function sync_package_siproxd() {
	global $config;

	// put the constant to a variable
	$varSIPROXD = SIPROXD;

	conf_mount_rw();

	$siproxd_chroot = "/var/siproxd/";
	@mkdir($siproxd_chroot);
	@chown($siproxd_chroot, "nobody");
	@chgrp($siproxd_chroot, "nobody");

	unlink_if_exists("$varSIPROXD/etc/rc.d/siproxd");
	$siproxd_conf = &$config['installedpackages']['siproxdsettings']['config'][0];
	$fout = fopen("$varSIPROXD/etc/siproxd.conf","w");

	fwrite($fout, "# This file was automatically generated by the pfSense\n");
	fwrite($fout, "# package management system.\n\n");

	/* proxy is turned off in package settings */
	if($siproxd_conf['sipenable'] == "0") {
		fclose($fout);
		return;
	}

	if($siproxd_conf['if_inbound'] != "") {
		fwrite($fout, "if_inbound = " . convert_friendly_interface_to_real_interface_name($siproxd_conf['if_inbound']) . "\n");
	}

	if($siproxd_conf['if_outbound'] != "") {
		if(intval($config['version']) < 6 && $config['interfaces'][$siproxd_conf['if_outbound']]['ipaddr'] == "pppoe") {
			fwrite($fout, "if_outbound = ng0\n");
		} else {
			fwrite($fout, "if_outbound = " . convert_friendly_interface_to_real_interface_name($siproxd_conf['if_outbound']) . "\n");
		}
	}

	if($siproxd_conf['port'] != "") {
		fwrite($fout, "sip_listen_port = " . $siproxd_conf['port'] . "\n");
	} else {
		fwrite($fout, "sip_listen_port = 5060\n");
	}

	fwrite($fout, "daemonize = 1\n");
	fwrite($fout, "silence_log = 0\n");
	//fwrite($fout, "log_calls = 1\n");
	fwrite($fout, "user = nobody\n");
	fwrite($fout, "chrootjail = {$siproxd_chroot}\n");
	fwrite($fout, "registration_file = siproxd_registrations\n");
	fwrite($fout, "autosave_registrations = 10\n");
	fwrite($fout, "pid_file = siproxd.pid\n");

	if($siproxd_conf['rtpenable'] != "") {
		fwrite($fout, "rtp_proxy_enable = " . $siproxd_conf['rtpenable'] . "\n");
	} else {
		fwrite($fout, "rtp_proxy_enable = 1\n");
	}

	if(($siproxd_conf['rtplower'] != "") && ($siproxd_conf['rtpupper'] != "")) {
		fwrite($fout, "rtp_port_low = " . $siproxd_conf['rtplower'] . "\n");
		fwrite($fout, "rtp_port_high = " . $siproxd_conf['rtpupper'] . "\n");
	} else {
		fwrite($fout, "rtp_port_low = 7070\n");
		fwrite($fout, "rtp_port_high = 7079\n");
	}

	if($siproxd_conf['rtptimeout'] != "") {
		fwrite($fout, "rtp_timeout = " . $siproxd_conf['rtptimeout'] . "\n");
	} else {
		fwrite($fout, "rtp_timeout = 300\n");
	}

	if($siproxd_conf['defaulttimeout'] != "") {
		fwrite($fout, "default_expires = " . $siproxd_conf['defaulttimeout'] . "\n");
	} else {
		fwrite($fout, "default_expires = 600\n");
	}

	if($siproxd_conf['authentication']) {
		fwrite($fout, "proxy_auth_realm = Authentication_Realm\n");
		fwrite($fout, "proxy_auth_pwfile = $varSIPROXD/etc/siproxd_passwd.cfg\n");
	}

	if($siproxd_conf['debug_level'] != "") {
		fwrite($fout, "debug_level = " . $siproxd_conf['debug_level'] . "\n");
	} else {
		fwrite($fout, "debug_level = 0x00000000\n");
	}

	if($siproxd_conf['debug_port'] != "") {
		fwrite($fout, "debug_port = " . $siproxd_conf['debug_port'] . "\n");
	}

	if($siproxd_conf['outboundproxyhost'] != "") {
		if($siproxd_conf['outboundproxyport'] != "") {
			fwrite($fout, "outbound_proxy_host = " . $siproxd_conf['outboundproxyhost'] . "\n");
			fwrite($fout, "outbound_proxy_port = " . $siproxd_conf['outboundproxyport'] . "\n");
		}
	}

	if($siproxd_conf['expeditedforwarding'] != "")
		fwrite($fout, "rtp_dscp = 46\n");
	if($siproxd_conf['expeditedsipforwarding'] != "")
		fwrite($fout, "sip_dscp = 26\n");

	if ($siproxd_conf['rtp_input_dejitter'] != "")
		fwrite($fout, "rtp_input_dejitter = " . $siproxd_conf['rtp_input_dejitter'] . "\n");
	if ($siproxd_conf['rtp_output_dejitter'] != "")
		fwrite($fout, "rtp_output_dejitter = " . $siproxd_conf['rtp_output_dejitter'] . "\n");
	if ($siproxd_conf['tcp_timeout'] != "")
		fwrite($fout, "tcp_timeout = " . $siproxd_conf['tcp_timeout'] . "\n");
	if ($siproxd_conf['tcp_connect_timeout'] != "")
		fwrite($fout, "tcp_connect_timeout = " . $siproxd_conf['tcp_connect_timeout'] . "\n");
	if ($siproxd_conf['tcp_keepalive'] != "")
		fwrite($fout, "tcp_keepalive = " . $siproxd_conf['tcp_keepalive'] . "\n");

	fwrite($fout, "plugindir=$varSIPROXD/lib/siproxd/\n");
	fwrite($fout, "load_plugin=plugin_logcall.la\n");

	if ($siproxd_conf['plugin_defaulttarget'] != "")
		fwrite($fout, "load_plugin=plugin_defaulttarget.la\n");
	if (($siproxd_conf['plugin_defaulttarget'] != "") && ($siproxd_conf['plugin_defaulttarget_log'] != ""))
		fwrite($fout, "plugin_defaulttarget_log = 1\n");
	if (($siproxd_conf['plugin_defaulttarget'] != "") && ($siproxd_conf['plugin_defaulttarget_target'] != ""))
		fwrite($fout, "plugin_defaulttarget_target = " . $siproxd_conf['plugin_defaulttarget_target'] . "\n");

	if ($siproxd_conf['plugin_fix_bogus_via'] != "")
		fwrite($fout, "load_plugin=plugin_fix_bogus_via.la\n");
	if (($siproxd_conf['plugin_fix_bogus_via'] != "") && ($siproxd_conf['plugin_fix_bogus_via_networks'] != ""))
		fwrite($fout, "plugin_fix_bogus_via_networks = " . $siproxd_conf['plugin_fix_bogus_via_networks'] . "\n");

	if ($siproxd_conf['plugin_stun'] != "")
		fwrite($fout, "load_plugin=plugin_stun.la\n");
	if (($siproxd_conf['plugin_stun'] != "") && ($siproxd_conf['plugin_stun_server'] != ""))
		fwrite($fout, "plugin_stun_server = " . $siproxd_conf['plugin_stun_server'] . "\n");
	if (($siproxd_conf['plugin_stun'] != "") && ($siproxd_conf['plugin_stun_port'] != ""))
		fwrite($fout, "plugin_stun_port = " . $siproxd_conf['plugin_stun_port'] . "\n");
	if (($siproxd_conf['plugin_stun'] != "") && ($siproxd_conf['plugin_stun_period'] != ""))
		fwrite($fout, "plugin_stun_period = " . $siproxd_conf['plugin_stun_period'] . "\n");

	fclose($fout);

	write_rcfile(array(
		"file" => "siproxd.sh",
		"start" => "$varSIPROXD/sbin/siproxd -c $varSIPROXD/etc/siproxd.conf &",
		"stop" => "/usr/bin/killall -9 siproxd"
		)
	);

	exec("killall -9 siproxd");

	sleep(3);

	start_service("siproxd");

	sleep(3);

	filter_configure();

	conf_mount_ro();

}

function validate_form_siproxd($post, $input_errors) {
	if ($post['port'] && !is_port($post['port']))
		$input_errors[] = 'Invalid port entered for "Listening Port"';
	if ($post['rtplower'] && !is_port($post['rtplower']))
		$input_errors[] = 'Invalid port entered for "RTP port range (lower)".';
	if ($post['rtpupper'] && !is_port($post['rtpupper']))
		$input_errors[] = 'Invalid port entered for "RTP port range (upper)".';
	if ($post['rtplower'] && $post['rtpupper'] && ($post['rtplower'] >= $post['rtpupper']))
		$input_errors[] = 'RTP lower port cannot be equal to or higher than the RTP upper port.';
	if ($post['rtptimeout'] && (!is_numeric($post['rtptimeout']) || ($post['rtptimeout'] < 0)))
		$input_errors[] = '"RTP stream timeout" must be numeric and greater than 0.';
	if ($post['defaulttimeout'] && (!is_numeric($post['defaulttimeout']) || ($post['defaulttimeout'] < 0)))
		$input_errors[] = '"Default expiration timeout" must be numeric and greater than 0.';
	if ($post['outboundproxyhost'] && (!is_hostname($post['outboundproxyhost']) && !is_ipaddr($post['outboundproxyhost'])))
		$input_errors[] = 'Invalid hostname or IP address entered for "Outbound Proxy Host".';
	if ($post['outboundproxyport'] && !is_port($post['outboundproxyport']))
		$input_errors[] = 'Invalid port entered for "Outbound Proxy Port".';
	if ($post['rtp_input_dejitter'] && (!is_numeric($post['rtp_input_dejitter']) || ($post['rtp_input_dejitter'] < 0)))
		$input_errors[] = '"Input Dejitter" must be numeric and greater than 0.';
	if ($post['rtp_output_dejitter'] && (!is_numeric($post['rtp_output_dejitter']) || ($post['rtp_output_dejitter'] < 0)))
		$input_errors[] = '"Output Dejitter" must be numeric and greater than 0.';
	if ($post['tcp_timeout'] && (!is_numeric($post['tcp_timeout']) || ($post['tcp_timeout'] < 0)))
		$input_errors[] = '"TCP inactivity timeout" must be numeric and greater than 0.';
	if ($post['tcp_connect_timeout'] && (!is_numeric($post['tcp_connect_timeout']) || ($post['tcp_connect_timeout'] < 0)))
		$input_errors[] = '"TCP Connect Timeout" must be numeric and greater than 0.';
	if ($post['tcp_keepalive'] && (!is_numeric($post['tcp_keepalive']) || ($post['tcp_keepalive'] < 0)))
		$input_errors[] = '"TCP Keepalive" must be numeric and greater than 0.';
	if ($post['plugin_stun_server'] && (!is_hostname($post['plugin_stun_server']) && !is_ipaddr($post['plugin_stun_server'])))
		$input_errors[] = 'Invalid hostname or IP address entered for "STUN Server".';
	if ($post['plugin_stun_port'] && !is_port($post['plugin_stun_port']))
		$input_errors[] = 'Invalid port entered for "STUN Port".';
	if ($post['plugin_stun_period'] && (!is_numeric($post['plugin_stun_period']) || ($post['plugin_stun_period'] < 0)))
		$input_errors[] = '"STUN Period" must be numeric and greater than 0.';

}

?>