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

/*
 * Copyright (C) 2017-2024 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';

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

if (empty($argument)) {
    $interface = 'wan';
    $device = get_real_interface($interface, 'inet6');
} 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;
}

/* make sure only one script runs at a time beyond this point */
$fp = fopen('/tmp/newwanipv6_' . $argument, 'a+e');
if (!$fp || !flock($fp, LOCK_EX | LOCK_NB)) {
    /* let go if not a forceful reload, otherwise block and wait */
    if ($force != 'yes' || !$fp || !flock($fp, LOCK_EX)) {
        fclose($fp);
        return;
    }
}

/* wait for DAD to complete to avoid discarding tentative address */
waitfordad(2);

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

if ($force == 'no') {
    /* we used to log here but many have complained about spurious log lines caused by RAs */
    return;
}

list ($ip) = interfaces_primary_address6($interface);
if (!is_ipaddr($ip)) {
    /*
     * The IP is only for diagnostics now, and this means the configured
     * settings for the client do not match the server action.
     */
    $ip = 'misconfigured';
}

log_msg("IP renewal starting (address: {$ip}, interface: {$interface}, device: {$device})");

interfaces_vips_configure($interface, 6);

$greifs = link_interface_to_gre($interface, true, 6);
$gififs = link_interface_to_gif($interface, true, 6);

switch (isset($config['system']['ipv6allow']) ? ($config['interfaces'][$interface]['ipaddrv6'] ?? 'none') : 'none') {
    case 'slaac':
        /* require immediate reconfiguration before reconfiguring clients */
        plugins_configure('dhcp', false, ['inet6']);
        break;
    default:
        /*
         * XXX We would like to discourage SLAAC addressing here but
         * in reality this is highly ISP dependent and the kernel is
         * not forthcoming in the quest as it likes to prefer this because
         * it came first breaking some setups but making others work at
         * the same time making it impractical to infer which setup we
         * currently require.
         */
        break;
}

interfaces_restart_by_device(false, array_merge($greifs, $gififs));

$interfaces = array_keys(link_interface_to_track6($interface, true));
array_unshift($interfaces, $interface);

system_routing_configure(false, $interfaces, true, 'inet6');

filter_configure_sync();

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