#!/usr/local/bin/php
<?php

/*
 * Copyright (C) 2017-2025 Franco Fichtner <franco@opnsense.org>
 * Copyright (C) 2006 Scott Ullrich <sullrich@gmail.com>
 * Copyright (C) 2003-2005 Manuel Kasper <mk@neon1.net>
 * 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("auth.inc");
require_once("filter.inc");
require_once("util.inc");
require_once("system.inc");
require_once("interfaces.inc");

$argument = isset($argv[1]) ? trim($argv[1]) : '';
$force = !empty($argv[2]) ? 'yes' : 'no';
$family = 'inet';
$family_int = 4;

exit_on_bootup(function ($argument) {
    log_msg("IP renewal deferred during boot on '{$argument}'");
    file_put_contents('/tmp/newwanip_' . $argument, $argument);
}, [$argument]);

if (empty($argument)) {
    $interface = 'wan';
    $device = get_real_interface($interface);
} else {
    $interface = convert_real_interface_to_friendly_interface_name($argument);
    $device = $argument;
}

if (!isset($config['interfaces'][$interface]['enable'])) {
    log_msg("Interface '{$interface}' ($device) is disabled or empty, nothing to do.", LOG_WARNING);
    return;
}

/* this may be required to cleanse the DNS information no longer available */
system_resolver_configure();

list ($ip) = interfaces_primary_address($interface);
if (!is_ipaddr($ip)) {
    log_msg("Failed to detect IP for interface {$interface}", LOG_INFO);
    return;
}

$gw = OPNsense\Interface\Autoconf::getRouter($device, $family);

$cacheip_file = "/tmp/{$device}_oldip";
$cacheip = trim(@file_get_contents($cacheip_file));

$cachegw_file = "/tmp/{$device}_oldgw";
$cachegw = trim(@file_get_contents($cachegw_file));

if ($force == 'no' && $ip == $cacheip) {
    log_msg("No IP change detected (current: {$ip}, interface: {$interface})", LOG_INFO);
    return;
}

log_msg("IP renewal starting (new: {$ip}, old: {$cacheip}, interface: {$interface}, device: {$device}, force: {$force})");

interfaces_vips_configure($interface, $family_int);

$auxdevs = [];

/* find and reconfigure all linked devices  */
foreach (link_interface_to_gre($interface, true, $family_int) as $linked) {
    $auxdevs[] = $linked;
}
foreach (link_interface_to_gif($interface, true, $family_int) as $linked) {
    $auxdevs[] = $linked;
}

switch (isset($config['system']['ipv6allow']) ? ($config['interfaces'][$interface]['ipaddrv6'] ?? 'none') : 'none') {
    case '6to4':
        interface_6to4_configure($interface, $config['interfaces'][$interface], true);
        system_routing_configure(false, $interface, true, 'inet6'); /* interface recreation breaks attached routes */
        break;
    case '6rd':
        interface_6rd_configure($interface, $config['interfaces'][$interface], true);
        system_routing_configure(false, $interface, true, 'inet6'); /* interface recreation breaks attached routes */
        break;
    default:
        break;
}

/* linked devices that are assigned need to be reconfigured now */
interfaces_restart_by_device(false, $auxdevs);

/*
 * Interface reconfigure finished here so sync
 * firewall groups in case of destroy/create use.
 */
ifgroup_setup();

$interfaces = [/* empty for v6 compat */];
array_unshift($interfaces, $interface);

system_routing_configure(false, $interfaces, true, $family);

filter_configure_sync();

if (is_ipaddr($cacheip) && $ip != $cacheip) {
    log_msg("IP address change detected, killing states for $cacheip");
    mwexecf('/sbin/pfctl -k 0.0.0.0/0 -k %s', $cacheip);
    mwexecf('/sbin/pfctl -k %s', $cacheip);
}

@file_put_contents($cacheip_file, $ip . PHP_EOL);

if (is_ipaddr($cachegw) && is_ipaddr($gw) && $gw != $cachegw) {
    log_msg("IP gateway change detected, killing states for $cachegw");
    mwexecf('/sbin/pfctl -k gateway -k %s', $cachegw);
}

@file_put_contents($cachegw_file, $gw . PHP_EOL);

plugins_configure('vpn', false, [$interfaces, $family]);
plugins_configure('newwanip', false, [$interfaces, $family]);
