#!/usr/bin/php
<?php
/*
  vim: set expandtab tabstop=4 softtabstop=4 shiftwidth=4:
  Codificación: UTF-8
  +----------------------------------------------------------------------+
  | Issabel version 4.0                                                  |
  | http://www.issabel.org                                               |
  +----------------------------------------------------------------------+
  | Copyright (c) 2006 Palosanto Solutions S. A.                         |
  +----------------------------------------------------------------------+
  | The contents of this file are subject to the General Public License  |
  | (GPL) Version 2 (the "License"); you may not use this file except in |
  | compliance with the License. You may obtain a copy of the License at |
  | http://www.opensource.org/licenses/gpl-license.php                   |
  |                                                                      |
  | Software distributed under the License is distributed on an "AS IS"  |
  | basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See  |
  | the License for the specific language governing rights and           |
  | limitations under the License.                                       |
  +----------------------------------------------------------------------+
  | The Initial Developer of the Original Code is PaloSanto Solutions    |
  +----------------------------------------------------------------------+
  $Id: dhcpconfig.php,v 1.1 2007/01/09 23:49:36 alex Exp $

  El servidor DHCP de Issabel 6 es Kea (ISC DHCP no existe en EL10). Este
  helper genera el archivo JSON /etc/kea/kea-dhcp4.conf y controla la unidad
  systemd kea-dhcp4.
*/
require_once 'Console/Getopt.php';

load_default_timezone();

// Parse command-line options
$opt = Console_Getopt::getopt($argv, '', array(
    'dumpconfig', // Dump DHCP configuration
    'refresh',  // Rewrites /etc/kea/kea-dhcp4.conf from current config and network.db
    'config',   // Configurate DHCP options
    'start',    // Start DHCP service and mark as autostart
    'stop',     // Stop DHCP service and remove from autostart
    //'restart',  // Restart DHCP service

    // DHCP configuration options
    'ip-start=',    // Start of IP range
    'ip-end=',      // End of IP range
    'lease-time=',  // Lease time
    'dns1=',        // DNS 1 (optional)
    'dns2=',        // DNS 2 (optional)
    'gateway=',     // Network gateway (optional)
    'wins=',        // New hostname (optional)
    'next-server=',  // PXE Boot Server
    'filename=',     // Filename for PXE Boot
    'phonesonly',   // If specified, restrict DHCP to known phones only
));
if (PEAR::isError($opt)) error_exit($opt->getMessage()."\n");
validateOptions($opt);
foreach ($opt[0] as $option) switch ($option[0]) {
case '--dumpconfig':
    exit(action_dumpconfig($opt) ? 0 : 1);
case '--refresh':
    exit(action_refresh($opt) ? 0 : 1);
case '--config':
    exit(action_configuration($opt) ? 0 : 1);
case '--start':
    exit(action_start($opt) ? 0 : 1);
case '--stop':
    exit(action_stop($opt) ? 0 : 1);
}
error_exit("No action specified (--config or --start or --stop)\n");

function error_exit($sMsg, $errorcode = 1)
{
    fwrite(STDERR, $sMsg);
    exit($errorcode);
}

function load_default_timezone()
{
    $sDefaultTimezone = @date_default_timezone_get();
    if ($sDefaultTimezone == 'UTC') {
        $sDefaultTimezone = 'America/New_York';
        $regs = NULL;
        if (is_link("/etc/localtime") && preg_match("|/usr/share/zoneinfo/(.+)|", readlink("/etc/localtime"), $regs)) {
            $sDefaultTimezone = $regs[1];
        } elseif (file_exists('/etc/sysconfig/clock')) {
            foreach (file('/etc/sysconfig/clock') as $s) {
                $regs = NULL;
                if (preg_match('/^ZONE\s*=\s*"(.+)"/', $s, $regs)) {
                    $sDefaultTimezone = $regs[1];
                }
            }
        }
    }
    date_default_timezone_set($sDefaultTimezone);
}

// Path of the Kea DHCPv4 configuration file
function keaConfigPath()
{
    return '/etc/kea/kea-dhcp4.conf';
}

// Parse and validate known command-line options
function validateOptions($opt)
{
    foreach ($opt[0] as $option) switch ($option[0]) {
    case '--lease-time':
        if (!ctype_digit($option[1]))
            error_exit('Option '.$option[0].": Invalid lease time\n");
        break;
    case '--dns1':
    case '--dns2':
    case '--gateway':
    case '--wins':
    case '--next-server':
    case '--ip-start':
    case '--ip-end':
        $regs = NULL;
        if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $option[1], $regs))
            error_exit('Option '.$option[0].": Invalid IP address\n");
        for ($i = 1; $i <= 4; $i++) if ($regs[$i] > 255)
            error_exit('Option '.$option[0].": Invalid IP address\n");
        break;
    }
}

// Dump configuration
function action_dumpconfig($opt)
{
    $sPath = keaConfigPath();
    if (file_exists($sPath)) {
        readfile($sPath);
        return TRUE;
    }
    return FALSE;
}

// Execute DNS configuration. Returns TRUE on success
function action_configuration($opt)
{
    $bExito = TRUE;

    $sIpStart = $sIpEnd = $iLeaseTime = $sGateway = $sDNS1 = $sDNS2 = $sWINS = $sNEXTSERVER = $sFILENAME = NULL;
    $bPhonesOnly = FALSE;
    foreach ($opt[0] as $option) switch ($option[0]) {
    case '--ip-start':
        $sIpStart = $option[1];
        break;
    case '--ip-end':
        $sIpEnd = $option[1];
        break;
    case '--lease-time':
        $iLeaseTime = $option[1];
        break;
    case '--gateway':
        $sGateway = $option[1];
        break;
    case '--dns1':
        $sDNS1 = $option[1];
        break;
    case '--dns2':
        $sDNS2 = $option[1];
        break;
    case '--wins':
        $sWINS = $option[1];
        break;
    case '--next-server':
        $sNEXTSERVER = $option[1];
        break;
    case '--filename':
        $sFILENAME = $option[1];
        break;
    case '--phonesonly':
        $bPhonesOnly = TRUE;
        break;
    }

    // Check required parameters
    if ($bExito && is_null($sIpStart)) {
        $bExito = FALSE;
        fprintf(STDERR, "ERR: start of IP range must be specified\n");
    }
    if ($bExito && is_null($sIpEnd)) {
        $bExito = FALSE;
        fprintf(STDERR, "ERR: end of IP range must be specified\n");
    }
    if ($bExito && is_null($iLeaseTime)) {
        $bExito = FALSE;
        fprintf(STDERR, "ERR: lease time must be specified\n");
    }
    if (is_null($sDNS1) && !is_null($sDNS2)) {
        $bExito = FALSE;
        fprintf(STDERR, "ERR: DNS 2 requires DNS 1 to be set\n");
    }

    if ($bExito) {
        $bExito = configureDHCP($sIpStart, $sIpEnd, $iLeaseTime, $sGateway,
            $sDNS1, $sDNS2, $sWINS, $sNEXTSERVER, $sFILENAME, $bPhonesOnly);
    }
    return $bExito;
}

// Write out the Kea DHCP configuration from requested parameters. Return TRUE on success
function configureDHCP($sIpStart, $sIpEnd, $iLeaseTime, $sGateway = NULL,
    $sDNS1 = NULL, $sDNS2 = NULL, $sWINS = NULL, $sNEXTSERVER = NULL, $sFILENAME = NULL, $bPhonesOnly = FALSE)
{
    // Fix reversed start and end
    if ((explode(".", $sIpStart) > explode(".", $sIpEnd))) {
        $t = $sIpStart; $sIpStart = $sIpEnd; $sIpEnd = $t;
    }

    // Get timezone offset
    $sTimezoneOffset = (int)date("Z");
    $sTimezoneName = date_default_timezone_get();

    // Find out hostname and derive a domain from it
    $sHostname = trim(file_get_contents("/proc/sys/kernel/hostname"));
    $hostnameParts = explode('.', $sHostname, 2);
    $sDomain = array_pop($hostnameParts);

    /* There might be multiple interfaces on the machine. The configuration
     * must be built with the subnet/mask information of the interface that
     * contains the required IP range */
    $sIpAddress = $sNetwork = $sNetmask = $sIntf = NULL;
    foreach (listIpAddresses() as $sIfName => $addrInfo) {
        $sNetwork_start = construir_ip_red($sIpStart, $addrInfo['netmask']);
        $sNetwork_end   = construir_ip_red($sIpEnd, $addrInfo['netmask']);
        if ($addrInfo['network'] == $sNetwork_start && $addrInfo['network'] == $sNetwork_end) {
            $sNetwork = $addrInfo['network'];
            $sNetmask = $addrInfo['netmask'];
            $sIpAddress = $addrInfo['ipaddr'];
            $sIntf = $sIfName;
            break;
        }
    }
    if (is_null($sIpAddress)) {
        fprintf(STDERR, "ERR: start or end IPs are outside range on all configured interfaces\n");
        return FALSE;
    }

    // Query all configured fixed IPs for DHCP
    $ipsInsideNet = array();

    // network.db exists in Elastix 2.0 only
    if (file_exists('/var/www/db/network.db')) {
        try {
            $conn = new PDO('sqlite:/var/www/db/network.db');
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sth = $conn->query('SELECT hostname, ipaddress, macaddress FROM dhcp_conf ORDER BY ipaddress');
            $ips = $sth->fetchAll(PDO::FETCH_ASSOC);

            // Keep only the IPs that belong to the configured subnet. Kea
            // requires reservations to live inside the subnet that serves them.
            foreach ($ips as $ip) {
                if (construir_ip_red($ip['ipaddress'], $sNetmask) == $sNetwork)
                    $ipsInsideNet[] = $ip;
            }
            $conn = NULL;
        } catch (PDOException $e) {
            fprintf(STDERR, "ERR: failed to query fixed IPs for DHCP - %s\n", $e->getMessage());
            return FALSE;
        }
    }

    // Known phone MAC prefixes, when restricting the pool to known phones
    $macs = array();
    if ($bPhonesOnly) {
        $sMysqlRootPass = 'iSsAbEl.2o17';
        foreach (file('/etc/issabel.conf') as $s) {
            $regs = NULL;
            if (preg_match('/^mysqlrootpwd\s*=\s*(.+)$/', trim($s), $regs)) {
                $sMysqlRootPass = $regs[1];
                break;
            }
        }

        try {
            $conn = new PDO('mysql:host=localhost;dbname=endpointconfig', 'root', $sMysqlRootPass);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sth = $conn->query('SELECT mac_prefix FROM mac_prefix ORDER BY mac_prefix');
            $macs = $sth->fetchAll(PDO::FETCH_COLUMN);
            $conn = NULL;
        } catch (PDOException $e) {
            fprintf(STDERR, "ERR: failed to query known phone MAC prefixes - %s\n", $e->getMessage());
            return FALSE;
        }
    }

    // Build the option-data list common to the subnet
    $optionData = array();
    if (!is_null($sGateway))
        $optionData[] = array('name' => 'routers', 'data' => $sGateway);
    if (!is_null($sWINS))
        $optionData[] = array('name' => 'netbios-name-servers', 'data' => $sWINS);
    $dnsList = array();
    if (!is_null($sDNS1)) $dnsList[] = $sDNS1;
    if (!is_null($sDNS2)) $dnsList[] = $sDNS2;
    if (count($dnsList) > 0)
        $optionData[] = array('name' => 'domain-name-servers', 'data' => implode(', ', $dnsList));
    $optionData[] = array('name' => 'nis-domain', 'data' => $sDomain);
    $optionData[] = array('name' => 'domain-name', 'data' => $sDomain);
    $optionData[] = array('name' => 'time-offset', 'data' => (string)$sTimezoneOffset);
    $optionData[] = array('name' => 'ntp-servers', 'data' => $sIpAddress);
    $optionData[] = array('name' => 'tftp-server-name', 'data' => $sIpAddress);
    // The following option tells Cisco phones the address of the TFTP server
    $optionData[] = array('name' => 'cisco-tftp-server', 'data' => $sIpAddress);

    // Fixed reservations. Kea uses hw-address/ip-address and does not require
    // a hostname, but we keep it so the lease can be identified.
    $reservations = array();
    foreach ($ipsInsideNet as $ip) {
        $entry = array(
            'hw-address' => $ip['macaddress'],
            'ip-address' => $ip['ipaddress'],
        );
        if (isset($ip['hostname']) && $ip['hostname'] !== '')
            $entry['hostname'] = $ip['hostname'];
        $reservations[] = $entry;
    }

    // Pool, optionally restricted to known phones through a client class
    $pool = array('pool' => $sIpStart.' - '.$sIpEnd);

    // Subnet definition
    $subnet = array(
        'id' => 1,
        'subnet' => $sNetwork.'/'.maskToBits($sNetmask),
        'interface' => $sIntf,
        'pools' => array($pool),
        'option-data' => $optionData,
    );
    if (!is_null($sNEXTSERVER)) $subnet['next-server'] = $sNEXTSERVER;
    if (!is_null($sFILENAME)) $subnet['boot-file-name'] = $sFILENAME;
    if (count($reservations) > 0) $subnet['reservations'] = $reservations;

    // Restrict the pool to known phones, if requested
    $clientClasses = NULL;
    if ($bPhonesOnly && count($macs) > 0) {
        $tests = array();
        foreach ($macs as $mac) {
            $mac = strtolower(trim($mac));
            $tests[] = "substring(hexstring(pkt4.mac, ':'),0,".strlen($mac).") == '".$mac."'";
        }
        $clientClasses = array(array(
            'name' => 'issabel-known-phones',
            'test' => implode(' or ', $tests),
        ));
        $subnet['pools'][0]['client-classes'] = array('issabel-known-phones');
    }

    // Global configuration
    $dhcp4 = array(
        'interfaces-config' => array('interfaces' => array($sIntf)),
        'valid-lifetime' => (int)$iLeaseTime,
        'max-valid-lifetime' => 50000,
        'lease-database' => array(
            'type' => 'memfile',
            'persist' => TRUE,
            'name' => '/var/lib/kea/kea-leases4.csv',
        ),
        // Option 150 is not a standard DHCPv4 option, it must be defined
        'option-def' => array(array(
            'name' => 'cisco-tftp-server',
            'code' => 150,
            'type' => 'ipv4-address',
            'space' => 'dhcp4',
        )),
        'subnet4' => array($subnet),
    );
    if (!is_null($clientClasses)) $dhcp4['client-classes'] = $clientClasses;

    $sPlantilla = json_encode(array('Dhcp4' => $dhcp4), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n";

    $sPath = keaConfigPath();
    if (!is_dir(dirname($sPath)) && !@mkdir(dirname($sPath), 0755, TRUE)) {
        fprintf(STDERR, "ERR: cannot create directory %s\n", dirname($sPath));
        return FALSE;
    }
    if (file_put_contents($sPath, $sPlantilla) === FALSE) {
        fprintf(STDERR, "ERR: cannot write %s\n", $sPath);
        return FALSE;
    }

    // Validate the generated configuration before touching the service
    if (file_exists('/usr/sbin/kea-dhcp4')) {
        $output = $ret = NULL;
        exec('/usr/sbin/kea-dhcp4 -t '.escapeshellarg($sPath).' 2>&1', $output, $ret);
        if ($ret != 0) {
            fprintf(STDERR, "ERR: invalid Kea configuration - %s\n", implode('', $output));
            return FALSE;
        }
    }

    // Restart dhcp service for changes to take effect
    if (is_dhcp_active()) {
        $output = $ret = NULL;
        exec('/usr/bin/systemctl restart kea-dhcp4 2>&1', $output, $ret);
        if ($ret != 0) {
            fprintf(STDERR, "ERR: failed to restart kea-dhcp4 - %s\n", implode('', $output));
            return FALSE;
        }
    }

    return TRUE;
}

// Convert a dotted netmask into a prefix length
function maskToBits($sMask)
{
    $iBits = 0;
    foreach (explode('.', $sMask) as $octet) {
        $iOctet = (int)$octet;
        while ($iOctet) {
            $iBits += $iOctet & 1;
            $iOctet >>= 1;
        }
    }
    return $iBits;
}

// List IPv4/Netmask for all Ethernet interfaces
function listIpAddresses()
{
    $iflist = array(); $if = NULL;
    $output = NULL;
    exec('/usr/sbin/ip addr show', $output);
    $ip = NULL;
    foreach ($output as $s) {
        $regs = NULL;
        if (preg_match('/^\d+:\s+([\w\.-]+)(@\w+)?:\s*<(.*)>/', $s, $regs)) {
            $if = $regs[1];
        } elseif (preg_match('|\s*inet (\d+\.\d+\.\d+.\d+)/(\d+) brd (\d+\.\d+\.\d+.\d+).+\s(([\w\.-]+)(:(\d+)?)?)\s*$|', trim($s), $regs)) {
            // Calcular IP de máscara a partir de número de bits
            $iMaskBits = $regs[2];
            $iMask = (0xFFFFFFFF << (32 - $iMaskBits)) & 0xFFFFFFFF;
            $sMaskIP = implode('.', array(
                ($iMask >> 24) & 0xFF,
                ($iMask >> 16) & 0xFF,
                ($iMask >>  8) & 0xFF,
                ($iMask      ) & 0xFF,
            ));
            if (!is_null($if) && !isset($iflist[$if])) {
                $iflist[$if] = array(
                    'ipaddr'    =>  $regs[1],
                    'broadcast' =>  $regs[3],
                    'netmask'   =>  $sMaskIP,
                    'network'   =>  construir_ip_red($regs[1], $sMaskIP),
                );
            }
        }
    }
    return $iflist;
}

function construir_ip_red($ip, $mascara)
{
    $ip = explode(".", $ip);
    $mascara = explode(".", $mascara);
    for ($i = 0; $i < 4; $i++) $ip[$i] = (int)$ip[$i] & (int)$mascara[$i];
    return implode(".", $ip);
}

// Starts DHCP and marks it for autostart. Returns TRUE on success.
function action_start($opt)
{
    $output = $ret = NULL;
    if (!is_dhcp_active()) {
        exec('/usr/bin/systemctl start kea-dhcp4 2>&1', $output, $ret);
        if ($ret != 0) return FALSE;
    }
    exec('/usr/bin/systemctl enable kea-dhcp4 2>&1', $output, $ret);
    return ($ret == 0);
}

// Stops DHCP and removes it from autostart. Returns TRUE on success
function action_stop($opt)
{
    $output = $ret = NULL;
    if (is_dhcp_active()) {
        exec('/usr/bin/systemctl stop kea-dhcp4 2>&1', $output, $ret);
        if ($ret != 0) return FALSE;
    }
    exec('/usr/bin/systemctl disable kea-dhcp4 2>&1', $output, $ret);
    return ($ret == 0);
}

// Check whether DHCP is running
function is_dhcp_active()
{
    $output = $ret = NULL;
    exec('/usr/bin/systemctl is-active --quiet kea-dhcp4 2>&1', $output, $ret);
    return ($ret == 0);
}

// Refresh the Kea configuration with fixed IPs from /var/www/db/network.db
function action_refresh($opt)
{
    $sPath = keaConfigPath();
    if (!file_exists($sPath)) {
        fprintf(STDERR, "ERR: Kea configuration file %s does not exist\n", $sPath);
        return FALSE;
    }
    $conf = json_decode(file_get_contents($sPath), TRUE);
    if (!is_array($conf) || !isset($conf['Dhcp4']['subnet4'][0])) {
        fprintf(STDERR, "ERR: cannot parse Kea DHCP configuration\n");
        return FALSE;
    }

    $dhcp4 = $conf['Dhcp4'];
    $subnet = $dhcp4['subnet4'][0];

    $sIpStart = $sIpEnd = $iLeaseTime = $sGateway = $sDNS1 = $sDNS2 = $sWINS = $sNEXTSERVER = $sFILENAME = NULL;
    $bPhonesOnly = FALSE;

    if (isset($subnet['pools'][0]['pool'])) {
        $parts = array_map('trim', explode('-', $subnet['pools'][0]['pool']));
        if (count($parts) == 2) {
            $sIpStart = $parts[0];
            $sIpEnd = $parts[1];
        }
    }
    if (isset($dhcp4['valid-lifetime']))
        $iLeaseTime = $dhcp4['valid-lifetime'];
    if (isset($subnet['next-server']))
        $sNEXTSERVER = $subnet['next-server'];
    if (isset($subnet['boot-file-name']))
        $sFILENAME = $subnet['boot-file-name'];
    if (isset($dhcp4['client-classes']) && count($dhcp4['client-classes']) > 0)
        $bPhonesOnly = TRUE;

    // Options may live either on the subnet or at the global scope
    foreach (array($subnet, $dhcp4) as $scope) {
        if (!isset($scope['option-data'])) continue;
        foreach ($scope['option-data'] as $od) {
            $name = isset($od['name']) ? $od['name'] : (isset($od['code']) ? $od['code'] : NULL);
            if ($name === 'routers' && is_null($sGateway)) {
                $sGateway = $od['data'];
            } elseif ($name === 'netbios-name-servers' && is_null($sWINS)) {
                $sWINS = $od['data'];
            } elseif ($name === 'domain-name-servers' && is_null($sDNS1)) {
                $list = array_map('trim', explode(',', $od['data']));
                $sDNS1 = $list[0];
                if (isset($list[1])) $sDNS2 = $list[1];
            }
        }
    }

    if (is_null($sIpStart) || is_null($sIpEnd)) {
        fprintf(STDERR, "ERR: could not find IP range in Kea configuration\n");
        return FALSE;
    }
    if (is_null($iLeaseTime)) $iLeaseTime = 7200;

    return configureDHCP($sIpStart, $sIpEnd, $iLeaseTime, $sGateway,
        $sDNS1, $sDNS2, $sWINS, $sNEXTSERVER, $sFILENAME, $bPhonesOnly);
}
?>
