PHP8 support

This commit is contained in:
bergware
2023-02-27 11:17:14 +01:00
parent a21c544bac
commit ba78296ab9
6 changed files with 133 additions and 122 deletions
+12 -9
View File
@@ -11,6 +11,10 @@
*/
?>
<?
$docroot = $docroot ?? $_SERVER['DOCUMENT_ROOT'] ?: '/usr/local/emhttp';
require_once "$docroot/webGui/include/Wrappers.php";
$device = $_POST['device']??'';
$name = $_POST['name']??'';
$action = $_POST['action']??'';
@@ -23,9 +27,7 @@ function prefix($key) {
function emhttpd($cmd) {
global $state, $csrf;
$ch = curl_init("http://127.0.0.1/update");
$options = array(CURLOPT_UNIX_SOCKET_PATH => '/var/run/emhttpd.socket',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => "$cmd&startState=$state&csrf_token=$csrf");
$options = [CURLOPT_UNIX_SOCKET_PATH => '/var/run/emhttpd.socket', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => "$cmd&startState=$state&csrf_token=$csrf"];
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);
@@ -33,7 +35,7 @@ function emhttpd($cmd) {
switch ($device) {
case 'New':
emhttpd("cmdSpin$action=$name");
emhttpd("cmdSpin{$action}={$name}");
break;
case 'Clear':
emhttpd("clearStatistics=true");
@@ -46,16 +48,17 @@ default:
}
if (substr($name,-1) != '*') {
// spin up/down single device
emhttpd("cmdSpin$action=$name");
emhttpd("cmdSpin{$action}={$name}");
break;
}
// spin up/down group of devices
$disks = (array)parse_ini_file('state/disks.ini',true);
$disks = @parse_ini_file('state/disks.ini',true) ?: [];
// remove '*' from name
$name = substr($name,0,-1);
foreach ($disks as $disk) {
if ($disk['status'] != 'DISK_OK') continue;
$array = ($name=='array' && in_array($disk['type'],['Parity','Data']));
if ($array || prefix($disk['name'])==$name) emhttpd("cmdSpin$action={$disk['name']}");
if (_var($disk,'status') != 'DISK_OK') continue;
$array = ($name=='array' && in_array(_var($disk,'type'),['Parity','Data']));
if ($array || prefix(_var($disk,'name'))==$name) emhttpd("cmdSpin{$action}="._var($disk,'name'));
}
break;
}
+1 -1
View File
@@ -121,7 +121,7 @@ function translate($key) {
// main
$language = [];
$locale = $_SESSION['locale'] ?? ($login_locale??'');
$locale = $_SESSION['locale'] ?? $login_locale ?? '';
$return = "function _(t){return t;}";
$jscript = "$docroot/webGui/javascript/translate.en_US.js";
$root = "$docroot/languages/en_US/helptext.txt";
+47 -46
View File
@@ -12,6 +12,7 @@
?>
<?
$docroot = $docroot ?? $_SERVER['DOCUMENT_ROOT'] ?: '/usr/local/emhttp';
// add translations
$_SERVER['REQUEST_URI'] = 'settings';
require_once "$docroot/webGui/include/Translations.php";
@@ -19,14 +20,14 @@ require_once "$docroot/webGui/include/Helpers.php";
function host_lookup_ip($host) {
$result = @dns_get_record($host, DNS_A);
$ip = ($result) ? $result[0]['ip']??'' : '';
$ip = $result ? _var($result[0],'ip') : '';
return($ip);
}
function rebindDisabled() {
global $isLegacyCert;
$rebindtesturl = $isLegacyCert ? "rebindtest.unraid.net" : "rebindtest.myunraid.net";
// DNS Rebind Protection - this checks the server but clients could still have issues
$validResponse = array("192.168.42.42", "fd42");
$validResponse = ["192.168.42.42", "fd42"];
$response = host_lookup_ip($rebindtesturl);
return in_array(explode('::',$response)[0], $validResponse);
}
@@ -69,24 +70,24 @@ function verbose_output($httpcode, $result) {
if (!$cli || !$verbose) return;
if ($anon) echo "(Output is anonymized, use '-vv' to see full details)".PHP_EOL;
echo "Unraid OS {$var['version']}".((strpos($plgversion, "base-") === false) ? " with My Servers plugin version {$plgversion}" : '').PHP_EOL;
echo "Unraid OS "._var($var,'version','???').((strpos($plgversion, "base-") === false) ? " with My Servers plugin version {$plgversion}" : '').PHP_EOL;
echo ($isRegistered) ? "{$icon_ok}Signed in to Unraid.net as {$myservers['remote']['username']}".PHP_EOL : "{$icon_warn}Not signed in to Unraid.net".PHP_EOL ;
echo "Use SSL is {$nginx['NGINX_USESSL']}".PHP_EOL;
echo "Use SSL is "._var($nginx,'NGINX_USESSL','No').PHP_EOL;
echo (rebindDisabled()) ? "{$icon_ok}Rebind protection is disabled" : "{$icon_warn}Rebind protection is enabled";
echo " for ".($isLegacyCert ? "unraid.net" : "myunraid.net").PHP_EOL;
if ($post) {
$wanip = trim(@file_get_contents("https://wanip4.unraid.net/"));
// check the data
$certhostname = $nginx['NGINX_CERTNAME'];
$certhostname = _var($nginx,'NGINX_CERTNAME');
if ($certhostname) {
// $certhostname is $nginx['NGINX_CERTNAME'] (certificate_bundle.pem)
$certhostip = host_lookup_ip(generate_internal_host($certhostname, $post['internalip']));
$certhosterr = ($certhostip != $post['internalip']);
$certhostip = host_lookup_ip(generate_internal_host($certhostname, _var($post,'internalip')));
$certhosterr = ($certhostip != _var($post,'internalip'));
}
if ($post['internalhostname'] != $certhostname) {
if (_var($post,'internalhostname') != $certhostname) {
// $post['internalhostname'] is $nginx['NGINX_LANMDNS'] (no cert, or Server_unraid_bundle.pem) || $nginx['NGINX_CERTNAME'] (certificate_bundle.pem)
$internalhostip = host_lookup_ip(generate_internal_host($post['internalhostname'], $post['internalip']));
$internalhosterr = ($internalhostip != $post['internalip']);
$internalhostip = host_lookup_ip(generate_internal_host(_var($post,'internalhostname'), _var($post,'internalip')));
$internalhosterr = ($internalhostip != _var($post,'internalip'));
}
if (!empty($post['externalhostname'])) {
// $post['externalhostname'] is $nginx['NGINX_CERTNAME'] (certificate_bundle.pem)
@@ -109,20 +110,20 @@ function verbose_output($httpcode, $result) {
if (!empty($post['keyfile'])) $post['keyfile'] = "[redacted]";
// output notes
if (!empty($post['internalprotocol']) && !empty($post['internalhostname']) && !empty($post['internalport'])) {
$localurl = $post['internalprotocol']."://".generate_internal_host($post['internalhostname'], $post['internalip']).format_port($post['internalport']);
$localurl = $post['internalprotocol']."://".generate_internal_host($post['internalhostname'], _var($post,'internalip')).format_port($post['internalport']);
echo 'Local Access url: '.$localurl.PHP_EOL;
if ($internalhostip) {
// $internalhostip will not be defined for .local domains, ok to skip
echo ($internalhosterr) ? $icon_warn : $icon_ok;
echo generate_internal_host($post['internalhostname'], $post['internalip'])." resolves to {$internalhostip}";
echo ($internalhosterr) ? ", it should resolve to {$post['internalip']}" : "";
echo generate_internal_host($post['internalhostname'], _var($post,'internalip'))." resolves to {$internalhostip}";
echo ($internalhosterr) ? ", it should resolve to "._var($post,'internalip') : "";
echo PHP_EOL;
}
if ($certhostname) {
echo ($certhosterr) ? $icon_warn : $icon_ok;
echo generate_internal_host($certhostname, $post['internalip']).' ';
echo generate_internal_host($certhostname, _var($post,'internalip')).' ';
echo ($certhostip) ? "resolves to {$certhostip}" : "does not resolve to an IP address";
echo ($certhosterr) ? ", it should resolve to {$post['internalip']}" : "";
echo ($certhosterr) ? ", it should resolve to "._var($post,'internalip') : "";
echo PHP_EOL;
}
if ($remoteaccess == 'yes' && !empty($post['externalprotocol']) && !empty($post['externalhostname']) && !empty($post['externalport'])) {
@@ -130,7 +131,7 @@ function verbose_output($httpcode, $result) {
echo 'Remote Access url: '.$remoteurl.PHP_EOL;
echo ($externalhosterr) ? $icon_warn : $icon_ok;
echo generate_external_host($post['externalhostname'], $wanip).' ';
echo ($externalhosterr) ? "does not resolve to an IP address" : "resolves to {$externalhostip}";
echo ($externalhosterr) ? "does not resolve to an IP address" : "resolves to ".($externalhostip??'');
echo PHP_EOL;
}
if ($reloadNginx) {
@@ -179,9 +180,9 @@ if ($cli && ($argc > 1) && $argv[1] == "-v") {
if ($cli && ($argc > 1) && $argv[1] == "-vv") {
$verbose = true;
}
$var = parse_ini_file('/var/local/emhttp/var.ini');
$nginx = parse_ini_file('/var/local/emhttp/nginx.ini');
$is69 = version_compare($var['version'],"6.9.9","<");
$var = @parse_ini_file('/var/local/emhttp/var.ini') ?: [];
$nginx = @parse_ini_file('/var/local/emhttp/nginx.ini') ?: [];
$is69 = version_compare(_var($var,'version'),"6.9.9","<");
$reloadNginx = false;
$dnserr = false;
$icon_warn = "⚠️ ";
@@ -201,11 +202,11 @@ if (empty($myservers['remote']['wanport'])) {
}
// remoteaccess, externalport
if ($cli) {
$remoteaccess = (empty($nginx['NGINX_WANFQDN'])) ? 'no' : 'yes';
$remoteaccess = empty($nginx['NGINX_WANFQDN']) ? 'no' : 'yes';
$externalport = $myservers['remote']['wanport'];
} else {
$remoteaccess = $_POST['remoteaccess']??'no';
$externalport = intval($_POST['externalport']??443);
$remoteaccess = _var($_POST,'remoteaccess','no');
$externalport = intval(_var($_POST,'externalport',443));
if ($remoteaccess != 'yes') {
$remoteaccess = 'no';
@@ -237,48 +238,48 @@ $isRegistered = !empty($myservers['remote']['username']);
// protocols, hostnames, ports
$internalprotocol = 'http';
$internalport = $nginx['NGINX_PORT'];
$internalhostname = $nginx['NGINX_LANMDNS'];
$internalport = _var($nginx,'NGINX_PORT');
$internalhostname = _var($nginx,'NGINX_LANMDNS');
$externalprotocol = 'https';
// keyserver will expand *.hash.myunraid.net or add www to hash.unraid.net as needed
$externalhostname = $nginx['NGINX_CERTNAME'];
$isLegacyCert = preg_match('/.*\.unraid\.net$/', $nginx['NGINX_CERTNAME']);
$isWildcardCert = preg_match('/.*\.myunraid\.net$/', $nginx['NGINX_CERTNAME']);
$internalip = $nginx['NGINX_LANIP'];
$externalhostname = _var($nginx,'NGINX_CERTNAME');
$isLegacyCert = preg_match('/.*\.unraid\.net$/', _var($nginx,'NGINX_CERTNAME'));
$isWildcardCert = preg_match('/.*\.myunraid\.net$/', _var($nginx,'NGINX_CERTNAME'));
$internalip = _var($nginx,'NGINX_LANIP');
if ($nginx['NGINX_USESSL']=='yes') {
if (_var($nginx,'NGINX_USESSL')=='yes') {
// When NGINX_USESSL is 'yes' in 6.9, it could be using either Server_unraid_bundle.pem or certificate_bundle.pem
// When NGINX_USESSL is 'yes' in 6.10, it is is using Server_unraid_bundle.pem
$internalprotocol = 'https';
$internalport = $nginx['NGINX_PORTSSL'];
if ($is69 && $nginx['NGINX_CERTNAME']) {
$internalport = _var($nginx,'NGINX_PORTSSL');
if ($is69 && _var($nginx,'NGINX_CERTNAME')) {
// this is from certificate_bundle.pem
$internalhostname = $nginx['NGINX_CERTNAME'];
$internalhostname = _var($nginx,'NGINX_CERTNAME');
}
}
if ($nginx['NGINX_USESSL']=='auto') {
if (_var($nginx,'NGINX_USESSL')=='auto') {
// NGINX_USESSL cannot be 'auto' in 6.9, it is either 'yes' or 'no'
// When NGINX_USESSL is 'auto' in 6.10, it is using certificate_bundle.pem
$internalprotocol = 'https';
$internalport = $nginx['NGINX_PORTSSL'];
$internalport = _var($nginx,'NGINX_PORTSSL');
// keyserver will expand *.hash.myunraid.net as needed
$internalhostname = $nginx['NGINX_CERTNAME'];
$internalhostname = _var($nginx,'NGINX_CERTNAME');
}
// My Servers version
$plgversion = file_exists("/var/log/plugins/dynamix.unraid.net.plg") ? trim(@exec('/usr/local/sbin/plugin version /var/log/plugins/dynamix.unraid.net.plg 2>/dev/null'))
: ( file_exists("/var/log/plugins/dynamix.unraid.net.staging.plg") ? trim(@exec('/usr/local/sbin/plugin version /var/log/plugins/dynamix.unraid.net.staging.plg 2>/dev/null'))
: 'base-'.$var['version'] );
$plgversion = file_exists("/var/log/plugins/dynamix.unraid.net.plg") ? trim(exec('/usr/local/sbin/plugin version /var/log/plugins/dynamix.unraid.net.plg 2>/dev/null'))
: (file_exists("/var/log/plugins/dynamix.unraid.net.staging.plg") ? trim(exec('/usr/local/sbin/plugin version /var/log/plugins/dynamix.unraid.net.staging.plg 2>/dev/null'))
: 'base-'._var($var,'version'));
// only proceed when when signed in or when legacy unraid.net SSL certificate exists
if (!$isRegistered && !$isLegacyCert) {
response_complete(406, array('error' => _('Nothing to do')));
response_complete(406, ['error' => _('Nothing to do')]);
}
// keyfile
$keyfile = empty($var['regFILE']) ? false : @file_get_contents($var['regFILE']);
if ($keyfile === false) {
response_complete(406, array('error' => _('Registration key required')));
response_complete(406, ['error' => _('Registration key required')]);
}
$keyfile = @base64_encode($keyfile);
@@ -292,7 +293,7 @@ if ($isLegacyCert) {
// enable local ddns regardless of use_ssl value
$post['internalip'] = $internalip;
// if host.unraid.net does not resolve to the internalip and DNS Rebind Protection is disabled, disable caching
if (host_lookup_ip(generate_internal_host($nginx['NGINX_CERTNAME'], $post['internalip'])) != $post['internalip'] && rebindDisabled()) $dnserr = true;
if (host_lookup_ip(generate_internal_host(_var($nginx,'NGINX_CERTNAME'), $post['internalip'])) != $post['internalip'] && rebindDisabled()) $dnserr = true;
}
if ($isRegistered) {
// if signed in, send data needed to maintain My Servers Dashboard
@@ -300,8 +301,8 @@ if ($isRegistered) {
$post['internalport'] = $internalport;
$post['internalprotocol'] = $internalprotocol;
$post['remoteaccess'] = $remoteaccess;
$post['servercomment'] = $var['COMMENT'];
$post['servername'] = $var['NAME'];
$post['servercomment'] = _var($var,'COMMENT');
$post['servername'] = _var($var,'NAME');
if ($isWildcardCert) {
// keyserver needs the internalip to generate the local access url
$post['internalip'] = $internalip;
@@ -318,11 +319,11 @@ if ($isRegistered) {
}
// if remoteaccess is enabled in 6.10.0-rc3+ and WANIP has changed since nginx started, reload nginx
if (isset($post['_wanip']) && ($post['_wanip'] != $nginx['NGINX_WANIP']) && version_compare($var['version'],"6.10.0-rc2",">")) $reloadNginx = true;
if ($post['_wanip'] != _var($nginx,'NGINX_WANIP') && version_compare(_var($var,'version'),"6.10.0-rc2",">")) $reloadNginx = true;
// if remoteaccess is currently disabled (perhaps because a wanip was not available when nginx was started)
// BUT the system is configured to have it enabled AND a wanip is now available
// then reload nginx
if ($remoteaccess == 'no' && $nginx['NGINX_WANACCESS'] == 'yes' && !empty(trim(@file_get_contents("https://wanip4.unraid.net/")))) $reloadNginx = true;
if ($remoteaccess == 'no' && _var($nginx,'NGINX_WANACCESS') == 'yes' && !empty(trim(@file_get_contents("https://wanip4.unraid.net/")))) $reloadNginx = true;
if ($reloadNginx) {
exec("/etc/rc.d/rc.nginx reload &>/dev/null");
}
@@ -356,7 +357,7 @@ curl_close($ch);
if ( ($result === false) || ($httpcode != "200") ) {
// delete cache file to retry submission on next run
@unlink($datafile);
response_complete($httpcode ?? "500", array('error' => $error));
response_complete($httpcode ?? "500", ['error' => $error]);
}
response_complete($httpcode, $result, _('success'));
+7 -6
View File
@@ -1,6 +1,6 @@
<?PHP
/* Copyright 2005-2021, Lime Technology
* Copyright 2012-2021, Bergware International.
/* Copyright 2005-2023, Lime Technology
* Copyright 2012-2023, Bergware International.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2,
@@ -16,19 +16,20 @@ $_SERVER['REQUEST_URI'] = '';
require_once "$docroot/webGui/include/Translations.php";
require_once "$docroot/webGui/include/Helpers.php";
$index = unscript($_GET['index']??'');
$tests = explode(',',unscript($_GET['test']??''));
$index = unscript(_var($_GET,'index'));
$tests = explode(',',unscript(_var($_GET,'test')));
if ($index < count($tests)) {
$test = $tests[$index];
[$name,$size] = my_explode(':',$test);
if (!$size) {
$default = ($test==($_GET['hash']??''));
$default = ($test==_var($_GET,'hash']));
if ($index>0) $test .= '|tail -1';
if ($default) echo "<b>";
echo preg_replace(['/^(# Tests.*\n)/','/\n$/'],["$1\n",""],shell_exec("/usr/sbin/cryptsetup benchmark -h $test"));
echo $default ? " (default)</b>\n" : "\n";
} else {
$default = ($test==($_GET['luks']??''));
$default = ($test==_var($_GET,'luks'));
if ($index>5) $size .= '|tail -1';
if ($default) echo "<b>";
echo preg_replace(['/^# Tests.*\n/','/\n$/'],["\n",""],shell_exec("/usr/sbin/cryptsetup benchmark -c $name -s $size"));
@@ -1,6 +1,6 @@
<?PHP
/* Copyright 2005-2021, Lime Technology
* Copyright 2012-2021, Bergware International.
/* Copyright 2005-2023, Lime Technology
* Copyright 2012-2023, Bergware International.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2,
@@ -12,15 +12,17 @@
?>
<?
$docroot = $docroot ?? $_SERVER['DOCUMENT_ROOT'] ?: '/usr/local/emhttp';
require_once "$docroot/webGui/include/Secure.php";
require_once "$docroot/webGui/include/Wrappers.php";
$vfio = '/boot/config/vfio-pci.cfg';
$old = is_file($vfio) ? rtrim(file_get_contents($vfio)) : '';
$new = $_GET["cfg"]??'';
$new = unscript(_var($_GET,'cfg'));
if ($old !== $new) {
exec("cp -f $vfio $vfio.bak");
exec("echo \"$new\" >$vfio", $output, $myreturn );
if ($myreturn !== "0") {echo "1";}
exec("echo \"$new\" >$vfio", $output, $myreturn);
if ($myreturn != 0) {echo "1";}
}
?>
+59 -55
View File
@@ -12,17 +12,20 @@
?>
<?
$docroot = $docroot ?? $_SERVER['DOCUMENT_ROOT'] ?: '/usr/local/emhttp';
require_once "$docroot/webGui/include/Helpers.php";
// add translations
$_SERVER['REQUEST_URI'] = 'settings';
// special case when script is called on form-submit and processed by update.php
if (!isset($_SESSION['locale'])) $_SESSION['locale'] = $_POST['#locale']??'';
if (!isset($_SESSION['locale'])) $_SESSION['locale'] = _var($_POST,'#locale');
require_once "$docroot/webGui/include/Translations.php";
require_once "$docroot/webGui/include/Helpers.php";
$dockerd = is_file('/var/run/dockerd.pid') && is_dir('/proc/'.file_get_contents('/var/run/dockerd.pid'));
$etc = '/etc/wireguard';
$validIP4 = "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}";
$validIP6 = "(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(:|([0-9a-fA-F]{1,4}:)+):(([0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4})?)";
$validIP4 = "(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})";
$validIP6 = "(?:([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(:|([0-9a-fA-F]{1,4}:)+):(([0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4})?)";
$normalize = ['address'=>'Address', 'dns'=>'DNS', 'privatekey'=>'PrivateKey', 'publickey'=>'PublicKey', 'allowedips'=>'AllowedIPs', 'endpoint'=>'Endpoint','listenport'=>'ListenPort','mtu'=>'MTU','persistentkeepalive'=>'PersistentKeepalive'];
$dockernet = "172.31";
@@ -36,8 +39,8 @@ function mask2cidr($mask) {
}
function thisNet($ethX='eth0') {
extract(parse_ini_file('state/network.ini',true));
$net = long2ip(ip2long($$ethX['IPADDR:0']) & ip2long($$ethX['NETMASK:0'])).'/'.mask2cidr($$ethX['NETMASK:0']);
$dev = $$ethX['BRIDGING']=='yes' ? $$ethX['BRNAME'] : ($$ethX['BONDING']=='yes' ? $$ethX['BONDNAME'] : $ethX);
$net = long2ip(ip2long(_var($$ethX,'IPADDR:0')) & ip2long(_var($$ethX,'NETMASK:0'))).'/'.mask2cidr(_var($$ethX,'NETMASK:0'));
$dev = _var($$ethX,'BRIDGING')=='yes' ? _var($$ethX,'BRNAME') : (_var($$ethX,'BONDING')=='yes' ? _var($$ethX,'BONDNAME') : $ethX);
return [$dev,$net,$$ethX['GATEWAY:0']];
}
function ipv4($ip) {
@@ -146,7 +149,7 @@ function addPeer(&$x) {
$peers[$x] = ['[Interface]']; // [Interface]
if (isset($var['client'])) $peers[$x][] = $var['client']; // #name
if (isset($var['privateKey'])) $peers[$x][] = $var['privateKey']; // PrivateKey
$peers[$x][] = $var['address']??''; // Address
$peers[$x][] = _var($var,'address'); // Address
if (isset($var['listenport'])) $peers[$x][] = $var['listenport']; // ListenPort
if (isset($var['dns'])) $peers[$x][] = $var['dns']; // DNS server
if (isset($var['mtu'])) $peers[$x][] = $var['mtu']; // MTU
@@ -155,10 +158,10 @@ function addPeer(&$x) {
if (isset($var['server'])) $peers[$x][] = $var['server']; // #name
if (isset($var['handshake'])) $peers[$x][] = $var['handshake']; // PersistentKeepalive
if (isset($var['presharedKey'])) $peers[$x][] = $var['presharedKey']; // PresharedKey
$peers[$x][] = $var['publicKey']??''; // PublicKey
$peers[$x][] = _var($var,'publicKey'); // PublicKey
if (isset($var['tunnel'])) $peers[$x][] = $var['tunnel']; // Tunnel address
$peers[$x][] = $var['endpoint'] ?: $var['internet'] ?: ''; // Endpoint
$peers[$x][] = $var['allowedIPs']??''; // AllowedIPs
$peers[$x][] = _var($var,'endpoint') ?: _var($var,'internet'); // Endpoint
$peers[$x][] = _var($var,'allowedIPs'); // AllowedIPs
$x++;
}
function autostart($vtun,$cmd) {
@@ -223,7 +226,7 @@ function createIPs($list) {
return implode(', ',array_map('host',array_filter(array_map('trim',explode(',',$list)))));
}
function parseInput($vtun,&$input,&$x) {
global $conf,$user,$var,$default,$default6,$vpn,$tunip;
global $conf,$user,$var,$default4,$default6,$vpn,$tunip;
$section = 0; $addPeer = false;
foreach ($input as $key => $value) {
if ($key[0]=='#') continue;
@@ -280,13 +283,13 @@ function parseInput($vtun,&$input,&$x) {
$protocol = $value;
$user[] = "$id:0=\"$value\"";
switch ($protocol) {
case '46': $var['default'] = "AllowedIPs=$default, $default6"; break;
case '46': $var['default'] = "AllowedIPs=$default4, $default6"; break;
case '6' : $var['default'] = "AllowedIPs=$default6"; break;
default : $var['default'] = "AllowedIPs=$default"; break;
default : $var['default'] = "AllowedIPs=$default4"; break;
}
break;
case 'TYPE':
$list = $value<4 ? ($value%2==1 ? $var['subnets1'] : $var['subnets2']) : ($value<6 ? ($value%2==1 ? $var['shared1'] : $var['shared2']) : $var['default']);
$list = $value<4 ? ($value%2==1 ? _var($var,'subnets1') : _var($var,'subnets2')) : ($value<6 ? ($value%2==1 ? _var($var,'shared1') : _var($var,'shared2')) : _var($var,'default'));
$var['allowedIPs'] = createIPs($list);
$var['tunnel'] = ($value==2||$value==3) ? $tunnel : false;
$user[] = "$id:$x=\"$value\"";
@@ -321,8 +324,8 @@ function parseInput($vtun,&$input,&$x) {
$var['endpoint'] = $value ? "Endpoint=".ipset($value) : false;
} else {
if ($value) $conf[] = "$id=$value";
$var['listenport'] = $value ? "ListenPort=".explode(ipsplit($value),$value)[1] : false;
if ($var['endpoint'] && strpos($var['endpoint'],ipsplit($var['endpoint']))===false) $var['endpoint'] .= ":".explode(ipsplit($var['internet']),$var['internet'])[1];
$var['listenport'] = $value ? "ListenPort=".(explode(ipsplit($value),$value)[1]??'') : false;
if ($var['endpoint'] && strpos(_var($var,'endpoint'),ipsplit(_var($var,'endpoint')))===false) $var['endpoint'] .= ":".(explode(ipsplit(_var($var,'internet')),_var($var,'internet'))[1]??'');
}
break;
case 'PersistentKeepalive':
@@ -342,9 +345,10 @@ function parseInput($vtun,&$input,&$x) {
}
}
}
$default = '0.0.0.0/0';
$default4 = '0.0.0.0/0';
$default6 = '::/0';
switch ($_POST['#cmd']) {
switch (_var($_POST,'#cmd')) {
case 'keypair':
$private = exec("wg genkey");
$public = exec("wg pubkey <<<'$private'");
@@ -360,19 +364,19 @@ case 'update':
if (!exec("ip6tables -S|grep -om1 'WIREGUARD$'")) {
exec("ip6tables -N WIREGUARD;ip6tables -A FORWARD -j WIREGUARD");
}
$cfg = $_POST['#cfg'];
$wg = $_POST['#wg'];
$name = $_POST['#name'];
$vtun = $_POST['#vtun'];
$gone = explode(',',$_POST['#deleted']);
$cfg = _var($_POST,'#cfg');
$wg = _var($_POST,'#wg');
$name = _var($_POST,'#name');
$vtun = _var($_POST,'#vtun');
$gone = explode(',',_var($_POST,'#deleted'));
$conf = ['[Interface]'];
$user = $peers = $var = [];
$tunip = "";
$var['subnets1'] = "AllowedIPs=".createList($_POST['#subnets1']);
$var['subnets2'] = "AllowedIPs=".createList($_POST['#subnets2']);
$var['shared1'] = "AllowedIPs=".createList($_POST['#shared1']);
$var['shared2'] = "AllowedIPs=".createList($_POST['#shared2']);
$var['internet'] = "Endpoint=".createList($_POST['#internet']);
$var['subnets1'] = "AllowedIPs=".createList(_var($_POST,'#subnets1'));
$var['subnets2'] = "AllowedIPs=".createList(_var($_POST,'#subnets2'));
$var['shared1'] = "AllowedIPs=".createList(_var($_POST,'#shared1'));
$var['shared2'] = "AllowedIPs=".createList(_var($_POST,'#shared2'));
$var['internet'] = "Endpoint=".createList(_var($_POST,'#internet'));
$x = 1; $vpn = 0;
parseInput($vtun,$_POST,$x);
addPeer($x);
@@ -382,7 +386,7 @@ case 'update':
file_put_contents($file,implode("\n",$conf)."\n");
file_put_contents($cfg,implode("\n",$user)."\n");
createPeerFiles($vtun);
if ($upstate) wgState($vtun,'up',$_POST['#type']);
if ($upstate) wgState($vtun,'up',_var($_POST,'#type'));
// if $tunip (with dots to slashes) not found in nginx config, then reload nginx to add it
$nginx = parse_ini_file('/var/local/emhttp/nginx.ini');
if (stripos($nginx['NGINX_CERTNAME'],'.myunraid.net')!==false) {
@@ -394,8 +398,8 @@ case 'update':
$save = false;
break;
case 'toggle':
$vtun = $_POST['#vtun'];
switch ($_POST['#wg']) {
$vtun = _var($_POST,'#vtun');
switch (_var($_POST,'#wg')) {
case 'stop':
wgState($vtun,'down');
echo status($vtun) ? 1 : 0;
@@ -406,7 +410,7 @@ case 'toggle':
exec("ip -4 rule add from $network table $index");
exec("ip -4 route add unreachable default table $index");
}
wgState($vtun,'up',$_POST['#type']??'');
wgState($vtun,'up',_var($_POST,'#type'));
echo status($vtun) ? 0 : 1;
break;
}
@@ -416,9 +420,9 @@ case 'ping':
echo exec("ping -qc1 -W4 $addr|grep -Pom1 '1 received'");
break;
case 'public':
$ip = $_POST['#ip'];
$v4 = $_POST['#prot']!='6';
$v6 = $_POST['#prot']!='';
$ip = _var($_POST,'#ip');
$v4 = _var($_POST,'#prot')!='6';
$v6 = _var($_POST,'#prot')!='';
$context = stream_context_create(['https'=>['timeout'=>12]]);
$int_ipv4 = $v4 ? (preg_match("/^$validIP4$/",$ip) ? $ip : (@dns_get_record($ip,DNS_A)[0]['ip'] ?: '')) : '';
$ext_ipv4 = $v4 ? (@file_get_contents('https://wanip4.unraid.net',false,$context) ?: '') : '';
@@ -428,7 +432,7 @@ case 'public':
break;
case 'addtunnel':
$vtun = vtun();
$name = $_POST['#name'];
$name = _var($_POST,'#name');
touch("$etc/$vtun.conf");
wgState($vtun,'down');
delete_file("$etc/$vtun.cfg");
@@ -436,8 +440,8 @@ case 'addtunnel':
autostart($vtun,'off');
break;
case 'deltunnel':
$vtun = $_POST['#vtun'];
$name = $_POST['#name'];
$vtun = _var($_POST,'#vtun');
$name = _var($_POST,'#name');
$error = delDocker($vtun);
if (!$error) {
wgState($vtun,'down');
@@ -454,9 +458,9 @@ case 'deltunnel':
echo $error ? 1 : 0;
break;
case 'import':
$name = $_POST['#name'];
$name = _var($_POST,'#name');
$user = $peers = $var = $import = $sort = [];
$entries = array_filter(array_map('trim',preg_split('/\[(Interface|Peer)\]/',$_POST['#data'])));
$entries = array_filter(array_map('trim',preg_split('/\[(Interface|Peer)\]/',_var($_POST,'#data'))));
foreach($entries as $key => $entry) {
$i = $key-1;
foreach (explode("\n",$entry) as $row) {
@@ -469,12 +473,12 @@ case 'import':
}
}
}
if ($import['PrivateKey:0'] && !$import['PublicKey:0']) $import['PublicKey:0'] = exec("wg pubkey <<<'{$import['PrivateKey:0']}'");
if (_var($import,'PrivateKey:0') && !_var($import,'PublicKey:0')) $import['PublicKey:0'] = exec("wg pubkey <<<'"._var($import,'PrivateKey:0')."'");
// delete ListenPort and let WG generate a random local port
unset($import['ListenPort:0']);
$import['UPNP:0'] = 'no';
$import['NAT:0'] = 'no';
[$subnet,$mask] = my_explode('/',$import['Address:0']);
[$subnet,$mask] = my_explode('/',_var($import,'Address:0'));
if (ipv4($subnet)) {
$mask = ($mask > 0 && $mask < 32) ? $mask : 24;
$import['Network:0'] = long2ip(ip2long($subnet) & (0x100000000-2**(32-$mask))).'/'.$mask;
@@ -488,18 +492,18 @@ case 'import':
}
$import['Endpoint:0'] = '';
for ($n = 1; $n <= $i; $n++) {
$vpn = array_map('trim',explode(',',$import["AllowedIPs:$n"]));
$vpn = (in_array($default,$vpn) || in_array($default6,$vpn)) ? 8 : 0;
$vpn = array_map('trim',explode(',',_var($import,"AllowedIPs:$n")));
$vpn = (in_array($default4,$vpn) || in_array($default6,$vpn)) ? 8 : 0;
if ($vpn==8) $import["Address:$n"] = '';
$import["TYPE:$n"] = $vpn;
ipfilter($import["AllowedIPs:$n"]);
if ($import["TYPE:$n"]==0) $var['subnets1'] = "AllowedIPs=".$import["AllowedIPs:$n"];
ipfilter(_var($import,"AllowedIPs:$n"));
if (_var($import,"TYPE:$n")==0) $var['subnets1'] = "AllowedIPs="._var($import,"AllowedIPs:$n");
}
foreach ($import as $key => $val) $sort[] = explode(':',$key)[1];
array_multisort($sort,$import);
$x = 1;
$conf = ['[Interface]'];
$var['default'] = $import['PROT:0']=='' ? "AllowedIPs=$default" : "AllowedIPs=$default6";
$var['default'] = _var($import,'PROT:0')=='' ? "AllowedIPs=$default4" : "AllowedIPs=$default6";
$var['internet'] = "Endpoint=unknown";
$vtun = vtun();
parseInput($vtun,$import,$x);
@@ -512,13 +516,13 @@ case 'import':
echo $vtun;
break;
case 'autostart':
autostart($_POST['#vtun'],$_POST['#start']);
autostart(_var($_POST,'#vtun'),_var($_POST,'#start'));
break;
case 'upnp':
$upnp = '/var/tmp/upnp';
if (is_executable('/usr/bin/upnpc')) {
$gw = $_POST['#gw'].':';
$link = $_POST['#link'];
$gw = _var($_POST,'#gw').':';
$link = _var($_POST,'#link');
$xml = @file_get_contents($upnp) ?: '';
if ($xml) {
exec("timeout $t1 stdbuf -o0 upnpc -u $xml -m $link -l 2>&1|grep -qm1 'refused'",$output,$code);
@@ -534,11 +538,11 @@ case 'upnp':
break;
case 'upnpc':
if (!is_executable('/usr/bin/upnpc')) break;
$xml = $_POST['#xml'];
$vtun = $_POST['#vtun'];
$link = $_POST['#link'];
$ip = $_POST['#ip'];
if ($_POST['#wg']=='active') {
$xml = _var($_POST,'#xml');
$vtun = _var($_POST,'#vtun');
$link = _var($_POST,'#link');
$ip = _var($_POST,'#ip');
if (_var($_POST,'#wg')=='active') {
exec("timeout $t1 stdbuf -o0 upnpc -u $xml -m $link -l 2>/dev/null|grep -Po \"^(ExternalIPAddress = \K.+|.+\KUDP.+>$ip:[0-9]+ 'WireGuard-$vtun')\"",$upnp);
[$addr,$upnp] = array_pad($upnp,2,'');
[$type,$rule] = my_explode(' ',$upnp);