#!/usr/local/bin/php-cgi -f
<?php
/*
 * rc.bootup
 *
 * originally based on m0n0wall (http://m0n0.ch/wall)
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
 * Copyright (c) 2009 Erik Kristensen
 * Copyright (c) 2005-2013 BSD Perimeter
 * Copyright (c) 2013-2016 Electric Sheep Fencing
 * Copyright (c) 2014-2024 Rubicon Communications, LLC (Netgate)
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// ======================= PHP TRACE =============================
$rcbSrcArray=0;
$rcbLoghandle=0;

function rcbLogSetup()
{
    global $rcbSrcArray;
    global $rcbLoghandle;
    // read source file into array, stripping out the log statements
    $srcFileName=__FILE__;
    $rcbSrcFile = @fopen($srcFileName, 'r');
    if ($rcbSrcFile) {
       $rcbSrcContent = fread($rcbSrcFile, filesize($srcFileName));
       $rcbSrcContent = str_replace("rcbLog();", "", $rcbSrcContent);
       //$rcbSrcArray = explode(PHP_EOL, fread($rcbSrcFile, filesize($srcFileName)));
       $rcbSrcArray = explode(PHP_EOL, $rcbSrcContent);
       array_unshift($rcbSrcArray, 'dummy entry to fix line mapping');
    }

    $rcbLoghandle = fopen('/tmp/rc.bootup.log', 'ab');
    fwrite($rcbLoghandle, 'Logging ' . __FILE__ . "\n");
}

function rcbLog()
{
  global $rcbLoghandle;
  global $rcbSrcArray;
  $bt = debug_backtrace();
  $caller = array_shift($bt);

  $date = date('d/m/Y H:i:s');
  $line = $date . ' L' . $caller['line'] . ': ' . $rcbSrcArray[$caller['line']] . "\n";
  fwrite($rcbLoghandle, $line);
}

rcbLogSetup();

// ======================= PHP TRACE =============================

require_once("pkg-utils.inc");

echo " done.\n";

echo "Initializing...";
echo ".";
require_once("/etc/inc/globals.inc");
echo ".";
require_once("/etc/inc/led.inc");
rcbLog();led_normalize();
echo ".";
if (led_count() >= 3) {
	led_kitt();
}

/* let the other functions know we're booting */
$pkg_interface = 'console';
$g['booting'] = true;

/* parse the configuration and include all functions used below */
require_once("/etc/inc/config.inc");
echo ".";
require_once("/etc/inc/config.console.inc");
echo ".";
require_once("/etc/inc/auth.inc");
echo ".";
require_once("/etc/inc/functions.inc");
echo ".";
require_once("/etc/inc/filter.inc");
echo ".";
require_once("/etc/inc/shaper.inc");
echo ".";
require_once("/etc/inc/ipsec.inc");
echo ".";
require_once("/etc/inc/vpn.inc");
echo ".";
require_once("/etc/inc/openvpn.inc");
echo ".";
require_once("/etc/inc/captiveportal.inc");
echo ".";
require_once("/etc/inc/rrd.inc");
echo ".";
require_once("/etc/inc/pfsense-utils.inc");
echo ".";
require_once("/etc/inc/notices.inc");
echo ".";

/* Bring in BE support if available */
$has_be_support = false;
if (function_exists('libbe_init')) {
	require_once('system_be.inc');
	echo ".";
	$has_be_support = (be_bootenv_check() && ($be_handle = libbe_init()));
}

/* Setup notice queues */
rcbLog();notices_setup();

/* Post any boot verification failures */
if ($has_be_support && ($failed_be = be_get_failed_previous($be_handle))) {
	file_notice(gettext('System Update'), sprintf(gettext('Boot verification failed for %s. %s was automatically rebooted back into %s.'),
		$failed_be, g_get('product_label'), be_active_name($be_handle)), 'warning');
}

/* get system memory amount */
$memory = get_memory();
$physmem = $memory[0];
$realmem = $memory[1];
echo " done.\n";


/* save dmesg output to file */
rcbLog();system_dmesg_save();

/* check whether config reset is desired (via hardware button on WRAP/ALIX) */
rcbLog();system_check_reset_button();

/* remove previous firmware upgrade if present */
if (file_exists("/root/firmware.tgz")) {
	unlink("/root/firmware.tgz");
}

/* restore RRD, SSH keys and extra data on bsdinstall config restore
 * see https://redmine.pfsense.org/issues/12518 */
if (file_exists("{$g['conf_path']}/installer_copied_config") &&
    file_exists("{$g['conf_path']}/restore_config_data")) {
	copy("/cf/conf/config.xml", "{$g['tmp_path']}/config_to_restore.xml");
	restore_backup("{$g['tmp_path']}/config_to_restore.xml");
	@unlink("{$g['tmp_path']}/config_to_restore.xml");
	@unlink("{$g['conf_path']}/installer_copied_config");
	@unlink("{$g['conf_path']}/restore_config_data");
}

/* Triggering of the initial setup wizard after reboot has been requested */
if (file_exists("{$g['conf_path']}/trigger_initial_wizard_after_reboot")) {
	touch("{$g['conf_path']}/trigger_initial_wizard");
	@unlink("{$g['conf_path']}/trigger_initial_wizard_after_reboot");
}

/* start devd (dhclient now uses it) */
echo "Starting device manager (devd)...";
rcbLog();mute_kernel_msgs();
rcbLog();start_devd();
rcbLog();set_device_perms();
rcbLog();unmute_kernel_msgs();
echo "done.\n";

echo "Loading configuration...";
rcbLog();parse_config_bootup();
echo "done.\n";

rcbLog();mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid 2>/dev/null");

if (isset($config['system']['trigger_virt_setup'])) {
	rcbLog();netgate_hardware_setup();
} elseif (file_exists("{$g['conf_path']}/trigger_initial_wizard") && !file_exists("{$g['conf_path']}/assign_complete")) {
	// Only do the alternate interface checks if:
	// 1) The user has not yet run the initial wizard; and
	// 2) The user has not used the console menu to setup interface assignments
	if (!netgate_hardware_setup()) {
		rcbLog();check_for_alternate_interfaces();
	}
}

/* Convert configuration
 * This must happen before the interface mismatch test, see
 * https://redmine.pfsense.org/issues/7809 */
echo "Updating configuration...";
rcbLog();convert_config();
echo "done.\n";

/*
 *	Determine if we need to throw a interface exception
 *	and ask the user to reassign interfaces.  This will
 *	avoid a reboot and that is a good thing.
 */
while (is_interface_mismatch() == true) {
	led_assigninterfaces();
	if (isset($config['revision'])) {
		if (file_exists("{$g['tmp_path']}/missing_interfaces")) {
			echo "Warning: Configuration references interfaces that do not exist: " . file_get_contents("{$g['tmp_path']}/missing_interfaces") . "\n";
		}
		echo "\nNetwork interface mismatch -- Running interface assignment option.\n";
	} else {
		echo "\nDefault interfaces not found -- Running interface assignment option.\n";
	}
	rcbLog();$ifaces = get_interface_list();
	if (is_array($ifaces)) {
		foreach ($ifaces as $iface => $ifdata) {
			rcbLog();interfaces_bring_up($iface);
		}
	}
	if (set_networking_interfaces_ports() == -1) {
		echo "\npfSense cannot continue without at least one Network Interface Card.\n";
		echo "\nHalting the system.\n";
		system("/sbin/shutdown -h now");
		exit(0);
	}
	rcbLog();reload_interfaces_sync();
	rcbLog();led_kitt();
}

/* enable optional crypto modules */
echo "Loading cryptographic accelerator drivers...";
rcbLog();load_crypto();
echo "done.\n";

/* set additional sysctls not defined in loader.conf */
echo "Setting up extended sysctls...";
rcbLog();system_setup_sysctl();
echo "done.\n";

$file = '/deferred_pkg_install';
if (file_exists($file)) {
	echo "Executing deferred package installation scripts...";
	rcbLog();register_all_installed_packages(true);
	unlink($file);
	echo "done.\n";
}

/* run any early shell commands specified in config.xml */
echo "Executing early shell commands...";
rcbLog();system_do_shell_commands(1);
echo "done.\n";

/* enable optional thermal sensor modules */
rcbLog();load_thermal_hardware();

/* set up our timezone */
rcbLog();system_timezone_configure();

/* set up our hostname */
rcbLog();system_hostname_configure();

/* make hosts file */
rcbLog();system_hosts_generate();

/* disable CARP prior to configuring interfaces */
rcbLog();enable_carp(false);

/* configure loopback interface */
rcbLog();interfaces_loopback_configure();

/* Setup Local CA Trust Store */
rcbLog();ca_setup_trust_store();

/* If the system uses ZFS and has compression enabled for /var/log, disable log
 * compression by default. See https://redmine.pfsense.org/issues/12011
 */
$varlog_compression_state = 'off';
if (is_module_loaded('zfs.ko')) {
	rcbLog();exec("/sbin/zfs get -H compression /var/log | /usr/bin/awk '{print $3;}'", $varlog_compression_state);
	$varlog_compression_state = $varlog_compression_state[0];
}
if (file_exists("{$g['conf_path']}/trigger_initial_wizard") &&
    (trim($varlog_compression_state) != 'off')) {
	touch("{$g['conf_path']}/syslog_default_uncompressed");
}
/* start syslogd */
rcbLog();system_syslogd_start();

/* set pam shell authentication backend */
rcbLog();set_pam_auth();

/* Log the RAM disk restore messages. */
if (file_exists("/var/log/restore_ramdisk_store.boot")) {
	rcbLog();exec("/usr/bin/logger -f /var/log/restore_ramdisk_store.boot");
}

/* Load the switches settings. */
rcbLog();switches_configure();

/* setup interface microcode which improves tcp/ip speed */
echo "Setting up interfaces microcode...";
rcbLog();setup_microcode();
echo "done.\n";

if (isset($config['system']['mds_disable']) &&
    (strlen($config['system']['mds_disable']) > 0)) {
	set_single_sysctl("hw.mds_disable" , (int)$config['system']['mds_disable']);
}

/* remove leftover dhcp6c lock file if it exist */
if (file_exists("/tmp/dhcp6c_lock")) {
	@unlink("/tmp/dhcp6c_lock");
	echo("Removed leftover dhcp6c lock file: /tmp/dhcp6c_lock\n");
}
if (file_exists("/tmp/dhcp6c_ifs")) {
	@unlink("/tmp/dhcp6c_ifs");
}

/* set up interfaces */
if (!$debugging) {
	mute_kernel_msgs();
}
rcbLog();interfaces_configure();
rcbLog();interfaces_sync_setup();
if (!$debugging) {
	unmute_kernel_msgs();
}

/* re-make hosts file after configuring interfaces */
rcbLog();system_hosts_generate();

/* start sshd */
init_config_arr(array('system', 'ssh'));
if (isset($config['system']['ssh']['enable'])) {
	echo "Starting Secure Shell Services...";
	rcbLog();send_event("service reload sshd");
	echo "done.\n";
}

/* start OpenVPN server & clients */
echo "Syncing OpenVPN settings...";
rcbLog();openvpn_resync_all();
echo "done.\n";

/* generate resolv.conf */
rcbLog();system_resolvconf_generate();

/* Setup pflow */
rcbLog();filter_pflow_configure();

/* setup altq + pf */
rcbLog();filter_configure_sync();

/* start pflog */
echo "Starting PFLOG...";
rcbLog();filter_pflog_start();
echo "done.\n";

/* reconfigure our gateway monitor */
rcbLog();setup_gateways_monitor();

/* set up static routes */
echo "Setting up static routes...";
rcbLog();system_routing_configure();
echo "done.\n";

init_config_arr(array('unbound'));
init_config_arr(array('dnsmasq'));
if (isset($config['unbound']['enable']) ||
    isset($config['dnsmasq']['enable'])) {
	echo "Setting up DNSs...\n";
	/* start dnsmasq service */
	rcbLog();services_dnsmasq_configure();

	/* start unbound service */
	rcbLog();services_unbound_configure();
}

echo "Synchronizing user settings...";
rcbLog();local_reset_accounts();
echo "done.\n";

/* configure cron service */
echo "Configuring CRON...";
rcbLog();configure_cron();
echo "done.\n";

/* enable routing */
rcbLog();system_routing_enable();

/* Set initial time by using IP addresses in case DNS is not available
 * This works around issues with DNSSEC and gives the firewall a better chance
 * of having a highly accurate clock at boot.
 * NG 7352, NG 7447
 */

/* Default to Google Public NTP servers */
$ntp_boot_time_servers = '216.239.35.0 216.239.35.4 216.239.35.8 216.239.35.12';
/* File to allow users to override default behavior.
 * Servers must be a single line with space-separated IP address entries ONLY as
 * DNS may not be functional. */
$ntp_boot_time_servers_override = '/conf/ntp-boot-time-servers';

/* Handle user override of NTP bootstrap behavior */
if (file_exists($ntp_boot_time_servers_override)) {
	if (filesize($ntp_boot_time_servers_override) > 0) {
		/* Read servers from file if the file is not empty. */
		$servers = file_get_contents($ntp_boot_time_servers_override);
		$checkservers = explode(' ', trim($servers));
		$goodservers = array();
		/* Only add entries which are valid IP addresses. */
		foreach ($checkservers as $ntpserver) {
			if (is_ipaddr($ntpserver)) {
				$goodservers[] = escapeshellarg($ntpserver);
			}
		}
		$ntp_boot_time_servers = implode(' ', $goodservers);
	} else {
		/* Disable check if the file exists but is empty. */
		$ntp_boot_time_servers = '';
	}
}

if (!empty($ntp_boot_time_servers)) {
	echo gettext("Bootstrapping clock...");
	rcbLog();mwexec("/usr/bin/timeout -k 45 30 /usr/local/sbin/ntpd -g -q -c /dev/null {$ntp_boot_time_servers}");
	echo gettext("done.") . "\n";
}

/* Enable ntpd */
rcbLog();system_ntp_configure();

if ($realmem > 0 and $realmem < 65) {
	echo "System has less than 65 megabytes of ram {$realmem}.  Delaying webConfigurator startup.\n";
	/* start webConfigurator up on final pass */
	rcbLog();mwexec("/usr/local/sbin/pfSctl -c 'service restart webgui'");
} else {
	/* start web server */
	rcbLog();system_webgui_start();
}

/* Configure console (and serial port - if necessary). */
rcbLog();console_configure();

/* start DHCP service */
rcbLog();services_dhcpd_configure();

/* start dhcpleases dhcp hosts leases program */
rcbLog();system_dhcpleases_configure();

/* start DHCP relay */
rcbLog();services_dhcrelay_configure();

/* start DHCP6 relay */
rcbLog();services_dhcrelay6_configure();

/* dyndns service updates */
rcbLog();send_event("service reload dyndnsall");

/* Run a filter configure now that most all services have started */
rcbLog();filter_configure_sync();

/* setup pppoe and pptp */
rcbLog();vpn_setup();

/* start the captive portal */
rcbLog();captiveportal_configure();

/* start Voucher support */
rcbLog();voucher_configure();

/* run any shell commands specified in config.xml */
rcbLog();system_do_shell_commands();

/* start IPsec tunnels */
rcbLog();$ipsec_dynamic_hosts = ipsec_configure();

/* start SNMP service */
rcbLog();services_snmpd_configure();

/* power down hard drive if needed/set */
rcbLog();system_set_harddisk_standby();

/* lock down console if necessary */
rcbLog();reload_ttys();

/* load graphing functions */
rcbLog();enable_rrd_graphing();

/* enable watchdog if supported */
rcbLog();enable_watchdog();

/* if <system><afterbootupshellcmd> exists, execute the command */
if ($config['system']['afterbootupshellcmd'] <> "") {
	echo "Running afterbootupshellcmd {$config['system']['afterbootupshellcmd']}\n";
	rcbLog();mwexec($config['system']['afterbootupshellcmd']);
}

if ($physmem < $g['minimum_ram_warning']) {
	file_notice("{$g['product_label']}MemoryRequirements", "{$g['product_label']} requires at least {$g['minimum_ram_warning_text']} of RAM.  Expect unusual performance.  This platform is not supported.", "Memory", "", 1);
	rcbLog();set_sysctl(array(
		"net.inet.tcp.recvspace" => "4096",
		"net.inet.tcp.sendspace" => "4096"
	));
}

if (file_exists("/conf/ram_disks_failed")) {
	file_notice("RAM Disks", "RAM disk creation failed. Reverted to traditional storage. Check RAM disk sizes.", "RAM Disks");
}

/* if we are operating at 1000 then increase timeouts.
   this was never accounted for after moving to 1000 hz */
$kern_hz = get_single_sysctl('kern.clockrate');
$kern_hz = substr($kern_hz, strpos($kern_hz, "hz = ") + 5);
$kern_hz = substr($kern_hz, 0, strpos($kern_hz, ","));
if ($kern_hz == "1000") {
	set_single_sysctl("net.inet.tcp.rexmit_min" , "30");
}

/* start the igmpproxy daemon */
rcbLog();services_igmpproxy_configure();

/* start the upnp daemon if it is enabled */
rcbLog();upnp_start();

/* If powerd is enabled, lets launch it */
rcbLog();activate_powerd();

/* Set preferred protocol */
rcbLog();prefer_ipv4_or_ipv6();

/* Resync / Reinstall packages if need be */
if (file_exists("{$g['conf_path']}/needs_package_sync")) {
	echo "Triggering packages reinstallation in background\n";
	rcbLog();mwexec_bg("{$g['etc_path']}/rc.package_reinstall_all");
} else {
	/* Detect installed binary pkgs that are not registered in the system */
	rcbLog();register_all_installed_packages();
}

/* Give syslogd a kick after everything else has been initialized, otherwise it can occasionally
   fail to route syslog messages properly on both IPv4 and IPv6 */
rcbLog();system_syslogd_start();

/* done */
$g['booting'] = false;
@unlink("{$g['varrun_path']}/booting");

/* re-enable CARP */
rcbLog();enable_carp();

/* If there are ipsec dynamic hosts try again to reload the tunnels as rc.newipsecdns does */
if ($ipsec_dynamic_hosts) {
	echo gettext("Configuring IPsec VPN for dynamic hosts... ");
	rcbLog();ipsec_configure();

	/* restart dpinger if PH1 remote gateway == fqdn and PH2 mode == VTI
	 * see https://redmine.pfsense.org/issues/12763 */
	foreach ($config['ipsec']['phase1'] as $p1) {
		if (!isset($p1['mobile']) && !isset($p1['disabled']) && is_fqdn($p1['remote-gateway'])) {
			foreach ($config['ipsec']['phase2'] as $p2) {
				if (!isset($p2['disabled']) && ($p2['mode'] == 'vti')) {
					rcbLog();setup_gateways_monitor();
					break 2;
				}
			}
		}
	}

	echo gettext("done") . "\n";
}
if ($ipsec_dynamic_hosts || !empty($filterdns)) {
	echo gettext("Configuring filter for dynamic IPsec VPN hosts... ");
	rcbLog();filter_configure();
	echo gettext("done") . "\n";
}

rcbLog();led_normalize();

rcbLog();notify_all_remote("Bootup complete");
?>
