<?php
/*
	olsrd.inc
	part of pfSense (https://www.pfSense.org/)
	Copyright (C) 2006 Scott Ullrich
	Copyright (C) 2015 ESF, LLC
	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.
*/
require_once("config.inc");
require_once("service-utils.inc");
require_once("util.inc");

$pfs_version = substr(trim(file_get_contents("/etc/version")), 0, 3);
if ($pfs_version == "2.1" || $pfs_version == "2.2") {
	define('OLSRD_LOCALBASE', '/usr/pbi/olsrd-' . php_uname("m") . '/local');
} else {
	define('OLSRD_LOCALBASE', '/usr/local');
}

function setup_wireless_olsr() {
	global $config, $g;

	conf_mount_rw();

	if (is_array($config['installedpackages']['olsrd'])) {
		$olsrd_config = $config['installedpackages']['olsrd']['config'][0];
	} else {
		$olsrd_config = array();
	}

	/* If disabled, stop service if needed, unlink the rc script and do nothing else */
	if ($olsrd_config['enable'] != "on") {
		if (is_service_running("olsrd")) {
			stop_service("olsrd");
		}
		unlink_if_exists("/usr/local/etc/rc.d/olsrd.sh");
		return;
	} else {
		/* parse package config and create configuration file */
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");

		if ($olsrd['announcedynamicroute'] or $olsrd['enableannounce'] == "on") {
			$enableannounce .= "\nHna4\n";
			$enableannounce .= "{\n";
		}
		if ($olsrd['announcedynamicroute']) {
			$enableannounce .= "\t{$olsrd['announcedynamicroute']}\n";
		}
		if ($olsrd['enableannounce'] == "on") {
			$enableannounce .= "0.0.0.0 0.0.0.0";
			$enableannounce .= "\n}\n";
		} else {
			$enableannounce = "";
		}
		
		$pluginpath = OLSRD_LOCALBASE . '/lib';
		$olsr .= <<<EODA
#
# olsr.org OLSR daemon config file
#
# Lines starting with a # are discarded
#
# This file was generated by setup_wireless_olsr() in services.inc
#

# This file is an example of a typical
# configuration for a mostly static
# network(regarding mobility) using
# the LQ extention

# Debug level(0-9)
# If set to 0 the daemon runs in the background

DebugLevel	2

# IP version to use (4 or 6)

IpVersion	4

# Clear the screen each time the internal state changes

ClearScreen     yes

{$enableannounce}

# Should olsrd keep on running even if there are
# no interfaces available? This is a good idea
# for a PCMCIA/USB hotswap environment.
# "yes" OR "no"

AllowNoInt	yes

# TOS(type of service) value for
# the IP header of control traffic.
# If not set it will default to 16

#TosValue	16

# The fixed willingness to use(0-7)
# If not set willingness will be calculated
# dynamically based on battery/power status
# if such information is available

#Willingness    	4

# Allow processes like the GUI front-end
# to connect to the daemon.

IpcConnect
{
     # Determines how many simultaneously
     # IPC connections that will be allowed
     # Setting this to 0 disables IPC

     MaxConnections  0

     # By default only 127.0.0.1 is allowed
     # to connect. Here allowed hosts can
     # be added

     Host            127.0.0.1
     #Host            10.0.0.5

     # You can also specify entire net-ranges
     # that are allowed to connect. Multiple
     # entries are allowed

     #Net             192.168.1.0 255.255.255.0
}

# Wether to use hysteresis or not
# Hysteresis adds more robustness to the
# link sensing but delays neighbor registration.
# Used by default. 'yes' or 'no'

UseHysteresis	no

# Hysteresis parameters
# Do not alter these unless you know
# what you are doing!
# Set to auto by default. Allowed
# values are floating point values
# in the interval 0,1
# THR_LOW must always be lower than
# THR_HIGH.

#HystScaling	0.50
#HystThrHigh	0.80
#HystThrLow	0.30


# Link quality level
# 0 = do not use link quality
# 1 = use link quality for MPR selection
# 2 = use link quality for MPR selection and routing
# Defaults to 0

LinkQualityLevel	{$olsrd['enablelqe']}

# Polling rate in seconds(float).
# Default value 0.05 sec

Pollrate	0.05


# TC redundancy
# Specifies how much neighbor info should
# be sent in TC messages
# Possible values are:
# 0 - only send MPR selectors
# 1 - send MPR selectors and MPRs
# 2 - send all neighbors
#
# defaults to 0

TcRedundancy	2

#
# MPR coverage
# Specifies how many MPRs a node should
# try select to reach every 2 hop neighbor
#
# Can be set to any integer >0
#
# defaults to 1

MprCoverage	3

# Example plugin entry with parameters:

EODA;

		if ($olsrd['enablehttpinfo'] == "on") {
			$olsr .= <<<EODB

LoadPlugin "{$pluginpath}/olsrd_httpinfo.so.0.1"
{
    PlParam     "port"   "{$olsrd['port']}"
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
}

EODB;

		}

		if ($olsrd['enabledsecure'] == "on") {
			@file_put_contents("{$g['tmp_path']}/olsrkey.txt", $olsrd['securekey']);
			$olsr .= <<<EODC

LoadPlugin "{$pluginpath}/olsrd_secure.so.0.6"
{
    PlParam     "Keyfile"   "{$g['tmp_path']}/olsrkey.txt"
}

EODC;

		}

		if ($olsrd['enabledyngw'] == "on") {

		/* unset default route, olsr auto negotiates */
		mwexec("/sbin/route delete default");

		$olsr .= <<<EODE

LoadPlugin "{$pluginpath}/olsrd_dyn_gw.so.0.4"
{
    # how often to look for a inet gw, in seconds
    # defaults to 5 secs, if commented out
    PlParam     "Interval"   "{$olsrd['polling']}"

    # if one or more IPv4 addresses are given, do a ping on these in
    # descending order to validate that there is not only an entry in
    # routing table, but also a real internet connection. If any of
    # these addresses could be pinged successfully, the test was
    # succesful, i.e. if the ping on the 1st address was successful,the
    # 2nd won't be pinged
    PlParam     "Ping"       "{$olsrd['ping']}"
    #PlParam     "HNA"   "192.168.81.0 255.255.255.0"
}

EODE;

		}

		foreach ($config['installedpackages']['olsrd']['config'] as $conf) {
			$interfaces = explode(',', $conf['iface_array']);
			foreach ($interfaces as $interface) {
				$realinterface = convert_friendly_interface_to_real_interface_name($interface);
				$olsr .= <<<EODAD
Interface "{$realinterface}"
{

    # Hello interval in seconds(float)
    HelloInterval    2.0

    # HELLO validity time
    HelloValidityTime	20.0

    # TC interval in seconds(float)
    TcInterval        5.0

    # TC validity time
    TcValidityTime	30.0

    # MID interval in seconds(float)
    MidInterval	5.0

    # MID validity time
    MidValidityTime	30.0

    # HNA interval in seconds(float)
    HnaInterval	5.0

    # HNA validity time
    HnaValidityTime 	30.0

    # When multiple links exist between hosts
    # the weight of interface is used to determine
    # the link to use. Normally the weight is
    # automatically calculated by olsrd based
    # on the characteristics of the interface,
    # but here you can specify a fixed value.
    # Olsrd will choose links with the lowest value.

    # Weight 0


}

EODAD;

			}
			break;
		}

		fwrite($fd, $olsr);
		fclose($fd);



		/* create rc script and (re)start service */
		$olsrd_start = "/usr/local/sbin/olsrd -f {$g['varetc_path']}/olsr.conf";
		$olsrd_stop = "/usr/bin/killall olsrd; sleep 3";
		write_rcfile(array(
			"file" => "olsrd.sh",
			"start" => $olsrd_start,
			"stop" => $olsrd_stop
			)
		);
		if (is_service_running("olsrd")) {
			restart_service("olsrd");
		} else {
			start_service("olsrd");
		}
	}

	conf_mount_ro();
}

function validate_form_olsrd($post, &$input_errors) {
	/*
	if ($post['iface_array'] == "") {
		$input_errors[] = 'You must select at least one interface for OSLRD.';
	}
	*/
	if ($post['enablehttpinfo']) {
		if (!$post['port'] || !$post['allowedhttpinfohost'] || !$post['allowedhttpinfosubnet']) {
			$input_errors[] = "'HTTPInfo Port', 'Allowed Host(s) IP Address/Subnet' and 'Allowed Host(s) Netmask' must be filled in when HTTPInfo Plugin is enabled.";
		}
		if ($post['port'] && !is_port($post['port'])) {
			$input_errors[] = "Invalid port entered for 'HTTPInfo Port'.";
		}
		if ($post['allowedhttpinfohost'] && !is_ipaddrv4($post['allowedhttpinfohost'])) {
			$input_errors[] = "Invalid IPv4 address entered for 'Allowed Host(s) IP Address/Subnet'.";
		}
		if ($post['allowedhttpinfosubnet'] && !is_ipaddrv4($post['allowedhttpinfosubnet'])) {
			$input_errors[] = "Invalid IPv4 address entered for 'Allowed Host(s) Netmask'.";
		}
		if ($post['allowedhttpinfohost'] && is_ipaddrv4($post['allowedhttpinfohost']) && $post['allowedhttpinfosubnet'] && is_ipaddrv4($post['allowedhttpinfosubnet'])) {
			$cidr = 32 - log((ip2long($post['allowedhttpinfosubnet']) ^ ip2long('255.255.255.255')) + 1, 2);
			$acl = "{$post['allowedhttpinfohost']}/{$cidr}";
			if (!is_subnetv4($acl)) {
				$input_errors[] = "'{$post['allowedhttpinfohost']}/{$post['allowedhttpinfosubnet']}' is not a valid IPv4 subnet.";
			}
		}
	}
	if ($post['enabledyngw']) {
		if (!$post['ping'] || !$post['polling']) {
			$input_errors[] = "'Ping IP Address' and 'Poll Interval' must be filled in when 'Enable Dynamic Gateway' is checked.";
		}
		if ($post['ping'] && !is_ipaddrv4($post['ping'])) {
			$input_errors[] = "Invalid IPv4 address entered for 'Ping IP Address'.";
		}
		if ($post['polling'] && (!is_numericint($post['polling']) || ($post['polling'] < 1))) {
			$input_errors[] = "'Poll Interval' must be numeric integer greater than 0.";
		}
	}
}

function php_deinstall_olsrd() {
	global $g;
	unlink_if_exists("{$g['varetc_path']}/olsr.conf");
	unlink_if_exists("{$g['tmp_path']}/olsrkey.txt");
}

?>