Processed with phpcs for PSR-2 coding standard

This commit is contained in:
billz 2019-04-10 08:37:35 +00:00
parent 89852cc633
commit c0570b616e
17 changed files with 1461 additions and 1416 deletions

5
includes/about.php Normal file → Executable file
View file

@ -1,8 +1,9 @@
<?php
include_once( 'includes/status_messages.php' );
include_once('includes/status_messages.php');
function DisplayAbout() {
function DisplayAbout()
{
/**
*
* Displays info about the RaspAP project

View file

@ -1,40 +1,41 @@
<?php
include_once( 'includes/status_messages.php' );
include_once('includes/status_messages.php');
function DisplayAuthConfig($username, $password){
$status = new StatusMessages();
if (isset($_POST['UpdateAdminPassword'])) {
if (CSRFValidate()) {
if (password_verify($_POST['oldpass'], $password)) {
$new_username=trim($_POST['username']);
if ($_POST['newpass'] !== $_POST['newpassagain']) {
$status->addMessage('New passwords do not match', 'danger');
} else if ($new_username == '') {
$status->addMessage('Username must not be empty', 'danger');
function DisplayAuthConfig($username, $password)
{
$status = new StatusMessages();
if (isset($_POST['UpdateAdminPassword'])) {
if (CSRFValidate()) {
if (password_verify($_POST['oldpass'], $password)) {
$new_username=trim($_POST['username']);
if ($_POST['newpass'] !== $_POST['newpassagain']) {
$status->addMessage('New passwords do not match', 'danger');
} elseif ($new_username == '') {
$status->addMessage('Username must not be empty', 'danger');
} else {
if (!file_exists(RASPI_ADMIN_DETAILS)) {
$tmpauth = fopen(RASPI_ADMIN_DETAILS, 'w');
fclose($tmpauth);
}
if ($auth_file = fopen(RASPI_ADMIN_DETAILS, 'w')) {
fwrite($auth_file, $new_username.PHP_EOL);
fwrite($auth_file, password_hash($_POST['newpass'], PASSWORD_BCRYPT).PHP_EOL);
fclose($auth_file);
$username = $new_username;
$status->addMessage('Admin password updated');
} else {
$status->addMessage('Failed to update admin password', 'danger');
}
}
} else {
$status->addMessage('Old password does not match', 'danger');
}
} else {
if (!file_exists(RASPI_ADMIN_DETAILS)) {
$tmpauth = fopen(RASPI_ADMIN_DETAILS, 'w');
fclose($tmpauth);
}
if ($auth_file = fopen(RASPI_ADMIN_DETAILS, 'w')) {
fwrite($auth_file, $new_username.PHP_EOL);
fwrite($auth_file, password_hash($_POST['newpass'], PASSWORD_BCRYPT).PHP_EOL);
fclose($auth_file);
$username = $new_username;
$status->addMessage('Admin password updated');
} else {
$status->addMessage('Failed to update admin password', 'danger');
}
error_log('CSRF violation');
}
} else {
$status->addMessage('Old password does not match', 'danger');
}
} else {
error_log('CSRF violation');
}
}
?>
<div class="row">
<div class="col-lg-12">
@ -74,6 +75,6 @@ function DisplayAuthConfig($username, $password){
</div><!-- /.panel-default -->
</div><!-- /.col-lg-12 -->
</div><!-- /.row -->
<?php
<?php
}

View file

@ -5,14 +5,13 @@ $pass = $_SERVER['PHP_AUTH_PW'];
$validated = ($user == $config['admin_user']) && password_verify($pass, $config['admin_pass']);
if (!$validated) {
header('WWW-Authenticate: Basic realm="RaspAP"');
if (function_exists('http_response_code')) {
// http_response_code will respond with proper HTTP version back.
http_response_code(401);
} else {
header('HTTP/1.0 401 Unauthorized');
}
header('WWW-Authenticate: Basic realm="RaspAP"');
if (function_exists('http_response_code')) {
// http_response_code will respond with proper HTTP version back.
http_response_code(401);
} else {
header('HTTP/1.0 401 Unauthorized');
}
exit('Not authorized'.PHP_EOL);
exit('Not authorized'.PHP_EOL);
}

View file

@ -2,7 +2,7 @@
define('RASPI_VERSION', '1.4.1');
define('RASPI_CONFIG', '/etc/raspap');
define('RASPI_CONFIG_NETWORKING',RASPI_CONFIG.'/networking');
define('RASPI_CONFIG_NETWORKING', RASPI_CONFIG.'/networking');
define('RASPI_ADMIN_DETAILS', RASPI_CONFIG.'/raspap.auth');
define('RASPI_WIFI_CLIENT_INTERFACE', 'wlan0');
@ -20,17 +20,16 @@ define('RASPI_OPENVPN_SERVER_CONFIG', '/etc/openvpn/server.conf');
define('RASPI_TORPROXY_CONFIG', '/etc/tor/torrc');
// Optional services, set to true to enable.
define('RASPI_WIFICLIENT_ENABLED', true );
define('RASPI_HOTSPOT_ENABLED', true );
define('RASPI_NETWORK_ENABLED', true );
define('RASPI_DHCP_ENABLED', true );
define('RASPI_OPENVPN_ENABLED', false );
define('RASPI_TORPROXY_ENABLED', false );
define('RASPI_CONFAUTH_ENABLED', true );
define('RASPI_CHANGETHEME_ENABLED', true );
define('RASPI_VNSTAT_ENABLED', true );
define('RASPI_WIFICLIENT_ENABLED', true);
define('RASPI_HOTSPOT_ENABLED', true);
define('RASPI_NETWORK_ENABLED', true);
define('RASPI_DHCP_ENABLED', true);
define('RASPI_OPENVPN_ENABLED', false);
define('RASPI_TORPROXY_ENABLED', false);
define('RASPI_CONFAUTH_ENABLED', true);
define('RASPI_CHANGETHEME_ENABLED', true);
define('RASPI_VNSTAT_ENABLED', true);
// Locale settings
define('LOCALE_ROOT', 'locale');
define('LOCALE_DOMAIN', 'messages');
define('LOCALE_DOMAIN', 'messages');

View file

@ -4,167 +4,167 @@
*
*
*/
function DisplayWPAConfig(){
$status = new StatusMessages();
$networks = array();
function DisplayWPAConfig()
{
$status = new StatusMessages();
$networks = array();
// Find currently configured networks
exec(' sudo cat ' . RASPI_WPA_SUPPLICANT_CONFIG, $known_return);
// Find currently configured networks
exec(' sudo cat ' . RASPI_WPA_SUPPLICANT_CONFIG, $known_return);
$network = null;
$ssid = null;
$network = null;
$ssid = null;
foreach($known_return as $line) {
if (preg_match('/network\s*=/', $line)) {
$network = array('visible' => false, 'configured' => true, 'connected' => false);
} elseif ($network !== null) {
if (preg_match('/^\s*}\s*$/', $line)) {
$networks[$ssid] = $network;
$network = null;
$ssid = null;
} elseif ($lineArr = preg_split('/\s*=\s*/', trim($line))) {
switch(strtolower($lineArr[0])) {
case 'ssid':
$ssid = trim($lineArr[1], '"');
break;
case 'psk':
if (array_key_exists('passphrase', $network)) {
break;
}
case '#psk':
$network['protocol'] = 'WPA';
case 'wep_key0': // Untested
$network['passphrase'] = trim($lineArr[1], '"');
break;
case 'key_mgmt':
if (! array_key_exists('passphrase', $network) && $lineArr[1] === 'NONE') {
$network['protocol'] = 'Open';
}
break;
case 'priority':
$network['priority'] = trim($lineArr[1], '"');
break;
}
}
}
}
if ( isset($_POST['connect']) ) {
$result = 0;
exec ( 'sudo wpa_cli -i ' . RASPI_WPA_CTRL_INTERFACE . ' select_network '.strval($_POST['connect'] ));
}
else if ( isset($_POST['client_settings']) && CSRFValidate() ) {
$tmp_networks = $networks;
if ($wpa_file = fopen('/tmp/wifidata', 'w')) {
fwrite($wpa_file, 'ctrl_interface=DIR=' . RASPI_WPA_CTRL_INTERFACE . ' GROUP=netdev' . PHP_EOL);
fwrite($wpa_file, 'update_config=1' . PHP_EOL);
foreach(array_keys($_POST) as $post) {
if (preg_match('/delete(\d+)/', $post, $post_match)) {
unset($tmp_networks[$_POST['ssid' . $post_match[1]]]);
} elseif (preg_match('/update(\d+)/', $post, $post_match)) {
// NB, at the moment, the value of protocol from the form may
// contain HTML line breaks
$tmp_networks[$_POST['ssid' . $post_match[1]]] = array(
'protocol' => ( $_POST['protocol' . $post_match[1]] === 'Open' ? 'Open' : 'WPA' ),
'passphrase' => $_POST['passphrase' . $post_match[1]],
'configured' => true
);
if (array_key_exists('priority' . $post_match[1], $_POST)) {
$tmp_networks[$_POST['ssid' . $post_match[1]]]['priority'] = $_POST['priority' . $post_match[1]];
}
}
}
$ok = true;
foreach($tmp_networks as $ssid => $network) {
if ($network['protocol'] === 'Open') {
fwrite($wpa_file, "network={".PHP_EOL);
fwrite($wpa_file, "\tssid=\"".$ssid."\"".PHP_EOL);
fwrite($wpa_file, "\tkey_mgmt=NONE".PHP_EOL);
if (array_key_exists('priority', $network)) {
fwrite($wpa_file, "\tpriority=".$network['priority'].PHP_EOL);
}
fwrite($wpa_file, "}".PHP_EOL);
} else {
if (strlen($network['passphrase']) >=8 && strlen($network['passphrase']) <= 63) {
unset($wpa_passphrase);
unset($line);
exec( 'wpa_passphrase '.escapeshellarg($ssid). ' ' . escapeshellarg($network['passphrase']),$wpa_passphrase );
foreach($wpa_passphrase as $line) {
if (preg_match('/^\s*}\s*$/', $line)) {
if (array_key_exists('priority', $network)) {
fwrite($wpa_file, "\tpriority=".$network['priority'].PHP_EOL);
foreach ($known_return as $line) {
if (preg_match('/network\s*=/', $line)) {
$network = array('visible' => false, 'configured' => true, 'connected' => false);
} elseif ($network !== null) {
if (preg_match('/^\s*}\s*$/', $line)) {
$networks[$ssid] = $network;
$network = null;
$ssid = null;
} elseif ($lineArr = preg_split('/\s*=\s*/', trim($line))) {
switch (strtolower($lineArr[0])) {
case 'ssid':
$ssid = trim($lineArr[1], '"');
break;
case 'psk':
if (array_key_exists('passphrase', $network)) {
break;
}
case '#psk':
$network['protocol'] = 'WPA';
case 'wep_key0': // Untested
$network['passphrase'] = trim($lineArr[1], '"');
break;
case 'key_mgmt':
if (! array_key_exists('passphrase', $network) && $lineArr[1] === 'NONE') {
$network['protocol'] = 'Open';
}
break;
case 'priority':
$network['priority'] = trim($lineArr[1], '"');
break;
}
fwrite($wpa_file, $line.PHP_EOL);
} else {
fwrite($wpa_file, $line.PHP_EOL);
}
}
} else {
$status->addMessage('WPA passphrase must be between 8 and 63 characters', 'danger');
$ok = false;
}
}
}
}
if ($ok) {
system( 'sudo cp /tmp/wifidata ' . RASPI_WPA_SUPPLICANT_CONFIG, $returnval );
if( $returnval == 0 ) {
exec('sudo wpa_cli -i ' . RASPI_WIFI_CLIENT_INTERFACE . ' reconfigure', $reconfigure_out, $reconfigure_return );
if ($reconfigure_return == 0) {
$status->addMessage('Wifi settings updated successfully', 'success');
$networks = $tmp_networks;
} else {
$status->addMessage('Wifi settings updated but cannot restart (cannot execute "wpa_cli reconfigure")', 'danger');
}
if (isset($_POST['connect'])) {
$result = 0;
exec('sudo wpa_cli -i ' . RASPI_WPA_CTRL_INTERFACE . ' select_network '.strval($_POST['connect']));
} elseif (isset($_POST['client_settings']) && CSRFValidate()) {
$tmp_networks = $networks;
if ($wpa_file = fopen('/tmp/wifidata', 'w')) {
fwrite($wpa_file, 'ctrl_interface=DIR=' . RASPI_WPA_CTRL_INTERFACE . ' GROUP=netdev' . PHP_EOL);
fwrite($wpa_file, 'update_config=1' . PHP_EOL);
foreach (array_keys($_POST) as $post) {
if (preg_match('/delete(\d+)/', $post, $post_match)) {
unset($tmp_networks[$_POST['ssid' . $post_match[1]]]);
} elseif (preg_match('/update(\d+)/', $post, $post_match)) {
// NB, at the moment, the value of protocol from the form may
// contain HTML line breaks
$tmp_networks[$_POST['ssid' . $post_match[1]]] = array(
'protocol' => ( $_POST['protocol' . $post_match[1]] === 'Open' ? 'Open' : 'WPA' ),
'passphrase' => $_POST['passphrase' . $post_match[1]],
'configured' => true
);
if (array_key_exists('priority' . $post_match[1], $_POST)) {
$tmp_networks[$_POST['ssid' . $post_match[1]]]['priority'] = $_POST['priority' . $post_match[1]];
}
}
}
$ok = true;
foreach ($tmp_networks as $ssid => $network) {
if ($network['protocol'] === 'Open') {
fwrite($wpa_file, "network={".PHP_EOL);
fwrite($wpa_file, "\tssid=\"".$ssid."\"".PHP_EOL);
fwrite($wpa_file, "\tkey_mgmt=NONE".PHP_EOL);
if (array_key_exists('priority', $network)) {
fwrite($wpa_file, "\tpriority=".$network['priority'].PHP_EOL);
}
fwrite($wpa_file, "}".PHP_EOL);
} else {
if (strlen($network['passphrase']) >=8 && strlen($network['passphrase']) <= 63) {
unset($wpa_passphrase);
unset($line);
exec('wpa_passphrase '.escapeshellarg($ssid). ' ' . escapeshellarg($network['passphrase']), $wpa_passphrase);
foreach ($wpa_passphrase as $line) {
if (preg_match('/^\s*}\s*$/', $line)) {
if (array_key_exists('priority', $network)) {
fwrite($wpa_file, "\tpriority=".$network['priority'].PHP_EOL);
}
fwrite($wpa_file, $line.PHP_EOL);
} else {
fwrite($wpa_file, $line.PHP_EOL);
}
}
} else {
$status->addMessage('WPA passphrase must be between 8 and 63 characters', 'danger');
$ok = false;
}
}
}
if ($ok) {
system('sudo cp /tmp/wifidata ' . RASPI_WPA_SUPPLICANT_CONFIG, $returnval);
if ($returnval == 0) {
exec('sudo wpa_cli -i ' . RASPI_WIFI_CLIENT_INTERFACE . ' reconfigure', $reconfigure_out, $reconfigure_return);
if ($reconfigure_return == 0) {
$status->addMessage('Wifi settings updated successfully', 'success');
$networks = $tmp_networks;
} else {
$status->addMessage('Wifi settings updated but cannot restart (cannot execute "wpa_cli reconfigure")', 'danger');
}
} else {
$status->addMessage('Wifi settings failed to be updated', 'danger');
}
}
} else {
$status->addMessage('Wifi settings failed to be updated', 'danger');
$status->addMessage('Failed to update wifi settings', 'danger');
}
}
} else {
$status->addMessage('Failed to update wifi settings', 'danger');
}
}
exec( 'sudo wpa_cli -i ' . RASPI_WIFI_CLIENT_INTERFACE . ' scan' );
sleep(3);
exec( 'sudo wpa_cli -i ' . RASPI_WIFI_CLIENT_INTERFACE . ' scan_results',$scan_return );
array_shift($scan_return);
// display output
foreach( $scan_return as $network ) {
$arrNetwork = preg_split("/[\t]+/",$network); // split result into array
// Save RSSI
if (array_key_exists(4, $arrNetwork)) {
$networks[$arrNetwork[4]]['RSSI'] = $arrNetwork[2];
}
// If network is saved
if (array_key_exists(4, $arrNetwork) && array_key_exists($arrNetwork[4], $networks)) {
$networks[$arrNetwork[4]]['visible'] = true;
$networks[$arrNetwork[4]]['channel'] = ConvertToChannel($arrNetwork[1]);
// TODO What if the security has changed?
} else {
$networks[$arrNetwork[4]] = array(
'configured' => false,
'protocol' => ConvertToSecurity($arrNetwork[3]),
'channel' => ConvertToChannel($arrNetwork[1]),
'passphrase' => '',
'visible' => true,
'connected' => false
);
}
}
exec('sudo wpa_cli -i ' . RASPI_WIFI_CLIENT_INTERFACE . ' scan');
sleep(3);
exec('sudo wpa_cli -i ' . RASPI_WIFI_CLIENT_INTERFACE . ' scan_results', $scan_return);
exec( 'iwconfig ' . RASPI_WIFI_CLIENT_INTERFACE, $iwconfig_return );
foreach ($iwconfig_return as $line) {
if (preg_match( '/ESSID:\"([^"]+)\"/i',$line,$iwconfig_ssid )) {
$networks[$iwconfig_ssid[1]]['connected'] = true;
array_shift($scan_return);
// display output
foreach ($scan_return as $network) {
$arrNetwork = preg_split("/[\t]+/", $network); // split result into array
// Save RSSI
if (array_key_exists(4, $arrNetwork)) {
$networks[$arrNetwork[4]]['RSSI'] = $arrNetwork[2];
}
// If network is saved
if (array_key_exists(4, $arrNetwork) && array_key_exists($arrNetwork[4], $networks)) {
$networks[$arrNetwork[4]]['visible'] = true;
$networks[$arrNetwork[4]]['channel'] = ConvertToChannel($arrNetwork[1]);
// TODO What if the security has changed?
} else {
$networks[$arrNetwork[4]] = array(
'configured' => false,
'protocol' => ConvertToSecurity($arrNetwork[3]),
'channel' => ConvertToChannel($arrNetwork[1]),
'passphrase' => '',
'visible' => true,
'connected' => false
);
}
}
exec('iwconfig ' . RASPI_WIFI_CLIENT_INTERFACE, $iwconfig_return);
foreach ($iwconfig_return as $line) {
if (preg_match('/ESSID:\"([^"]+)\"/i', $line, $iwconfig_ssid)) {
$networks[$iwconfig_ssid[1]]['connected'] = true;
}
}
}
?>
<div class="row">
@ -176,11 +176,11 @@ function DisplayWPAConfig(){
<p><?php $status->showMessages(); ?></p>
<h4><?php echo _("Client settings"); ?></h4>
<div class="btn-group btn-block">
<a href=".?<?php echo htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES); ?>" style="padding:10px;float: right;display: block;position: relative;margin-top: -55px;" class="col-md-2 btn btn-info" id="update"><?php echo _("Rescan"); ?></a>
</div>
<a href=".?<?php echo htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES); ?>" style="padding:10px;float: right;display: block;position: relative;margin-top: -55px;" class="col-md-2 btn btn-info" id="update"><?php echo _("Rescan"); ?></a>
</div>
<form method="POST" action="?page=wpa_conf" name="wpa_conf_form">
<?php CSRFToken() ?>
<?php CSRFToken() ?>
<input type="hidden" name="client_settings" ?>
<script>
function showPassword(index) {
@ -193,8 +193,8 @@ function DisplayWPAConfig(){
}
</script>
<?php $index = 0; ?>
<?php foreach ($networks as $ssid => $network) { ?>
<?php $index = 0; ?>
<?php foreach ($networks as $ssid => $network) { ?>
<div class="col-md-6">
<div class="panel panel-default">
@ -206,23 +206,23 @@ function DisplayWPAConfig(){
<div class="row">
<div class="col-xs-4 col-md-4">Status</div>
<div class="col-xs-4 col-md-4">
<?php if ($network['configured']) { ?>
<?php if ($network['configured']) { ?>
<i class="fa fa-check-circle fa-fw"></i>
<?php } ?>
<?php if ($network['connected']) { ?>
<?php } ?>
<?php if ($network['connected']) { ?>
<i class="fa fa-exchange fa-fw"></i>
<?php } ?>
<?php } ?>
</div>
</div>
<div class="row">
<div class="col-xs-4 col-md-4">Channel</div>
<div class="col-xs-4 col-md-4">
<?php if ($network['visible']) { ?>
<?php echo htmlspecialchars($network['channel'], ENT_QUOTES) ?>
<?php } else { ?>
<?php if ($network['visible']) { ?>
<?php echo htmlspecialchars($network['channel'], ENT_QUOTES) ?>
<?php } else { ?>
<span class="label label-warning"> X </span>
<?php } ?>
<?php } ?>
</div>
</div>
@ -231,17 +231,21 @@ function DisplayWPAConfig(){
<div class="col-xs-6 col-md-6">
<?php echo htmlspecialchars($network['RSSI'], ENT_QUOTES);
echo "dB (";
if($network['RSSI'] >= -50) { echo 100; }
else if($network['RSSI'] <= -100) { echo 0;}
else {echo 2*($network['RSSI'] + 100); }
if ($network['RSSI'] >= -50) {
echo 100;
} elseif ($network['RSSI'] <= -100) {
echo 0;
} else {
echo 2*($network['RSSI'] + 100);
}
echo "%)";
?>
</div>
</div>
<?php if (array_key_exists('priority', $network)) { ?>
<?php if (array_key_exists('priority', $network)) { ?>
<input type="hidden" name="priority<?php echo $index ?>" value="<?php echo htmlspecialchars($network['priority'], ENT_QUOTES); ?>" />
<?php } ?>
<?php } ?>
<input type="hidden" name="protocol<?php echo $index ?>" value="<?php echo htmlspecialchars($network['protocol'], ENT_QUOTES); ?>" />
<div class="row">
@ -252,14 +256,14 @@ function DisplayWPAConfig(){
<div class="form-group">
<div class="input-group col-xs-12 col-md-12">
<span class="input-group-addon" id="passphrase">Passphrase</span>
<?php if ($network['protocol'] === 'Open') { ?>
<?php if ($network['protocol'] === 'Open') { ?>
<input type="hidden" name="passphrase<?php echo $index ?>" value="" />---
<?php } else { ?>
<?php } else { ?>
<input type="password" class="form-control" aria-describedby="passphrase" name="passphrase<?php echo $index ?>" value="<?php echo $network['passphrase'] ?>" onKeyUp="CheckPSK(this, 'update<?php echo $index?>')" >
<span class="input-group-btn">
<button class="btn btn-default" onclick="showPassword(<?php echo $index; ?>)" type="button">Show</button>
</span>
<?php } ?>
<?php } ?>
</div>
</div>
@ -282,7 +286,7 @@ function DisplayWPAConfig(){
</form>
</div><!-- ./ Panel body -->
<div class="panel-footer"><?php echo _("<strong>Note:</strong> WEP access points appear as 'Open'. RaspAP does not currently support connecting to WEP"); ?></div>
<div class="panel-footer"><?php echo _("<strong>Note:</strong> WEP access points appear as 'Open'. RaspAP does not currently support connecting to WEP"); ?></div>
</div><!-- /.panel-primary -->
</div><!-- /.col-lg-12 -->
</div><!-- /.row -->

View file

@ -3,179 +3,180 @@
/**
* Show dashboard page.
*/
function DisplayDashboard(){
function DisplayDashboard()
{
$status = new StatusMessages();
// Need this check interface name for proper shell execution.
if (!preg_match('/^([a-zA-Z0-9]+)$/', RASPI_WIFI_CLIENT_INTERFACE)) {
$status->addMessage(_('Interface name invalid.'), 'danger');
$status->showMessages();
return;
}
if (!function_exists('exec')) {
$status->addMessage(_('Required exec function is disabled. Check if exec is not added to php disable_functions.'), 'danger');
$status->showMessages();
return;
}
exec('ip a show '.RASPI_WIFI_CLIENT_INTERFACE, $stdoutIp);
$stdoutIpAllLinesGlued = implode(" ", $stdoutIp);
$stdoutIpWRepeatedSpaces = preg_replace('/\s\s+/', ' ', $stdoutIpAllLinesGlued);
preg_match('/link\/ether ([0-9a-f:]+)/i', $stdoutIpWRepeatedSpaces, $matchesMacAddr ) || $matchesMacAddr[1] = _('No MAC Address Found');
$macAddr = $matchesMacAddr[1];
$ipv4Addrs = '';
$ipv4Netmasks = '';
if (!preg_match_all('/inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/([0-3][0-9])/i', $stdoutIpWRepeatedSpaces, $matchesIpv4AddrAndSubnet)) {
$ipv4Addrs = _('No IPv4 Address Found');
} else {
$numMatchesIpv4AddrAndSubnet = count($matchesIpv4AddrAndSubnet);
for ($i = 1; $i < $numMatchesIpv4AddrAndSubnet; $i += 2) {
if ($i > 2) {
$ipv4Netmasks .= ' ';
$ipv4Addrs .= ' ';
}
$ipv4Addrs .= $matchesIpv4AddrAndSubnet[$i][0];
$ipv4Netmasks .= long2ip(-1 << (32 -(int)$matchesIpv4AddrAndSubnet[$i+1][0]));
$status = new StatusMessages();
// Need this check interface name for proper shell execution.
if (!preg_match('/^([a-zA-Z0-9]+)$/', RASPI_WIFI_CLIENT_INTERFACE)) {
$status->addMessage(_('Interface name invalid.'), 'danger');
$status->showMessages();
return;
}
}
$ipv6Addrs = '';
if (!preg_match_all('/inet6 ([a-f0-9:]+)/i', $stdoutIpWRepeatedSpaces, $matchesIpv6Addr)) {
$ipv6Addrs = _('No IPv6 Address Found');
} else {
$numMatchesIpv6Addr = count($matchesIpv6Addr);
for ($i = 1; $i < $numMatchesIpv6Addr; ++$i) {
if ($i > 1) {
$ipv6Addrs .= ' ';
}
$ipv6Addrs .= $matchesIpv6Addr[$i];
if (!function_exists('exec')) {
$status->addMessage(_('Required exec function is disabled. Check if exec is not added to php disable_functions.'), 'danger');
$status->showMessages();
return;
}
}
preg_match('/state (UP|DOWN)/i', $stdoutIpWRepeatedSpaces, $matchesState ) || $matchesState[1] = 'unknown';
$interfaceState = $matchesState[1];
exec('ip a show '.RASPI_WIFI_CLIENT_INTERFACE, $stdoutIp);
$stdoutIpAllLinesGlued = implode(" ", $stdoutIp);
$stdoutIpWRepeatedSpaces = preg_replace('/\s\s+/', ' ', $stdoutIpAllLinesGlued);
// Because of table layout used in the ip output we get the interface statistics directly from
// the system. One advantage of this is that it could work when interface is disable.
exec('cat /sys/class/net/'.RASPI_WIFI_CLIENT_INTERFACE.'/statistics/rx_packets ', $stdoutCatRxPackets);
$strRxPackets = _('No data');
if (ctype_digit($stdoutCatRxPackets[0])) {
$strRxPackets = $stdoutCatRxPackets[0];
}
preg_match('/link\/ether ([0-9a-f:]+)/i', $stdoutIpWRepeatedSpaces, $matchesMacAddr) || $matchesMacAddr[1] = _('No MAC Address Found');
$macAddr = $matchesMacAddr[1];
exec('cat /sys/class/net/'.RASPI_WIFI_CLIENT_INTERFACE.'/statistics/tx_packets ', $stdoutCatTxPackets);
$strTxPackets = _('No data');
if (ctype_digit($stdoutCatTxPackets[0])) {
$strTxPackets = $stdoutCatTxPackets[0];
}
$ipv4Addrs = '';
$ipv4Netmasks = '';
if (!preg_match_all('/inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/([0-3][0-9])/i', $stdoutIpWRepeatedSpaces, $matchesIpv4AddrAndSubnet)) {
$ipv4Addrs = _('No IPv4 Address Found');
} else {
$numMatchesIpv4AddrAndSubnet = count($matchesIpv4AddrAndSubnet);
for ($i = 1; $i < $numMatchesIpv4AddrAndSubnet; $i += 2) {
if ($i > 2) {
$ipv4Netmasks .= ' ';
$ipv4Addrs .= ' ';
}
exec('cat /sys/class/net/'.RASPI_WIFI_CLIENT_INTERFACE.'/statistics/rx_bytes ', $stdoutCatRxBytes);
$strRxBytes = _('No data');
if (ctype_digit($stdoutCatRxBytes[0])) {
$strRxBytes = $stdoutCatRxBytes[0];
$strRxBytes .= getHumanReadableDatasize($strRxBytes);
}
$ipv4Addrs .= $matchesIpv4AddrAndSubnet[$i][0];
$ipv4Netmasks .= long2ip(-1 << (32 -(int)$matchesIpv4AddrAndSubnet[$i+1][0]));
}
}
exec('cat /sys/class/net/'.RASPI_WIFI_CLIENT_INTERFACE.'/statistics/tx_bytes ', $stdoutCatTxBytes);
$strTxBytes = _('No data');
if (ctype_digit($stdoutCatTxBytes[0])) {
$strTxBytes = $stdoutCatTxBytes[0];
$strTxBytes .= getHumanReadableDatasize($strTxBytes);
}
$ipv6Addrs = '';
if (!preg_match_all('/inet6 ([a-f0-9:]+)/i', $stdoutIpWRepeatedSpaces, $matchesIpv6Addr)) {
$ipv6Addrs = _('No IPv6 Address Found');
} else {
$numMatchesIpv6Addr = count($matchesIpv6Addr);
for ($i = 1; $i < $numMatchesIpv6Addr; ++$i) {
if ($i > 1) {
$ipv6Addrs .= ' ';
}
define('SSIDMAXLEN', 32);
// Warning iw comes with: "Do NOT screenscrape this tool, we don't consider its output stable."
exec('iw dev '.RASPI_WIFI_CLIENT_INTERFACE.' link ', $stdoutIw);
$stdoutIwAllLinesGlued = implode(' ', $stdoutIw);
$stdoutIwWRepSpaces = preg_replace('/\s\s+/', ' ', $stdoutIwAllLinesGlued);
$ipv6Addrs .= $matchesIpv6Addr[$i];
}
}
preg_match('/Connected to (([0-9A-Fa-f]{2}:){5}([0-9A-Fa-f]{2}))/', $stdoutIwWRepSpaces, $matchesBSSID) || $matchesBSSID[1] = '';
$connectedBSSID = $matchesBSSID[1];
preg_match('/state (UP|DOWN)/i', $stdoutIpWRepeatedSpaces, $matchesState) || $matchesState[1] = 'unknown';
$interfaceState = $matchesState[1];
$wlanHasLink = false;
if ($interfaceState === 'UP') {
$wlanHasLink = true;
}
// Because of table layout used in the ip output we get the interface statistics directly from
// the system. One advantage of this is that it could work when interface is disable.
exec('cat /sys/class/net/'.RASPI_WIFI_CLIENT_INTERFACE.'/statistics/rx_packets ', $stdoutCatRxPackets);
$strRxPackets = _('No data');
if (ctype_digit($stdoutCatRxPackets[0])) {
$strRxPackets = $stdoutCatRxPackets[0];
}
exec('cat /sys/class/net/'.RASPI_WIFI_CLIENT_INTERFACE.'/statistics/tx_packets ', $stdoutCatTxPackets);
$strTxPackets = _('No data');
if (ctype_digit($stdoutCatTxPackets[0])) {
$strTxPackets = $stdoutCatTxPackets[0];
}
exec('cat /sys/class/net/'.RASPI_WIFI_CLIENT_INTERFACE.'/statistics/rx_bytes ', $stdoutCatRxBytes);
$strRxBytes = _('No data');
if (ctype_digit($stdoutCatRxBytes[0])) {
$strRxBytes = $stdoutCatRxBytes[0];
$strRxBytes .= getHumanReadableDatasize($strRxBytes);
}
exec('cat /sys/class/net/'.RASPI_WIFI_CLIENT_INTERFACE.'/statistics/tx_bytes ', $stdoutCatTxBytes);
$strTxBytes = _('No data');
if (ctype_digit($stdoutCatTxBytes[0])) {
$strTxBytes = $stdoutCatTxBytes[0];
$strTxBytes .= getHumanReadableDatasize($strTxBytes);
}
define('SSIDMAXLEN', 32);
// Warning iw comes with: "Do NOT screenscrape this tool, we don't consider its output stable."
exec('iw dev '.RASPI_WIFI_CLIENT_INTERFACE.' link ', $stdoutIw);
$stdoutIwAllLinesGlued = implode(' ', $stdoutIw);
$stdoutIwWRepSpaces = preg_replace('/\s\s+/', ' ', $stdoutIwAllLinesGlued);
preg_match('/Connected to (([0-9A-Fa-f]{2}:){5}([0-9A-Fa-f]{2}))/', $stdoutIwWRepSpaces, $matchesBSSID) || $matchesBSSID[1] = '';
$connectedBSSID = $matchesBSSID[1];
if (!preg_match('/SSID: ([^ ]{1,'.SSIDMAXLEN.'})/', $stdoutIwWRepSpaces, $matchesSSID)) {
$wlanHasLink = false;
$matchesSSID[1] = 'Not connected';
}
$connectedSSID = $matchesSSID[1];
preg_match('/freq: (\d+)/i', $stdoutIwWRepSpaces, $matchesFrequency) || $matchesFrequency[1] = '';
$frequency = $matchesFrequency[1].' MHz';
preg_match('/signal: (-?[0-9]+ dBm)/i', $stdoutIwWRepSpaces, $matchesSignal) || $matchesSignal[1] = '';
$signalLevel = $matchesSignal[1];
preg_match('/tx bitrate: ([0-9\.]+ [KMGT]?Bit\/s)/', $stdoutIwWRepSpaces, $matchesBitrate) || $matchesBitrate[1] = '';
$bitrate = $matchesBitrate[1];
// txpower is now displayed on iw dev(..) info command, not on link command.
exec('iw dev '.RASPI_WIFI_CLIENT_INTERFACE.' info ', $stdoutIwInfo);
$stdoutIwInfoAllLinesGlued = implode(' ', $stdoutIwInfo);
$stdoutIpInfoWRepSpaces = preg_replace('/\s\s+/', ' ', $stdoutIwInfoAllLinesGlued);
preg_match('/txpower ([0-9\.]+ dBm)/i', $stdoutIpInfoWRepSpaces, $matchesTxPower ) || $matchesTxPower[1] = '';
$txPower = $matchesTxPower[1];
// iw does not have the "Link Quality". This is a is an aggregate value,
// and depends on the driver and hardware.
// Display link quality as signal quality for now.
$strLinkQuality = 0;
if ($signalLevel > -100 && $wlanHasLink) {
if ($signalLevel >= 0) {
$strLinkQuality = 100;
} else {
$strLinkQuality = 100 + $signalLevel;
}
}
$wlan0up = false;
$classMsgDevicestatus = 'warning';
if ($interfaceState === 'UP') {
$wlan0up = true;
$classMsgDevicestatus = 'success';
}
if (isset($_POST['ifdown_wlan0'])) {
// Pressed stop button
if ($interfaceState === 'UP') {
$status->addMessage(sprintf(_('Interface is going %s.'), _('down')), 'warning');
exec( 'sudo ip link set '.RASPI_WIFI_CLIENT_INTERFACE.' down' );
$wlan0up = false;
$status->addMessage(sprintf(_('Interface is now %s.'), _('down')), 'success');
} elseif ($interfaceState === 'unknown') {
$status->addMessage(_('Interface state unknown.'), 'danger');
} else {
$status->addMessage(sprintf(_('Interface already %s.'), _('down')), 'warning');
$wlanHasLink = true;
}
} elseif( isset($_POST['ifup_wlan0']) ) {
// Pressed start button
if ($interfaceState === 'DOWN') {
$status->addMessage(sprintf(_('Interface is going %s.'), _('up')), 'warning');
exec('sudo ip link set ' . RASPI_WIFI_CLIENT_INTERFACE . ' up');
exec('sudo ip -s a f label ' . RASPI_WIFI_CLIENT_INTERFACE);
$wlan0up = true;
$status->addMessage(sprintf(_('Interface is now %s.'), _('up')), 'success');
} elseif ($interfaceState === 'unknown') {
$status->addMessage(_('Interface state unknown.'), 'danger');
} else {
$status->addMessage(sprintf(_('Interface already %s.'), _('up')), 'warning');
if (!preg_match('/SSID: ([^ ]{1,'.SSIDMAXLEN.'})/', $stdoutIwWRepSpaces, $matchesSSID)) {
$wlanHasLink = false;
$matchesSSID[1] = 'Not connected';
}
} else {
$status->addMessage(sprintf(_('Interface is %s.'), strtolower($interfaceState)), $classMsgDevicestatus);
}
?>
<div class="row">
$connectedSSID = $matchesSSID[1];
preg_match('/freq: (\d+)/i', $stdoutIwWRepSpaces, $matchesFrequency) || $matchesFrequency[1] = '';
$frequency = $matchesFrequency[1].' MHz';
preg_match('/signal: (-?[0-9]+ dBm)/i', $stdoutIwWRepSpaces, $matchesSignal) || $matchesSignal[1] = '';
$signalLevel = $matchesSignal[1];
preg_match('/tx bitrate: ([0-9\.]+ [KMGT]?Bit\/s)/', $stdoutIwWRepSpaces, $matchesBitrate) || $matchesBitrate[1] = '';
$bitrate = $matchesBitrate[1];
// txpower is now displayed on iw dev(..) info command, not on link command.
exec('iw dev '.RASPI_WIFI_CLIENT_INTERFACE.' info ', $stdoutIwInfo);
$stdoutIwInfoAllLinesGlued = implode(' ', $stdoutIwInfo);
$stdoutIpInfoWRepSpaces = preg_replace('/\s\s+/', ' ', $stdoutIwInfoAllLinesGlued);
preg_match('/txpower ([0-9\.]+ dBm)/i', $stdoutIpInfoWRepSpaces, $matchesTxPower) || $matchesTxPower[1] = '';
$txPower = $matchesTxPower[1];
// iw does not have the "Link Quality". This is a is an aggregate value,
// and depends on the driver and hardware.
// Display link quality as signal quality for now.
$strLinkQuality = 0;
if ($signalLevel > -100 && $wlanHasLink) {
if ($signalLevel >= 0) {
$strLinkQuality = 100;
} else {
$strLinkQuality = 100 + $signalLevel;
}
}
$wlan0up = false;
$classMsgDevicestatus = 'warning';
if ($interfaceState === 'UP') {
$wlan0up = true;
$classMsgDevicestatus = 'success';
}
if (isset($_POST['ifdown_wlan0'])) {
// Pressed stop button
if ($interfaceState === 'UP') {
$status->addMessage(sprintf(_('Interface is going %s.'), _('down')), 'warning');
exec('sudo ip link set '.RASPI_WIFI_CLIENT_INTERFACE.' down');
$wlan0up = false;
$status->addMessage(sprintf(_('Interface is now %s.'), _('down')), 'success');
} elseif ($interfaceState === 'unknown') {
$status->addMessage(_('Interface state unknown.'), 'danger');
} else {
$status->addMessage(sprintf(_('Interface already %s.'), _('down')), 'warning');
}
} elseif (isset($_POST['ifup_wlan0'])) {
// Pressed start button
if ($interfaceState === 'DOWN') {
$status->addMessage(sprintf(_('Interface is going %s.'), _('up')), 'warning');
exec('sudo ip link set ' . RASPI_WIFI_CLIENT_INTERFACE . ' up');
exec('sudo ip -s a f label ' . RASPI_WIFI_CLIENT_INTERFACE);
$wlan0up = true;
$status->addMessage(sprintf(_('Interface is now %s.'), _('up')), 'success');
} elseif ($interfaceState === 'unknown') {
$status->addMessage(_('Interface state unknown.'), 'danger');
} else {
$status->addMessage(sprintf(_('Interface already %s.'), _('up')), 'warning');
}
} else {
$status->addMessage(sprintf(_('Interface is %s.'), strtolower($interfaceState)), $classMsgDevicestatus);
}
?>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading"><i class="fa fa-dashboard fa-fw"></i> <?php echo _("Dashboard"); ?></div>
@ -238,7 +239,7 @@ function DisplayDashboard(){
<tbody>
<?php
exec('cat '.RASPI_DNSMASQ_LEASES.'| grep -E $(arp -i '.RASPI_WIFI_CLIENT_INTERFACE.' | grep -oE "(([0-9]|[a-f]|[A-F]){2}:){5}([0-9]|[a-f]|[A-F]){2}" | tr "\n" "\|" | sed "s/.$//")', $clients);
foreach( $clients as $client ) {
foreach ($clients as $client) {
$client_items = explode(' ', $client);
echo '<tr>'.PHP_EOL;
echo '<td>'.htmlspecialchars($client_items[3], ENT_QUOTES).'</td>'.PHP_EOL;
@ -258,12 +259,12 @@ foreach( $clients as $client ) {
<div class="col-lg-12">
<div class="row">
<form action="?page=wlan0_info" method="POST">
<?php if ( !$wlan0up ) {
echo '<input type="submit" class="btn btn-success" value="'._("Start ").RASPI_WIFI_CLIENT_INTERFACE.'" name="ifup_wlan0" />';
} else {
echo '<input type="submit" class="btn btn-warning" value="'._("Stop ").RASPI_WIFI_CLIENT_INTERFACE.'" name="ifdown_wlan0" />';
}
?>
<?php if (!$wlan0up) {
echo '<input type="submit" class="btn btn-success" value="'._("Start ").RASPI_WIFI_CLIENT_INTERFACE.'" name="ifup_wlan0" />';
} else {
echo '<input type="submit" class="btn btn-warning" value="'._("Stop ").RASPI_WIFI_CLIENT_INTERFACE.'" name="ifdown_wlan0" />';
}
?>
<input type="button" class="btn btn-outline btn-primary" value="<?php echo _("Refresh"); ?>" onclick="document.location.reload(true)" />
</form>
</div>
@ -274,7 +275,7 @@ foreach( $clients as $client ) {
</div><!-- /.panel-default -->
</div><!-- /.col-lg-12 -->
</div><!-- /.row -->
<?php
<?php
}
@ -287,24 +288,24 @@ foreach( $clients as $client ) {
*/
function getHumanReadableDatasize($numbytes, $precision = 2)
{
$humanDatasize = '';
$kib = 1024;
$mib = $kib * 1024;
$gib = $mib * 1024;
$tib = $gib * 1024;
$pib = $tib * 1024;
if ($numbytes >= $pib) {
$humanDatasize = ' ('.round($numbytes / $pib, $precision).' PB)';
} elseif ($numbytes >= $tib) {
$humanDatasize = ' ('.round($numbytes / $tib, $precision).' TB)';
} elseif ($numbytes >= $gib) {
$humanDatasize = ' ('.round($numbytes / $gib, $precision).' GB)';
} elseif ($numbytes >= $mib) {
$humanDatasize = ' ('.round($numbytes / $mib, $precision).' MB)';
} elseif ($numbytes >= $kib) {
$humanDatasize = ' ('.round($numbytes / $kib, $precision).' KB)';
}
$humanDatasize = '';
$kib = 1024;
$mib = $kib * 1024;
$gib = $mib * 1024;
$tib = $gib * 1024;
$pib = $tib * 1024;
if ($numbytes >= $pib) {
$humanDatasize = ' ('.round($numbytes / $pib, $precision).' PB)';
} elseif ($numbytes >= $tib) {
$humanDatasize = ' ('.round($numbytes / $tib, $precision).' TB)';
} elseif ($numbytes >= $gib) {
$humanDatasize = ' ('.round($numbytes / $gib, $precision).' GB)';
} elseif ($numbytes >= $mib) {
$humanDatasize = ' ('.round($numbytes / $mib, $precision).' MB)';
} elseif ($numbytes >= $kib) {
$humanDatasize = ' ('.round($numbytes / $kib, $precision).' KB)';
}
return $humanDatasize;
return $humanDatasize;
}

View file

@ -5,7 +5,7 @@
*/
function DisplayDataUsage(&$extraFooterScripts)
{
exec("ip -o link show | awk -F ': ' '{print $2}' | grep -v lo ", $interfacesWlo);
exec("ip -o link show | awk -F ': ' '{print $2}' | grep -v lo ", $interfacesWlo);
?>
<div class="row">
<div class="col-lg-12">

View file

@ -1,139 +1,140 @@
<?php
include_once( 'includes/status_messages.php' );
include_once('includes/status_messages.php');
/**
*
* Manage DHCP configuration
*
*/
function DisplayDHCPConfig() {
function DisplayDHCPConfig()
{
$status = new StatusMessages();
if( isset( $_POST['savedhcpdsettings'] ) ) {
if (CSRFValidate()) {
$errors = '';
define('IFNAMSIZ', 16);
if (!preg_match('/^[a-zA-Z0-9]+$/', $_POST['interface']) ||
$status = new StatusMessages();
if (isset($_POST['savedhcpdsettings'])) {
if (CSRFValidate()) {
$errors = '';
define('IFNAMSIZ', 16);
if (!preg_match('/^[a-zA-Z0-9]+$/', $_POST['interface']) ||
strlen($_POST['interface']) >= IFNAMSIZ) {
$errors .= _('Invalid interface name.').'<br />'.PHP_EOL;
}
if (!preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/', $_POST['RangeStart']) &&
!empty($_POST['RangeStart'])) { // allow ''/null ?
$errors .= _('Invalid DHCP range start.').'<br />'.PHP_EOL;
}
if (!preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/', $_POST['RangeEnd']) &&
!empty($_POST['RangeEnd'])) { // allow ''/null ?
$errors .= _('Invalid DHCP range end.').'<br />'.PHP_EOL;
}
if (!ctype_digit($_POST['RangeLeaseTime']) && $_POST['RangeLeaseTimeUnits'] !== 'infinite') {
$errors .= _('Invalid DHCP lease time, not a number.').'<br />'.PHP_EOL;
}
if (!in_array($_POST['RangeLeaseTimeUnits'], array('m', 'h', 'd', 'infinite'))) {
$errors .= _('Unknown DHCP lease time unit.').'<br />'.PHP_EOL;
}
$return = 1;
if (empty($errors)) {
$config = 'interface='.$_POST['interface'].PHP_EOL.
'dhcp-range='.$_POST['RangeStart'].','.$_POST['RangeEnd'].
',255.255.255.0,';
if ($_POST['RangeLeaseTimeUnits'] !== 'infinite') {
$config .= $_POST['RangeLeaseTime'];
$errors .= _('Invalid interface name.').'<br />'.PHP_EOL;
}
$config .= $_POST['RangeLeaseTimeUnits'];
exec('echo "'.$config.'" > /tmp/dhcpddata', $temp);
system('sudo cp /tmp/dhcpddata '.RASPI_DNSMASQ_CONFIG, $return);
} else {
$status->addMessage($errors, 'danger');
}
if (!preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/', $_POST['RangeStart']) &&
!empty($_POST['RangeStart'])) { // allow ''/null ?
$errors .= _('Invalid DHCP range start.').'<br />'.PHP_EOL;
}
if ($return == 0) {
$status->addMessage('Dnsmasq configuration updated successfully', 'success');
if (!preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/', $_POST['RangeEnd']) &&
!empty($_POST['RangeEnd'])) { // allow ''/null ?
$errors .= _('Invalid DHCP range end.').'<br />'.PHP_EOL;
}
if (!ctype_digit($_POST['RangeLeaseTime']) && $_POST['RangeLeaseTimeUnits'] !== 'infinite') {
$errors .= _('Invalid DHCP lease time, not a number.').'<br />'.PHP_EOL;
}
if (!in_array($_POST['RangeLeaseTimeUnits'], array('m', 'h', 'd', 'infinite'))) {
$errors .= _('Unknown DHCP lease time unit.').'<br />'.PHP_EOL;
}
$return = 1;
if (empty($errors)) {
$config = 'interface='.$_POST['interface'].PHP_EOL.
'dhcp-range='.$_POST['RangeStart'].','.$_POST['RangeEnd'].
',255.255.255.0,';
if ($_POST['RangeLeaseTimeUnits'] !== 'infinite') {
$config .= $_POST['RangeLeaseTime'];
}
$config .= $_POST['RangeLeaseTimeUnits'];
exec('echo "'.$config.'" > /tmp/dhcpddata', $temp);
system('sudo cp /tmp/dhcpddata '.RASPI_DNSMASQ_CONFIG, $return);
} else {
$status->addMessage($errors, 'danger');
}
if ($return == 0) {
$status->addMessage('Dnsmasq configuration updated successfully', 'success');
} else {
$status->addMessage('Dnsmasq configuration failed to be updated.', 'danger');
}
} else {
$status->addMessage('Dnsmasq configuration failed to be updated.', 'danger');
error_log('CSRF violation');
}
}
exec('pidof dnsmasq | wc -l', $dnsmasq);
$dnsmasq_state = ($dnsmasq[0] > 0);
if (isset($_POST['startdhcpd'])) {
if (CSRFValidate()) {
if ($dnsmasq_state) {
$status->addMessage('dnsmasq already running', 'info');
} else {
exec('sudo /etc/init.d/dnsmasq start', $dnsmasq, $return);
if ($return == 0) {
$status->addMessage('Successfully started dnsmasq', 'success');
$dnsmasq_state = true;
} else {
$status->addMessage('Failed to start dnsmasq', 'danger');
}
}
} else {
error_log('CSRF violation');
}
} elseif (isset($_POST['stopdhcpd'])) {
if (CSRFValidate()) {
if ($dnsmasq_state) {
exec('sudo /etc/init.d/dnsmasq stop', $dnsmasq, $return);
if ($return == 0) {
$status->addMessage('Successfully stopped dnsmasq', 'success');
$dnsmasq_state = false;
} else {
$status->addMessage('Failed to stop dnsmasq', 'danger');
}
} else {
$status->addMessage('dnsmasq already stopped', 'info');
}
} else {
error_log('CSRF violation');
}
} else {
error_log('CSRF violation');
}
}
exec( 'pidof dnsmasq | wc -l',$dnsmasq );
$dnsmasq_state = ($dnsmasq[0] > 0);
if( isset( $_POST['startdhcpd'] ) ) {
if (CSRFValidate()) {
if ($dnsmasq_state) {
$status->addMessage('dnsmasq already running', 'info');
} else {
exec('sudo /etc/init.d/dnsmasq start', $dnsmasq, $return);
if ($return == 0) {
$status->addMessage('Successfully started dnsmasq', 'success');
$dnsmasq_state = true;
if ($dnsmasq_state) {
$status->addMessage('Dnsmasq is running', 'success');
} else {
$status->addMessage('Failed to start dnsmasq', 'danger');
$status->addMessage('Dnsmasq is not running', 'warning');
}
}
} else {
error_log('CSRF violation');
}
} elseif( isset($_POST['stopdhcpd'] ) ) {
if (CSRFValidate()) {
if ($dnsmasq_state) {
exec('sudo /etc/init.d/dnsmasq stop', $dnsmasq, $return);
if ($return == 0) {
$status->addMessage('Successfully stopped dnsmasq', 'success');
$dnsmasq_state = false;
} else {
$status->addMessage('Failed to stop dnsmasq', 'danger');
exec('cat '. RASPI_DNSMASQ_CONFIG, $return);
$conf = ParseConfig($return);
$arrRange = explode(",", $conf['dhcp-range']);
$RangeStart = $arrRange[0];
$RangeEnd = $arrRange[1];
$RangeMask = $arrRange[2];
$leaseTime = $arrRange[3];
$hselected = '';
$mselected = '';
$dselected = '';
$infiniteselected = '';
preg_match('/([0-9]*)([a-z])/i', $leaseTime, $arrRangeLeaseTime);
if ($leaseTime === 'infinite') {
$infiniteselected = ' selected="selected"';
} else {
switch ($arrRangeLeaseTime[2]) {
case 'h':
$hselected = ' selected="selected"';
break;
case 'm':
$mselected = ' selected="selected"';
break;
case 'd':
$dselected = ' selected="selected"';
break;
}
} else {
$status->addMessage('dnsmasq already stopped', 'info');
}
} else {
error_log('CSRF violation');
}
} else {
if( $dnsmasq_state ) {
$status->addMessage('Dnsmasq is running', 'success');
} else {
$status->addMessage('Dnsmasq is not running', 'warning');
}
}
exec( 'cat '. RASPI_DNSMASQ_CONFIG, $return );
$conf = ParseConfig($return);
$arrRange = explode( ",", $conf['dhcp-range'] );
$RangeStart = $arrRange[0];
$RangeEnd = $arrRange[1];
$RangeMask = $arrRange[2];
$leaseTime = $arrRange[3];
$hselected = '';
$mselected = '';
$dselected = '';
$infiniteselected = '';
preg_match( '/([0-9]*)([a-z])/i', $leaseTime, $arrRangeLeaseTime );
if ($leaseTime === 'infinite') {
$infiniteselected = ' selected="selected"';
} else {
switch( $arrRangeLeaseTime[2] ) {
case 'h':
$hselected = ' selected="selected"';
break;
case 'm':
$mselected = ' selected="selected"';
break;
case 'd':
$dselected = ' selected="selected"';
break;
}
}
?>
<div class="row">
@ -160,18 +161,18 @@ function DisplayDHCPConfig() {
<div class="form-group col-md-4">
<label for="code">Interface</label>
<select class="form-control" name="interface">
<?php
<?php
exec("ip -o link show | awk -F': ' '{print $2}'", $interfaces);
foreach( $interfaces as $inet ) {
$select = '';
if( $inet === $conf['interface'] ) {
$select = ' selected="selected"';
}
foreach ($interfaces as $inet) {
$select = '';
if ($inet === $conf['interface']) {
$select = ' selected="selected"';
}
echo ' <option value="'.htmlspecialchars($inet, ENT_QUOTES).'"'.
$select.'>'.htmlspecialchars($inet, ENT_QUOTES).'</option>' , PHP_EOL;
}
echo ' <option value="'.htmlspecialchars($inet, ENT_QUOTES).'"'.
$select.'>'.htmlspecialchars($inet, ENT_QUOTES).'</option>' , PHP_EOL;
}
?>
</select>
</div>
@ -209,12 +210,12 @@ function DisplayDHCPConfig() {
<input type="submit" class="btn btn-outline btn-primary" value="<?php echo _("Save settings"); ?>" name="savedhcpdsettings" />
<?php
if ( $dnsmasq_state ) {
echo '<input type="submit" class="btn btn-warning" value="' . _("Stop dnsmasq") . '" name="stopdhcpd" />';
if ($dnsmasq_state) {
echo '<input type="submit" class="btn btn-warning" value="' . _("Stop dnsmasq") . '" name="stopdhcpd" />';
} else {
echo'<input type="submit" class="btn btn-success" value="' . _("Start dnsmasq") . '" name="startdhcpd" />';
echo'<input type="submit" class="btn btn-success" value="' . _("Start dnsmasq") . '" name="startdhcpd" />';
}
?>
?>
</form>
</div><!-- /.tab-pane -->
@ -238,11 +239,11 @@ function DisplayDHCPConfig() {
</thead>
<tbody>
<?php
exec( 'cat ' . RASPI_DNSMASQ_LEASES, $leases );
foreach( $leases as $lease ) {
exec('cat ' . RASPI_DNSMASQ_LEASES, $leases);
foreach ($leases as $lease) {
echo ' <tr>'.PHP_EOL;
$lease_items = explode(' ', $lease);
foreach( $lease_items as $lease_item ) {
foreach ($lease_items as $lease_item) {
echo ' <td>'.htmlspecialchars($lease_item, ENT_QUOTES).'</td>'.PHP_EOL;
}
echo ' </tr>'.PHP_EOL;

View file

@ -1,38 +1,46 @@
<?php
/* Functions for Networking */
function mask2cidr($mask){
$long = ip2long($mask);
$base = ip2long('255.255.255.255');
return 32-log(($long ^ $base)+1,2);
function mask2cidr($mask)
{
$long = ip2long($mask);
$base = ip2long('255.255.255.255');
return 32-log(($long ^ $base)+1, 2);
}
/* Functions to write ini files */
function write_php_ini($array, $file) {
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val) {
if(is_array($val)) {
foreach ($array as $key => $val) {
if (is_array($val)) {
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
foreach ($val as $skey => $sval) {
$res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
} else {
$res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
if(safefilerewrite($file, implode("\r\n", $res))) {
if (safefilerewrite($file, implode("\r\n", $res))) {
return true;
} else {
return false;
}
}
function safefilerewrite($fileName, $dataToSave) {
function safefilerewrite($fileName, $dataToSave)
{
if ($fp = fopen($fileName, 'w')) {
$startTime = microtime(TRUE);
$startTime = microtime(true);
do {
$canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
if (!$canWrite) {
usleep(round(rand(0, 100)*1000));
}
} while ((!$canWrite)and((microtime(true)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite) {
@ -46,16 +54,16 @@ function safefilerewrite($fileName, $dataToSave) {
}
}
/**
*
* Add CSRF Token to form
*
*/
function CSRFToken() {
function CSRFToken()
{
?>
<input id="csrf_token" type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES);; ?>" />
<input id="csrf_token" type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES);
; ?>" />
<?php
}
@ -64,20 +72,22 @@ function CSRFToken() {
* Validate CSRF Token
*
*/
function CSRFValidate() {
if ( hash_equals($_POST['csrf_token'], $_SESSION['csrf_token']) ) {
return true;
} else {
error_log('CSRF violation');
return false;
}
function CSRFValidate()
{
if (hash_equals($_POST['csrf_token'], $_SESSION['csrf_token'])) {
return true;
} else {
error_log('CSRF violation');
return false;
}
}
/**
* Test whether array is associative
*/
function isAssoc($arr) {
return array_keys($arr) !== range(0, count($arr) - 1);
function isAssoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
/**
@ -89,25 +99,26 @@ function isAssoc($arr) {
* If $options is an associative array this should be the key
*
*/
function SelectorOptions($name, $options, $selected = null, $id = null) {
echo '<select class="form-control" name="'.htmlspecialchars($name, ENT_QUOTES).'"';
if (isset($id)) {
echo ' id="' . htmlspecialchars($id, ENT_QUOTES) .'"';
}
echo '>' , PHP_EOL;
foreach ( $options as $opt => $label) {
$select = '';
$key = isAssoc($options) ? $opt : $label;
if( $key == $selected ) {
$select = ' selected="selected"';
function SelectorOptions($name, $options, $selected = null, $id = null)
{
echo '<select class="form-control" name="'.htmlspecialchars($name, ENT_QUOTES).'"';
if (isset($id)) {
echo ' id="' . htmlspecialchars($id, ENT_QUOTES) .'"';
}
echo '<option value="'.htmlspecialchars($key, ENT_QUOTES).'"'.$select.'>'.
htmlspecialchars($label, ENT_QUOTES).'</option>' , PHP_EOL;
}
echo '>' , PHP_EOL;
foreach ($options as $opt => $label) {
$select = '';
$key = isAssoc($options) ? $opt : $label;
if ($key == $selected) {
$select = ' selected="selected"';
}
echo '</select>' , PHP_EOL;
echo '<option value="'.htmlspecialchars($key, ENT_QUOTES).'"'.$select.'>'.
htmlspecialchars($label, ENT_QUOTES).'</option>' , PHP_EOL;
}
echo '</select>' , PHP_EOL;
}
/**
@ -118,9 +129,10 @@ function SelectorOptions($name, $options, $selected = null, $id = null) {
* @param string $separator
* @return $string
*/
function GetDistString( $input,$string,$offset,$separator ) {
$string = substr( $input,strpos( $input,$string )+$offset,strpos( substr( $input,strpos( $input,$string )+$offset ), $separator ) );
return $string;
function GetDistString($input, $string, $offset, $separator)
{
$string = substr($input, strpos($input, $string)+$offset, strpos(substr($input, strpos($input, $string)+$offset), $separator));
return $string;
}
/**
@ -128,16 +140,17 @@ function GetDistString( $input,$string,$offset,$separator ) {
* @param array $arrConfig
* @return $config
*/
function ParseConfig( $arrConfig ) {
$config = array();
foreach( $arrConfig as $line ) {
$line = trim($line);
if( $line != "" && $line[0] != "#" ) {
$arrLine = explode( "=",$line );
$config[$arrLine[0]] = ( count($arrLine) > 1 ? $arrLine[1] : true );
}
}
return $config;
function ParseConfig($arrConfig)
{
$config = array();
foreach ($arrConfig as $line) {
$line = trim($line);
if ($line != "" && $line[0] != "#") {
$arrLine = explode("=", $line);
$config[$arrLine[0]] = ( count($arrLine) > 1 ? $arrLine[1] : true );
}
}
return $config;
}
/**
@ -145,21 +158,22 @@ function ParseConfig( $arrConfig ) {
* @param string $freq
* @return $channel
*/
function ConvertToChannel( $freq ) {
if ($freq >= 2412 && $freq <= 2484) {
$channel = ($freq - 2407)/5;
} elseif ($freq >= 4915 && $freq <= 4980) {
$channel = ($freq - 4910)/5 + 182;
} elseif ($freq >= 5035 && $freq <= 5865) {
$channel = ($freq - 5030)/5 + 6;
} else {
$channel = -1;
}
if ($channel >= 1 && $channel <= 196) {
return $channel;
} else {
return 'Invalid Channel';
}
function ConvertToChannel($freq)
{
if ($freq >= 2412 && $freq <= 2484) {
$channel = ($freq - 2407)/5;
} elseif ($freq >= 4915 && $freq <= 4980) {
$channel = ($freq - 4910)/5 + 182;
} elseif ($freq >= 5035 && $freq <= 5865) {
$channel = ($freq - 5030)/5 + 6;
} else {
$channel = -1;
}
if ($channel >= 1 && $channel <= 196) {
return $channel;
} else {
return 'Invalid Channel';
}
}
/**
@ -167,154 +181,156 @@ function ConvertToChannel( $freq ) {
* @param string $security
* @return string
*/
function ConvertToSecurity( $security ) {
$options = array();
preg_match_all('/\[([^\]]+)\]/s', $security, $matches);
foreach($matches[1] as $match) {
if (preg_match('/^(WPA\d?)/', $match, $protocol_match)) {
$protocol = $protocol_match[1];
$matchArr = explode('-', $match);
if (count($matchArr) > 2) {
$options[] = htmlspecialchars($protocol . ' ('. $matchArr[2] .')', ENT_QUOTES);
} else {
$options[] = htmlspecialchars($protocol, ENT_QUOTES);
}
function ConvertToSecurity($security)
{
$options = array();
preg_match_all('/\[([^\]]+)\]/s', $security, $matches);
foreach ($matches[1] as $match) {
if (preg_match('/^(WPA\d?)/', $match, $protocol_match)) {
$protocol = $protocol_match[1];
$matchArr = explode('-', $match);
if (count($matchArr) > 2) {
$options[] = htmlspecialchars($protocol . ' ('. $matchArr[2] .')', ENT_QUOTES);
} else {
$options[] = htmlspecialchars($protocol, ENT_QUOTES);
}
}
}
}
if (count($options) === 0) {
// This could also be WEP but wpa_supplicant doesn't have a way to determine
// this.
// And you shouldn't be using WEP these days anyway.
return 'Open';
} else {
return implode('<br />', $options);
}
if (count($options) === 0) {
// This could also be WEP but wpa_supplicant doesn't have a way to determine
// this.
// And you shouldn't be using WEP these days anyway.
return 'Open';
} else {
return implode('<br />', $options);
}
}
/**
*
*
*/
function DisplayOpenVPNConfig() {
function DisplayOpenVPNConfig()
{
exec( 'cat '. RASPI_OPENVPN_CLIENT_CONFIG, $returnClient );
exec( 'cat '. RASPI_OPENVPN_SERVER_CONFIG, $returnServer );
exec( 'pidof openvpn | wc -l', $openvpnstatus);
exec('cat '. RASPI_OPENVPN_CLIENT_CONFIG, $returnClient);
exec('cat '. RASPI_OPENVPN_SERVER_CONFIG, $returnServer);
exec('pidof openvpn | wc -l', $openvpnstatus);
if( $openvpnstatus[0] == 0 ) {
$status = '<div class="alert alert-warning alert-dismissable">OpenVPN is not running
if ($openvpnstatus[0] == 0) {
$status = '<div class="alert alert-warning alert-dismissable">OpenVPN is not running
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button></div>';
} else {
$status = '<div class="alert alert-success alert-dismissable">OpenVPN is running
} else {
$status = '<div class="alert alert-success alert-dismissable">OpenVPN is running
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button></div>';
}
}
// parse client settings
foreach( $returnClient as $a ) {
if( $a[0] != "#" ) {
$arrLine = explode( " ",$a) ;
$arrClientConfig[$arrLine[0]]=$arrLine[1];
}
}
// parse client settings
foreach ($returnClient as $a) {
if ($a[0] != "#") {
$arrLine = explode(" ", $a) ;
$arrClientConfig[$arrLine[0]]=$arrLine[1];
}
}
// parse server settings
foreach( $returnServer as $a ) {
if( $a[0] != "#" ) {
$arrLine = explode( " ",$a) ;
$arrServerConfig[$arrLine[0]]=$arrLine[1];
}
}
?>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading"><i class="fa fa-lock fa-fw"></i> Configure OpenVPN </div>
<!-- /.panel-heading -->
<div class="panel-body">
<!-- Nav tabs -->
<ul class="nav nav-tabs">
<li class="active"><a href="#openvpnclient" data-toggle="tab">Client settings</a></li>
<li><a href="#openvpnserver" data-toggle="tab">Server settings</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<p><?php echo $status; ?></p>
<div class="tab-pane fade in active" id="openvpnclient">
// parse server settings
foreach ($returnServer as $a) {
if ($a[0] != "#") {
$arrLine = explode(" ", $a) ;
$arrServerConfig[$arrLine[0]]=$arrLine[1];
}
}
?>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading"><i class="fa fa-lock fa-fw"></i> Configure OpenVPN </div>
<!-- /.panel-heading -->
<div class="panel-body">
<!-- Nav tabs -->
<ul class="nav nav-tabs">
<li class="active"><a href="#openvpnclient" data-toggle="tab">Client settings</a></li>
<li><a href="#openvpnserver" data-toggle="tab">Server settings</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<p><?php echo $status; ?></p>
<div class="tab-pane fade in active" id="openvpnclient">
<h4>Client settings</h4>
<form role="form" action="?page=save_hostapd_conf" method="POST">
<h4>Client settings</h4>
<form role="form" action="?page=save_hostapd_conf" method="POST">
<div class="row">
<div class="form-group col-md-4">
<label>Select OpenVPN configuration file (.ovpn)</label>
<input type="file" name="openvpn-config">
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Client Log</label>
<input type="text" class="form-control" id="disabledInput" name="log-append" type="text" placeholder="<?php echo htmlspecialchars($arrClientConfig['log-append'], ENT_QUOTES); ?>" disabled="disabled" />
</div>
</div>
</div>
<div class="tab-pane fade" id="openvpnserver">
<h4>Server settings</h4>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Port</label>
<input type="text" class="form-control" name="openvpn_port" value="<?php echo htmlspecialchars($arrServerConfig['port'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Protocol</label>
<input type="text" class="form-control" name="openvpn_proto" value="<?php echo htmlspecialchars($arrServerConfig['proto'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Root CA certificate</label>
<input type="text" class="form-control" name="openvpn_rootca" placeholder="<?php echo htmlspecialchars($arrServerConfig['ca'], ENT_QUOTES); ?>" disabled="disabled" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Server certificate</label>
<input type="text" class="form-control" name="openvpn_cert" placeholder="<?php echo htmlspecialchars($arrServerConfig['cert'], ENT_QUOTES); ?>" disabled="disabled" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Diffie Hellman parameters</label>
<input type="text" class="form-control" name="openvpn_dh" placeholder="<?php echo htmlspecialchars($arrServerConfig['dh'], ENT_QUOTES); ?>" disabled="disabled" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">KeepAlive</label>
<input type="text" class="form-control" name="openvpn_keepalive" value="<?php echo htmlspecialchars($arrServerConfig['keepalive'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Server log</label>
<input type="text" class="form-control" name="openvpn_status" placeholder="<?php echo htmlspecialchars($arrServerConfig['status'], ENT_QUOTES); ?>" disabled="disabled" />
</div>
</div>
</div>
<input type="submit" class="btn btn-outline btn-primary" name="SaveOpenVPNSettings" value="Save settings" />
<?php
if($hostapdstatus[0] == 0) {
echo '<input type="submit" class="btn btn-success" name="StartOpenVPN" value="Start OpenVPN" />' , PHP_EOL;
} else {
echo '<input type="submit" class="btn btn-warning" name="StopOpenVPN" value="Stop OpenVPN" />' , PHP_EOL;
}
<div class="row">
<div class="form-group col-md-4">
<label>Select OpenVPN configuration file (.ovpn)</label>
<input type="file" name="openvpn-config">
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Client Log</label>
<input type="text" class="form-control" id="disabledInput" name="log-append" type="text" placeholder="<?php echo htmlspecialchars($arrClientConfig['log-append'], ENT_QUOTES); ?>" disabled="disabled" />
</div>
</div>
</div>
<div class="tab-pane fade" id="openvpnserver">
<h4>Server settings</h4>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Port</label>
<input type="text" class="form-control" name="openvpn_port" value="<?php echo htmlspecialchars($arrServerConfig['port'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Protocol</label>
<input type="text" class="form-control" name="openvpn_proto" value="<?php echo htmlspecialchars($arrServerConfig['proto'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Root CA certificate</label>
<input type="text" class="form-control" name="openvpn_rootca" placeholder="<?php echo htmlspecialchars($arrServerConfig['ca'], ENT_QUOTES); ?>" disabled="disabled" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Server certificate</label>
<input type="text" class="form-control" name="openvpn_cert" placeholder="<?php echo htmlspecialchars($arrServerConfig['cert'], ENT_QUOTES); ?>" disabled="disabled" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Diffie Hellman parameters</label>
<input type="text" class="form-control" name="openvpn_dh" placeholder="<?php echo htmlspecialchars($arrServerConfig['dh'], ENT_QUOTES); ?>" disabled="disabled" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">KeepAlive</label>
<input type="text" class="form-control" name="openvpn_keepalive" value="<?php echo htmlspecialchars($arrServerConfig['keepalive'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Server log</label>
<input type="text" class="form-control" name="openvpn_status" placeholder="<?php echo htmlspecialchars($arrServerConfig['status'], ENT_QUOTES); ?>" disabled="disabled" />
</div>
</div>
</div>
<input type="submit" class="btn btn-outline btn-primary" name="SaveOpenVPNSettings" value="Save settings" />
<?php
if ($hostapdstatus[0] == 0) {
echo '<input type="submit" class="btn btn-success" name="StartOpenVPN" value="Start OpenVPN" />' , PHP_EOL;
} else {
echo '<input type="submit" class="btn btn-warning" name="StopOpenVPN" value="Stop OpenVPN" />' , PHP_EOL;
}
?>
</form>
</div><!-- /.panel-body -->
</div><!-- /.panel-primary -->
<div class="panel-footer"> Information provided by openvpn</div>
</form>
</div><!-- /.panel-body -->
</div><!-- /.panel-primary -->
<div class="panel-footer"> Information provided by openvpn</div>
</div><!-- /.col-lg-12 -->
</div><!-- /.row -->
<?php
@ -324,35 +340,36 @@ function DisplayOpenVPNConfig() {
*
*
*/
function DisplayTorProxyConfig(){
function DisplayTorProxyConfig()
{
exec( 'cat '. RASPI_TORPROXY_CONFIG, $return );
exec( 'pidof tor | wc -l', $torproxystatus);
exec('cat '. RASPI_TORPROXY_CONFIG, $return);
exec('pidof tor | wc -l', $torproxystatus);
if( $torproxystatus[0] == 0 ) {
$status = '<div class="alert alert-warning alert-dismissable">TOR is not running
if ($torproxystatus[0] == 0) {
$status = '<div class="alert alert-warning alert-dismissable">TOR is not running
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button></div>';
} else {
$status = '<div class="alert alert-success alert-dismissable">TOR is running
} else {
$status = '<div class="alert alert-success alert-dismissable">TOR is running
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button></div>';
}
}
$arrConfig = array();
foreach( $return as $a ) {
if( $a[0] != "#" ) {
$arrLine = explode( " ",$a) ;
$arrConfig[$arrLine[0]]=$arrLine[1];
}
}
$arrConfig = array();
foreach ($return as $a) {
if ($a[0] != "#") {
$arrLine = explode(" ", $a) ;
$arrConfig[$arrLine[0]]=$arrLine[1];
}
}
?>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading"><i class="fa fa-eye-slash fa-fw"></i> Configure TOR proxy</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading"><i class="fa fa-eye-slash fa-fw"></i> Configure TOR proxy</div>
<!-- /.panel-heading -->
<div class="panel-body">
<!-- Nav tabs -->
<!-- Nav tabs -->
<ul class="nav nav-tabs">
<li class="active"><a href="#basic" data-toggle="tab">Basic</a>
</li>
@ -361,140 +378,141 @@ function DisplayTorProxyConfig(){
</ul>
<!-- Tab panes -->
<div class="tab-content">
<p><?php echo $status; ?></p>
<div class="tab-content">
<p><?php echo $status; ?></p>
<div class="tab-pane fade in active" id="basic">
<h4>Basic settings</h4>
<form role="form" action="?page=save_hostapd_conf" method="POST">
<div class="row">
<div class="form-group col-md-4">
<label for="code">VirtualAddrNetwork</label>
<input type="text" class="form-control" name="virtualaddrnetwork" value="<?php echo htmlspecialchars($arrConfig['VirtualAddrNetwork'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">AutomapHostsSuffixes</label>
<input type="text" class="form-control" name="automaphostssuffixes" value="<?php echo htmlspecialchars($arrConfig['AutomapHostsSuffixes'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">AutomapHostsOnResolve</label>
<input type="text" class="form-control" name="automaphostsonresolve" value="<?php echo htmlspecialchars($arrConfig['AutomapHostsOnResolve'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">TransListenAddress</label>
<input type="text" class="form-control" name="translistenaddress" value="<?php echo htmlspecialchars($arrConfig['TransListenAddress'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">DNSPort</label>
<input type="text" class="form-control" name="dnsport" value="<?php echo htmlspecialchars($arrConfig['DNSPort'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">DNSListenAddress</label>
<input type="text" class="form-control" name="dnslistenaddress" value="<?php echo htmlspecialchars($arrConfig['DNSListenAddress'], ENT_QUOTES); ?>" />
</div>
</div>
</div>
<div class="tab-pane fade" id="relay">
<h4>Relay settings</h4>
<div class="row">
<div class="form-group col-md-4">
<label for="code">ORPort</label>
<input type="text" class="form-control" name="orport" value="<?php echo htmlspecialchars($arrConfig['ORPort'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">ORListenAddress</label>
<input type="text" class="form-control" name="orlistenaddress" value="<?php echo htmlspecialchars($arrConfig['ORListenAddress'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Nickname</label>
<input type="text" class="form-control" name="nickname" value="<?php echo htmlspecialchars($arrConfig['Nickname'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Address</label>
<input type="text" class="form-control" name="address" value="<?php echo htmlspecialchars($arrConfig['Address'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">RelayBandwidthRate</label>
<input type="text" class="form-control" name="relaybandwidthrate" value="<?php echo htmlspecialchars($arrConfig['RelayBandwidthRate'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">RelayBandwidthBurst</label>
<input type="text" class="form-control" name="relaybandwidthburst" value="<?php echo htmlspecialchars($arrConfig['RelayBandwidthBurst'], ENT_QUOTES); ?>" />
</div>
</div>
</div>
<div class="tab-pane fade in active" id="basic">
<h4>Basic settings</h4>
<form role="form" action="?page=save_hostapd_conf" method="POST">
<div class="row">
<div class="form-group col-md-4">
<label for="code">VirtualAddrNetwork</label>
<input type="text" class="form-control" name="virtualaddrnetwork" value="<?php echo htmlspecialchars($arrConfig['VirtualAddrNetwork'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">AutomapHostsSuffixes</label>
<input type="text" class="form-control" name="automaphostssuffixes" value="<?php echo htmlspecialchars($arrConfig['AutomapHostsSuffixes'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">AutomapHostsOnResolve</label>
<input type="text" class="form-control" name="automaphostsonresolve" value="<?php echo htmlspecialchars($arrConfig['AutomapHostsOnResolve'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">TransListenAddress</label>
<input type="text" class="form-control" name="translistenaddress" value="<?php echo htmlspecialchars($arrConfig['TransListenAddress'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">DNSPort</label>
<input type="text" class="form-control" name="dnsport" value="<?php echo htmlspecialchars($arrConfig['DNSPort'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">DNSListenAddress</label>
<input type="text" class="form-control" name="dnslistenaddress" value="<?php echo htmlspecialchars($arrConfig['DNSListenAddress'], ENT_QUOTES); ?>" />
</div>
</div>
</div>
<div class="tab-pane fade" id="relay">
<h4>Relay settings</h4>
<div class="row">
<div class="form-group col-md-4">
<label for="code">ORPort</label>
<input type="text" class="form-control" name="orport" value="<?php echo htmlspecialchars($arrConfig['ORPort'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">ORListenAddress</label>
<input type="text" class="form-control" name="orlistenaddress" value="<?php echo htmlspecialchars($arrConfig['ORListenAddress'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Nickname</label>
<input type="text" class="form-control" name="nickname" value="<?php echo htmlspecialchars($arrConfig['Nickname'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">Address</label>
<input type="text" class="form-control" name="address" value="<?php echo htmlspecialchars($arrConfig['Address'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">RelayBandwidthRate</label>
<input type="text" class="form-control" name="relaybandwidthrate" value="<?php echo htmlspecialchars($arrConfig['RelayBandwidthRate'], ENT_QUOTES); ?>" />
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="code">RelayBandwidthBurst</label>
<input type="text" class="form-control" name="relaybandwidthburst" value="<?php echo htmlspecialchars($arrConfig['RelayBandwidthBurst'], ENT_QUOTES); ?>" />
</div>
</div>
</div>
<input type="submit" class="btn btn-outline btn-primary" name="SaveTORProxySettings" value="Save settings" />
<?php
if( $torproxystatus[0] == 0 ) {
echo '<input type="submit" class="btn btn-success" name="StartTOR" value="Start TOR" />' , PHP_EOL;
} else {
echo '<input type="submit" class="btn btn-warning" name="StopTOR" value="Stop TOR" />' , PHP_EOL;
};
?>
</form>
</div><!-- /.tab-content -->
</div><!-- /.panel-body -->
<div class="panel-footer"> Information provided by tor</div>
<input type="submit" class="btn btn-outline btn-primary" name="SaveTORProxySettings" value="Save settings" />
<?php
if ($torproxystatus[0] == 0) {
echo '<input type="submit" class="btn btn-success" name="StartTOR" value="Start TOR" />' , PHP_EOL;
} else {
echo '<input type="submit" class="btn btn-warning" name="StopTOR" value="Stop TOR" />' , PHP_EOL;
};
?>
</form>
</div><!-- /.tab-content -->
</div><!-- /.panel-body -->
<div class="panel-footer"> Information provided by tor</div>
</div><!-- /.panel-primary -->
</div><!-- /.col-lg-12 -->
</div><!-- /.row -->
<?php
<?php
}
/**
*
*
*/
function SaveTORAndVPNConfig(){
if( isset($_POST['SaveOpenVPNSettings']) ) {
// TODO
} elseif( isset($_POST['SaveTORProxySettings']) ) {
// TODO
} elseif( isset($_POST['StartOpenVPN']) ) {
echo "Attempting to start openvpn";
exec( 'sudo /etc/init.d/openvpn start', $return );
foreach( $return as $line ) {
echo htmlspecialchars($line, ENT_QUOTES).'<br />' , PHP_EOL;
function SaveTORAndVPNConfig()
{
if (isset($_POST['SaveOpenVPNSettings'])) {
// TODO
} elseif (isset($_POST['SaveTORProxySettings'])) {
// TODO
} elseif (isset($_POST['StartOpenVPN'])) {
echo "Attempting to start openvpn";
exec('sudo /etc/init.d/openvpn start', $return);
foreach ($return as $line) {
echo htmlspecialchars($line, ENT_QUOTES).'<br />' , PHP_EOL;
}
} elseif (isset($_POST['StopOpenVPN'])) {
echo "Attempting to stop openvpn";
exec('sudo /etc/init.d/openvpn stop', $return);
foreach ($return as $line) {
echo htmlspecialchars($line, ENT_QUOTES).'<br />' , PHP_EOL;
}
} elseif (isset($_POST['StartTOR'])) {
echo "Attempting to start TOR";
exec('sudo /etc/init.d/tor start', $return);
foreach ($return as $line) {
echo htmlspecialchars($line, ENT_QUOTES).'<br />' , PHP_EOL;
}
} elseif (isset($_POST['StopTOR'])) {
echo "Attempting to stop TOR";
exec('sudo /etc/init.d/tor stop', $return);
foreach ($return as $line) {
echo htmlspecialchars($line, ENT_QUOTES).'<br />' , PHP_EOL;
}
}
} elseif( isset($_POST['StopOpenVPN']) ) {
echo "Attempting to stop openvpn";
exec( 'sudo /etc/init.d/openvpn stop', $return );
foreach( $return as $line ) {
echo htmlspecialchars($line, ENT_QUOTES).'<br />' , PHP_EOL;
}
} elseif( isset($_POST['StartTOR']) ) {
echo "Attempting to start TOR";
exec( 'sudo /etc/init.d/tor start', $return );
foreach( $return as $line ) {
echo htmlspecialchars($line, ENT_QUOTES).'<br />' , PHP_EOL;
}
} elseif( isset($_POST['StopTOR']) ) {
echo "Attempting to stop TOR";
exec( 'sudo /etc/init.d/tor stop', $return );
foreach( $return as $line ) {
echo htmlspecialchars($line, ENT_QUOTES).'<br />' , PHP_EOL;
}
}
}

View file

@ -1,6 +1,6 @@
<?php
include_once( 'includes/status_messages.php' );
include_once('includes/status_messages.php');
/**
*
@ -8,67 +8,65 @@ include_once( 'includes/status_messages.php' );
*/
function DisplayHostAPDConfig()
{
$status = new StatusMessages();
$status = new StatusMessages();
$arrHostapdConf = parse_ini_file('/etc/raspap/hostapd.ini');
$arrConfig = array();
$arr80211Standard = array('a','b','g','n');
$arrSecurity = array(1 => 'WPA', 2 => 'WPA2', 3 => 'WPA+WPA2', 'none' => _("None"));
$arrEncType = array('TKIP' => 'TKIP', 'CCMP' => 'CCMP', 'TKIP CCMP' => 'TKIP+CCMP');
exec("ip -o link show | awk -F': ' '{print $2}'", $interfaces);
$arrHostapdConf = parse_ini_file('/etc/raspap/hostapd.ini');
if (isset($_POST['SaveHostAPDSettings'])) {
if (CSRFValidate()) {
SaveHostAPDConfig($arrSecurity, $arrEncType, $arr80211Standard, $interfaces, $status);
} else {
error_log('CSRF violation');
}
} elseif (isset($_POST['StartHotspot'])) {
if (CSRFValidate()) {
$status->addMessage('Attempting to start hotspot', 'info');
if ($arrHostapdConf['WifiAPEnable'] == 1) {
exec('sudo /etc/raspap/hostapd/servicestart.sh --interface uap0 --seconds 5', $return);
} else {
exec('sudo /etc/raspap/hostapd/servicestart.sh --seconds 5', $return);
}
foreach ($return as $line) {
$status->addMessage($line, 'info');
}
} else {
error_log('CSRF violation');
}
} elseif (isset($_POST['StopHotspot'])) {
if (CSRFValidate()) {
$status->addMessage('Attempting to stop hotspot', 'info');
exec('sudo /etc/init.d/hostapd stop', $return);
foreach ($return as $line) {
$status->addMessage($line, 'info');
}
} else {
error_log('CSRF violation');
}
}
$arrConfig = array();
$arr80211Standard = array('a','b','g','n');
$arrSecurity = array(1 => 'WPA', 2 => 'WPA2', 3 => 'WPA+WPA2', 'none' => _("None"));
$arrEncType = array('TKIP' => 'TKIP', 'CCMP' => 'CCMP', 'TKIP CCMP' => 'TKIP+CCMP');
exec("ip -o link show | awk -F': ' '{print $2}'", $interfaces);
exec('cat '. RASPI_HOSTAPD_CONFIG, $hostapdconfig);
exec('pidof hostapd | wc -l', $hostapdstatus);
if( isset($_POST['SaveHostAPDSettings']) ) {
if (CSRFValidate()) {
SaveHostAPDConfig($arrSecurity, $arrEncType, $arr80211Standard, $interfaces, $status);
if ($hostapdstatus[0] == 0) {
$status->addMessage('HostAPD is not running', 'warning');
} else {
error_log('CSRF violation');
}
} elseif( isset($_POST['StartHotspot']) ) {
if (CSRFValidate()) {
$status->addMessage('Attempting to start hotspot', 'info');
if ($arrHostapdConf['WifiAPEnable'] == 1) {
exec('sudo /etc/raspap/hostapd/servicestart.sh --interface uap0 --seconds 5', $return );
} else {
exec( 'sudo /etc/raspap/hostapd/servicestart.sh --seconds 5', $return );
}
foreach( $return as $line ) {
$status->addMessage($line, 'info');
}
} else {
error_log('CSRF violation');
}
} elseif( isset($_POST['StopHotspot']) ) {
if (CSRFValidate()) {
$status->addMessage('Attempting to stop hotspot', 'info');
exec( 'sudo /etc/init.d/hostapd stop', $return );
foreach( $return as $line ) {
$status->addMessage($line, 'info');
}
} else {
error_log('CSRF violation');
}
}
exec( 'cat '. RASPI_HOSTAPD_CONFIG, $hostapdconfig );
exec( 'pidof hostapd | wc -l', $hostapdstatus);
if( $hostapdstatus[0] == 0 ) {
$status->addMessage('HostAPD is not running', 'warning');
} else {
$status->addMessage('HostAPD is running', 'success');
}
foreach( $hostapdconfig as $hostapdconfigline ) {
if (strlen($hostapdconfigline) === 0) {
continue;
$status->addMessage('HostAPD is running', 'success');
}
if ($hostapdconfigline[0] != "#" ) {
$arrLine = explode("=", $hostapdconfigline) ;
$arrConfig[$arrLine[0]]=$arrLine[1];
}
};
foreach ($hostapdconfig as $hostapdconfigline) {
if (strlen($hostapdconfigline) === 0) {
continue;
}
if ($hostapdconfigline[0] != "#") {
$arrLine = explode("=", $hostapdconfigline) ;
$arrConfig[$arrLine[0]]=$arrLine[1];
}
};
?>
<div class="row">
@ -77,7 +75,7 @@ function DisplayHostAPDConfig()
<div class="panel-heading"><i class="fa fa-dot-circle-o fa-fw"></i> <?php echo _("Configure hotspot"); ?></div>
<!-- /.panel-heading -->
<div class="panel-body">
<p><?php $status->showMessages(); ?></p>
<p><?php $status->showMessages(); ?></p>
<form role="form" action="?page=hostapd_conf" method="POST">
<!-- Nav tabs -->
<ul class="nav nav-tabs">
@ -111,38 +109,38 @@ function DisplayHostAPDConfig()
<div class="form-group col-md-4">
<label for="cbxhwmode"><?php echo _("Wireless Mode") ;?></label>
<?php
$selectedHwMode = $arrConfig['hw_mode'];
if (isset($arrConfig['ieee80211n'])) {
if (strval($arrConfig['ieee80211n']) === '1') {
$selectedHwMode = 'n';
}
}
$selectedHwMode = $arrConfig['hw_mode'];
if (isset($arrConfig['ieee80211n'])) {
if (strval($arrConfig['ieee80211n']) === '1') {
$selectedHwMode = 'n';
}
}
SelectorOptions('hw_mode', $arr80211Standard, $selectedHwMode, 'cbxhwmode'); ?>
SelectorOptions('hw_mode', $arr80211Standard, $selectedHwMode, 'cbxhwmode'); ?>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="cbxchannel"><?php echo _("Channel"); ?></label>
<?php
$selectablechannels = range(1, 13);
$countries_2_4Ghz_max11ch = array('AG', 'BS', 'BB', 'BZ', 'CR', 'CU', 'DM', 'DO', 'SV', 'GD', 'GT',
$selectablechannels = range(1, 13);
$countries_2_4Ghz_max11ch = array('AG', 'BS', 'BB', 'BZ', 'CR', 'CU', 'DM', 'DO', 'SV', 'GD', 'GT',
'HT', 'HN', 'JM', 'MX', 'NI', 'PA', 'KN', 'LC', 'VC', 'TT',
'US', 'CA', 'UZ', 'CO');
$countries_2_4Ghz_max14ch = array('JA');
if (in_array($arrConfig['country_code'], $countries_max11channels)) {
// In North America till channel 11 is the maximum allowed wi-fi 2.4Ghz channel.
// Except for the US that allows channel 12 & 13 in low power mode with additional restrictions.
// Canada that allows channel 12 in low power mode. Because it's unsure if low powered mode
// can be supported the channels are not selectable for those countries.
// source: https://en.wikipedia.org/wiki/List_of_WLAN_channels#Interference_concerns
// Also Uzbekistan and Colombia allow to select till channel 11 as maximum channel on the 2.4Ghz wi-fi band.
$selectablechannels = range(1, 11);
} elseif (in_array($arrConfig['country_code'], $countries_2_4Ghz_max14ch)) {
if ($arrConfig['hw_mode'] === 'b') {
$selectablechannels = range(1, 14);
}
}
$countries_2_4Ghz_max14ch = array('JA');
if (in_array($arrConfig['country_code'], $countries_max11channels)) {
// In North America till channel 11 is the maximum allowed wi-fi 2.4Ghz channel.
// Except for the US that allows channel 12 & 13 in low power mode with additional restrictions.
// Canada that allows channel 12 in low power mode. Because it's unsure if low powered mode
// can be supported the channels are not selectable for those countries.
// source: https://en.wikipedia.org/wiki/List_of_WLAN_channels#Interference_concerns
// Also Uzbekistan and Colombia allow to select till channel 11 as maximum channel on the 2.4Ghz wi-fi band.
$selectablechannels = range(1, 11);
} elseif (in_array($arrConfig['country_code'], $countries_2_4Ghz_max14ch)) {
if ($arrConfig['hw_mode'] === 'b') {
$selectablechannels = range(1, 14);
}
}
SelectorOptions('channel', $selectablechannels, intval($arrConfig['channel']), 'cbxchannel'); ?>
</div>
</div>
@ -169,61 +167,61 @@ if (in_array($arrConfig['country_code'], $countries_max11channels)) {
</div>
</div>
<div class="tab-pane fade" id="logoutput">
<h4><?php echo _("Logfile output"); ?></h4>
<h4><?php echo _("Logfile output"); ?></h4>
<div class="row">
<div class="form-group col-md-8">
<?php
if($arrHostapdConf['LogEnable'] == 1) {
$log = file_get_contents('/tmp/hostapd.log');
echo '<br /><textarea class="logoutput">'.htmlspecialchars($log, ENT_QUOTES).'</textarea>';
} else {
echo "<br />Logfile output not enabled";
}
?>
<?php
if ($arrHostapdConf['LogEnable'] == 1) {
$log = file_get_contents('/tmp/hostapd.log');
echo '<br /><textarea class="logoutput">'.htmlspecialchars($log, ENT_QUOTES).'</textarea>';
} else {
echo "<br />Logfile output not enabled";
}
?>
</div>
</div>
</div>
<div class="tab-pane fade" id="advanced">
<h4><?php echo _("Advanced settings"); ?></h4>
<h4><?php echo _("Advanced settings"); ?></h4>
<div class="row">
<div class="col-md-4">
<div class="checkbox">
<?php
<div class="checkbox">
<?php
$checkedWifiAPEnabled = '';
if ($arrHostapdConf['WifiAPEnable'] == 1) {
$checkedWifiAPEnabled = ' checked="checked"';
}
?>
<input id="chxwificlientap" name="wifiAPEnable" type="checkbox" class="form-check-input" data-toggle="toggle" data-on="Enabled" data-off="Disabled" data-width="100" value="1"<?php echo $checkedWifiAPEnabled; ?> />
<label class="form-check-label" for="chxwificlientap"><?php echo _("WiFi client AP mode"); ?></label>
<input id="chxwificlientap" name="wifiAPEnable" type="checkbox" class="form-check-input" data-toggle="toggle" data-on="Enabled" data-off="Disabled" data-width="100" value="1"<?php echo $checkedWifiAPEnabled; ?> />
<label class="form-check-label" for="chxwificlientap"><?php echo _("WiFi client AP mode"); ?></label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="checkbox">
<?php
$checkedLogEnabled = '';
<div class="checkbox">
<?php
$checkedLogEnabled = '';
if ($arrHostapdConf['LogEnable'] == 1) {
$checkedLogEnabled = ' checked="checked"';
}
?>
<input id="chxlogenable" name="logEnable" type="checkbox" class="form-check-input" data-toggle="toggle" data-on="Enabled" data-off="Disabled" data-width="100" value="1"<?php echo $checkedLogEnabled; ?> />
<label class="form-check-label" for="chxlogenable"><?php echo _("Logfile output"); ?></label>
<input id="chxlogenable" name="logEnable" type="checkbox" class="form-check-input" data-toggle="toggle" data-on="Enabled" data-off="Disabled" data-width="100" value="1"<?php echo $checkedLogEnabled; ?> />
<label class="form-check-label" for="chxlogenable"><?php echo _("Logfile output"); ?></label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="checkbox">
<div class="checkbox">
<?php
$checkedHiddenSSID = '';
$checkedHiddenSSID = '';
if ($arrConfig['ignore_broadcast_ssid'] == 1 || $arrConfig['ignore_broadcast_ssid'] == 2) {
$checkedHiddenSSID = ' checked="checked"';
}
?>
<input id="chxhiddenssid" name="hiddenSSID" type="checkbox" class="form-check-input" data-toggle="toggle" data-on="Enabled" data-off="Disabled" data-width="100" value="1"<?php echo $checkedHiddenSSID; ?> />
<label class="form-check-label" for="chxhiddenssid"><?php echo _("Hide SSID in broadcast"); ?></label>
<input id="chxhiddenssid" name="hiddenSSID" type="checkbox" class="form-check-input" data-toggle="toggle" data-on="Enabled" data-off="Disabled" data-width="100" value="1"<?php echo $checkedHiddenSSID; ?> />
<label class="form-check-label" for="chxhiddenssid"><?php echo _("Hide SSID in broadcast"); ?></label>
</div>
</div>
</div>
@ -487,10 +485,10 @@ var country = document.getElementById("selected_country").value;
var countries = document.getElementById("cbxcountries");
var ops = countries.getElementsByTagName("option");
for (var i = 0; i < ops.length; ++i) {
if(ops[i].value == country){
ops[i].selected=true;
break;
}
if(ops[i].value == country){
ops[i].selected=true;
break;
}
}
</script>
@ -499,203 +497,204 @@ for (var i = 0; i < ops.length; ++i) {
</div><!-- /.panel-primary -->
<input type="submit" class="btn btn-outline btn-primary" name="SaveHostAPDSettings" value="<?php echo _("Save settings"); ?>" />
<?php
if($hostapdstatus[0] == 0) {
if ($hostapdstatus[0] == 0) {
echo '<input type="submit" class="btn btn-success" name="StartHotspot" value="' . _("Start hotspot") . '"/>' , PHP_EOL;
} else {
} else {
echo '<input type="submit" class="btn btn-warning" name="StopHotspot" value="' . _("Stop hotspot") . '"/>' , PHP_EOL;
};
};
?>
</form>
</div></div><!-- /.panel-primary -->
<div class="panel-footer"> <?php echo _("Information provided by hostapd"); ?></div>
</div><!-- /.col-lg-12 -->
</div><!-- /.row -->
<?php
<?php
}
function SaveHostAPDConfig($wpa_array, $enc_types, $modes, $interfaces, $status) {
// It should not be possible to send bad data for these fields so clearly
// someone is up to something if they fail. Fail silently.
if (!(array_key_exists($_POST['wpa'], $wpa_array) &&
function SaveHostAPDConfig($wpa_array, $enc_types, $modes, $interfaces, $status)
{
// It should not be possible to send bad data for these fields so clearly
// someone is up to something if they fail. Fail silently.
if (!(array_key_exists($_POST['wpa'], $wpa_array) &&
array_key_exists($_POST['wpa_pairwise'], $enc_types) &&
in_array($_POST['hw_mode'], $modes))) {
error_log("Attempting to set hostapd config with wpa='".$_POST['wpa']."', wpa_pairwise='".$_POST['wpa_pairwise']."' and hw_mode='".$_POST['hw_mode']."'"); // FIXME: log injection
return false;
}
error_log("Attempting to set hostapd config with wpa='".$_POST['wpa']."', wpa_pairwise='".$_POST['wpa_pairwise']."' and hw_mode='".$_POST['hw_mode']."'"); // FIXME: log injection
return false;
}
if (!filter_var($_POST['channel'], FILTER_VALIDATE_INT)) {
error_log("Attempting to set channel to invalid number.");
return false;
}
if (!filter_var($_POST['channel'], FILTER_VALIDATE_INT)) {
error_log("Attempting to set channel to invalid number.");
return false;
}
if (intval($_POST['channel']) < 1 || intval($_POST['channel']) > 14) {
error_log("Attempting to set channel to '".$_POST['channel']."'");
return false;
}
if (intval($_POST['channel']) < 1 || intval($_POST['channel']) > 14) {
error_log("Attempting to set channel to '".$_POST['channel']."'");
return false;
}
$good_input = true;
$good_input = true;
// Check for WiFi client AP mode checkbox
$wifiAPEnable = 0;
if($arrHostapdConf['WifiAPEnable'] == 0) {
if(isset($_POST['wifiAPEnable'])) {
$wifiAPEnable = 1;
}
} else {
if(isset($_POST['wifiAPEnable'])) {
$wifiAPEnable = 1;
}
}
// Check for WiFi client AP mode checkbox
$wifiAPEnable = 0;
if ($arrHostapdConf['WifiAPEnable'] == 0) {
if (isset($_POST['wifiAPEnable'])) {
$wifiAPEnable = 1;
}
} else {
if (isset($_POST['wifiAPEnable'])) {
$wifiAPEnable = 1;
}
}
// Check for Logfile output checkbox
$logEnable = 0;
if($arrHostapdConf['LogEnable'] == 0) {
if(isset($_POST['logEnable'])) {
$logEnable = 1;
exec('sudo /etc/raspap/hostapd/enablelog.sh');
} else {
exec('sudo /etc/raspap/hostapd/disablelog.sh');
}
} else {
if(isset($_POST['logEnable'])) {
$logEnable = 1;
exec('sudo /etc/raspap/hostapd/enablelog.sh');
} else {
exec('sudo /etc/raspap/hostapd/disablelog.sh');
}
}
$cfg = [];
$cfg['LogEnable'] = $logEnable;
$cfg['WifiAPEnable'] = $wifiAPEnable;
write_php_ini($cfg,'/etc/raspap/hostapd.ini');
// Check for Logfile output checkbox
$logEnable = 0;
if ($arrHostapdConf['LogEnable'] == 0) {
if (isset($_POST['logEnable'])) {
$logEnable = 1;
exec('sudo /etc/raspap/hostapd/enablelog.sh');
} else {
exec('sudo /etc/raspap/hostapd/disablelog.sh');
}
} else {
if (isset($_POST['logEnable'])) {
$logEnable = 1;
exec('sudo /etc/raspap/hostapd/enablelog.sh');
} else {
exec('sudo /etc/raspap/hostapd/disablelog.sh');
}
}
$cfg = [];
$cfg['LogEnable'] = $logEnable;
$cfg['WifiAPEnable'] = $wifiAPEnable;
write_php_ini($cfg, '/etc/raspap/hostapd.ini');
// Verify input
if (empty($_POST['ssid']) || strlen($_POST['ssid']) > 32) {
// Not sure of all the restrictions of SSID
$status->addMessage('SSID must be between 1 and 32 characters', 'danger');
$good_input = false;
}
// Verify input
if (empty($_POST['ssid']) || strlen($_POST['ssid']) > 32) {
// Not sure of all the restrictions of SSID
$status->addMessage('SSID must be between 1 and 32 characters', 'danger');
$good_input = false;
}
if ($_POST['wpa'] !== 'none' &&
if ($_POST['wpa'] !== 'none' &&
(strlen($_POST['wpa_passphrase']) < 8 || strlen($_POST['wpa_passphrase']) > 63)) {
$status->addMessage('WPA passphrase must be between 8 and 63 characters', 'danger');
$good_input = false;
}
$status->addMessage('WPA passphrase must be between 8 and 63 characters', 'danger');
$good_input = false;
}
if (isset($_POST['hiddenSSID'])) {
if (!is_int((int)$_POST['hiddenSSID'])) {
$status->addMessage('Parameter hiddenSSID not a number.', 'danger');
$good_input = false;
} elseif ((int)$_POST['hiddenSSID'] < 0 || (int)$_POST['hiddenSSID'] >= 3) {
$status->addMessage('Parameter hiddenSSID contains invalid configuratie value.', 'danger');
$good_input = false;
if (isset($_POST['hiddenSSID'])) {
if (!is_int((int)$_POST['hiddenSSID'])) {
$status->addMessage('Parameter hiddenSSID not a number.', 'danger');
$good_input = false;
} elseif ((int)$_POST['hiddenSSID'] < 0 || (int)$_POST['hiddenSSID'] >= 3) {
$status->addMessage('Parameter hiddenSSID contains invalid configuratie value.', 'danger');
$good_input = false;
} else {
$ignore_broadcast_ssid = $_POST['hiddenSSID'];
}
} else {
$ignore_broadcast_ssid = $_POST['hiddenSSID'];
$ignore_broadcast_ssid = '0';
}
} else {
$ignore_broadcast_ssid = '0';
}
if (! in_array($_POST['interface'], $interfaces)) {
// The user is probably up to something here but it may also be a
// genuine error.
$status->addMessage('Unknown interface '.htmlspecialchars($_POST['interface'], ENT_QUOTES), 'danger');
$good_input = false;
}
if (! in_array($_POST['interface'], $interfaces)) {
// The user is probably up to something here but it may also be a
// genuine error.
$status->addMessage('Unknown interface '.htmlspecialchars($_POST['interface'], ENT_QUOTES), 'danger');
$good_input = false;
}
if (strlen($_POST['country_code']) !== 0 && strlen($_POST['country_code']) != 2) {
$status->addMessage('Country code must be blank or two characters', 'danger');
$good_input = false;
}
if (strlen($_POST['country_code']) !== 0 && strlen($_POST['country_code']) != 2) {
$status->addMessage('Country code must be blank or two characters', 'danger');
$good_input = false;
}
if ($good_input) {
// Fixed values
$config = 'driver=nl80211'.PHP_EOL;
$config.= 'ctrl_interface='.RASPI_HOSTAPD_CTRL_INTERFACE.PHP_EOL;
$config.= 'ctrl_interface_group=0'.PHP_EOL;
$config.= 'auth_algs=1'.PHP_EOL;
$config.= 'wpa_key_mgmt=WPA-PSK'.PHP_EOL;
$config.= 'beacon_int=100'.PHP_EOL;
$config.= 'ssid='.$_POST['ssid'].PHP_EOL;
$config.= 'channel='.$_POST['channel'].PHP_EOL;
if ($_POST['hw_mode'] === 'n') {
$config.= 'hw_mode=g'.PHP_EOL;
$config.= 'ieee80211n=1'.PHP_EOL;
// Enable basic Quality of service
$config.= 'wme_enabled=1'.PHP_EOL;
if ($good_input) {
// Fixed values
$config = 'driver=nl80211'.PHP_EOL;
$config.= 'ctrl_interface='.RASPI_HOSTAPD_CTRL_INTERFACE.PHP_EOL;
$config.= 'ctrl_interface_group=0'.PHP_EOL;
$config.= 'auth_algs=1'.PHP_EOL;
$config.= 'wpa_key_mgmt=WPA-PSK'.PHP_EOL;
$config.= 'beacon_int=100'.PHP_EOL;
$config.= 'ssid='.$_POST['ssid'].PHP_EOL;
$config.= 'channel='.$_POST['channel'].PHP_EOL;
if ($_POST['hw_mode'] === 'n') {
$config.= 'hw_mode=g'.PHP_EOL;
$config.= 'ieee80211n=1'.PHP_EOL;
// Enable basic Quality of service
$config.= 'wme_enabled=1'.PHP_EOL;
} else {
$config.= 'hw_mode='.$_POST['hw_mode'].PHP_EOL;
$config.= 'ieee80211n=0'.PHP_EOL;
}
$config.= 'wpa_passphrase='.$_POST['wpa_passphrase'].PHP_EOL;
if ($wifiAPEnable == 1) {
$config.= 'interface=uap0'.PHP_EOL;
} else {
$config.= 'interface='.$_POST['interface'].PHP_EOL;
}
$config.= 'wpa='.$_POST['wpa'].PHP_EOL;
$config.= 'wpa_pairwise='.$_POST['wpa_pairwise'].PHP_EOL;
$config.= 'country_code='.$_POST['country_code'].PHP_EOL;
$config.= 'ignore_broadcast_ssid='.$ignore_broadcast_ssid.PHP_EOL;
exec('echo "'.$config.'" > /tmp/hostapddata', $temp);
system("sudo cp /tmp/hostapddata " . RASPI_HOSTAPD_CONFIG, $return);
if ($wifiAPEnable == 1) {
// Enable uap0 configuration in dnsmasq for Wifi client AP mode
$config = 'interface=lo,uap0 # Enable uap0 interface for wireless client AP mode'.PHP_EOL;
$config.= 'bind-interfaces # Bind to the interfaces'.PHP_EOL;
$config.= 'server=8.8.8.8 # Forward DNS requests to Google DNS'.PHP_EOL;
$config.= 'domain-needed # Don\'t forward short names'.PHP_EOL;
$config.= 'bogus-priv # Never forward addresses in the non-routed address spaces'.PHP_EOL;
$config.= 'dhcp-range=192.168.50.50,192.168.50.150,12h'.PHP_EOL;
} else {
// Fallback to default config
$config = 'domain-needed'.PHP_EOL;
$config.= 'interface='.$_POST['interface'].PHP_EOL;
$config.= 'dhcp-range=10.3.141.50,10.3.141.255,255.255.255.0,12h'.PHP_EOL;
}
exec('echo "'.$config.'" > /tmp/dhcpddata', $temp);
system('sudo cp /tmp/dhcpddata '.RASPI_DNSMASQ_CONFIG, $return);
if ($wifiAPEnable == 1) {
// Enable uap0 configuration in dhcpcd for Wifi client AP mode
$config = PHP_EOL.'# RaspAP uap0 configuration'.PHP_EOL;
$config.= 'interface uap0'.PHP_EOL;
$config.= 'static ip_address=192.168.50.1/24'.PHP_EOL;
$config.= 'nohook wpa_supplicant'.PHP_EOL;
} else {
// Default config
$config = '# RaspAP wlan0 configuration'.PHP_EOL;
$config.= 'hostname'.PHP_EOL;
$config.= 'clientid'.PHP_EOL;
$config.= 'persistent'.PHP_EOL;
$config.= 'option rapid_commit'.PHP_EOL;
$config.= 'option domain_name_servers, domain_name, domain_search, host_name'.PHP_EOL;
$config.= 'option classless_static_routes'.PHP_EOL;
$config.= 'option ntp_servers'.PHP_EOL;
$config.= 'require dhcp_server_identifier'.PHP_EOL;
$config.= 'slaac private'.PHP_EOL;
$config.= 'nohook lookup-hostname'.PHP_EOL;
$config.= 'interface '.RASPI_WIFI_CLIENT_INTERFACE.PHP_EOL;
$config.= 'static ip_address=10.3.141.1/24'.PHP_EOL;
$config.= 'static routers=10.3.141.1'.PHP_EOL;
$config.= 'static domain_name_server=1.1.1.1 8.8.8.8'.PHP_EOL;
}
exec('echo "'.$config.'" > /tmp/dhcpddata', $temp);
system('sudo cp /tmp/dhcpddata '.RASPI_DHCPCD_CONFIG, $return);
if ($return == 0) {
$status->addMessage('Wifi Hotspot settings saved', 'success');
} else {
$status->addMessage('Unable to save wifi hotspot settings', 'danger');
}
} else {
$config.= 'hw_mode='.$_POST['hw_mode'].PHP_EOL;
$config.= 'ieee80211n=0'.PHP_EOL;
$status->addMessage('Unable to save wifi hotspot settings', 'danger');
return false;
}
$config.= 'wpa_passphrase='.$_POST['wpa_passphrase'].PHP_EOL;
if ($wifiAPEnable == 1) {
$config.= 'interface=uap0'.PHP_EOL;
} else {
$config.= 'interface='.$_POST['interface'].PHP_EOL;
}
$config.= 'wpa='.$_POST['wpa'].PHP_EOL;
$config.= 'wpa_pairwise='.$_POST['wpa_pairwise'].PHP_EOL;
$config.= 'country_code='.$_POST['country_code'].PHP_EOL;
$config.= 'ignore_broadcast_ssid='.$ignore_broadcast_ssid.PHP_EOL;
exec('echo "'.$config.'" > /tmp/hostapddata', $temp);
system( "sudo cp /tmp/hostapddata " . RASPI_HOSTAPD_CONFIG, $return );
if ($wifiAPEnable == 1) {
// Enable uap0 configuration in dnsmasq for Wifi client AP mode
$config = 'interface=lo,uap0 # Enable uap0 interface for wireless client AP mode'.PHP_EOL;
$config.= 'bind-interfaces # Bind to the interfaces'.PHP_EOL;
$config.= 'server=8.8.8.8 # Forward DNS requests to Google DNS'.PHP_EOL;
$config.= 'domain-needed # Don\'t forward short names'.PHP_EOL;
$config.= 'bogus-priv # Never forward addresses in the non-routed address spaces'.PHP_EOL;
$config.= 'dhcp-range=192.168.50.50,192.168.50.150,12h'.PHP_EOL;
} else {
// Fallback to default config
$config = 'domain-needed'.PHP_EOL;
$config.= 'interface='.$_POST['interface'].PHP_EOL;
$config.= 'dhcp-range=10.3.141.50,10.3.141.255,255.255.255.0,12h'.PHP_EOL;
}
exec('echo "'.$config.'" > /tmp/dhcpddata', $temp);
system('sudo cp /tmp/dhcpddata '.RASPI_DNSMASQ_CONFIG, $return);
if ($wifiAPEnable == 1) {
// Enable uap0 configuration in dhcpcd for Wifi client AP mode
$config = PHP_EOL.'# RaspAP uap0 configuration'.PHP_EOL;
$config.= 'interface uap0'.PHP_EOL;
$config.= 'static ip_address=192.168.50.1/24'.PHP_EOL;
$config.= 'nohook wpa_supplicant'.PHP_EOL;
} else {
// Default config
$config = '# RaspAP wlan0 configuration'.PHP_EOL;
$config.= 'hostname'.PHP_EOL;
$config.= 'clientid'.PHP_EOL;
$config.= 'persistent'.PHP_EOL;
$config.= 'option rapid_commit'.PHP_EOL;
$config.= 'option domain_name_servers, domain_name, domain_search, host_name'.PHP_EOL;
$config.= 'option classless_static_routes'.PHP_EOL;
$config.= 'option ntp_servers'.PHP_EOL;
$config.= 'require dhcp_server_identifier'.PHP_EOL;
$config.= 'slaac private'.PHP_EOL;
$config.= 'nohook lookup-hostname'.PHP_EOL;
$config.= 'interface '.RASPI_WIFI_CLIENT_INTERFACE.PHP_EOL;
$config.= 'static ip_address=10.3.141.1/24'.PHP_EOL;
$config.= 'static routers=10.3.141.1'.PHP_EOL;
$config.= 'static domain_name_server=1.1.1.1 8.8.8.8'.PHP_EOL;
}
exec('echo "'.$config.'" > /tmp/dhcpddata', $temp);
system('sudo cp /tmp/dhcpddata '.RASPI_DHCPCD_CONFIG, $return);
if( $return == 0 ) {
$status->addMessage('Wifi Hotspot settings saved', 'success');
} else {
$status->addMessage('Unable to save wifi hotspot settings', 'danger');
}
} else {
$status->addMessage('Unable to save wifi hotspot settings', 'danger');
return false;
}
return true;
return true;
}

View file

@ -1,64 +1,62 @@
<?php
/**
* Sets locale information for i18n support
*
*/
/**
/**
* Rudimentary language detection via the browser.
* Accept-Language returns a list of weighted values with a quality (or 'q') parameter.
* A better method would parse the list of preferred languages and match this with
* A better method would parse the list of preferred languages and match this with
* the languages supported by our platform.
*
* Refer to: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
*/
if (empty($_SESSION['locale']) && strlen($_SERVER['HTTP_ACCEPT_LANGUAGE']) >= 2) {
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
case "de":
$locale = "de_DE.UTF-8";
break;
case "fr":
$locale = "fr_FR.UTF-8";
break;
case "it":
$locale = "it_IT.UTF-8";
break;
case "pt":
$locale = "pt_BR.UTF-8";
break;
case "sv":
$locale = "sv_SE.UTF-8";
break;
case "nl":
$locale = "nl_NL.UTF-8";
break;
case "zh":
$locale = "zh_CN.UTF-8";
break;
case "cs":
$locale = "cs_CZ.UTF-8";
break;
case "ru":
$locale = "ru_RU.UTF-8";
break;
case "es":
$locale = "es_MX.UTF-8";
break;
case "fi":
$locale = "fi_FI.UTF-8";
break;
case "si":
$locale = "si_LK.UTF-8";
break;
default:
$locale = "en_GB.UTF-8";
break;
}
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang) {
case "de":
$locale = "de_DE.UTF-8";
break;
case "fr":
$locale = "fr_FR.UTF-8";
break;
case "it":
$locale = "it_IT.UTF-8";
break;
case "pt":
$locale = "pt_BR.UTF-8";
break;
case "sv":
$locale = "sv_SE.UTF-8";
break;
case "nl":
$locale = "nl_NL.UTF-8";
break;
case "zh":
$locale = "zh_CN.UTF-8";
break;
case "cs":
$locale = "cs_CZ.UTF-8";
break;
case "ru":
$locale = "ru_RU.UTF-8";
break;
case "es":
$locale = "es_MX.UTF-8";
break;
case "fi":
$locale = "fi_FI.UTF-8";
break;
case "si":
$locale = "si_LK.UTF-8";
break;
default:
$locale = "en_GB.UTF-8";
break;
}
$_SESSION['locale'] = $locale;
$_SESSION['locale'] = $locale;
}
// Note: the associated locale must be installed on the RPi
@ -72,4 +70,3 @@ bindtextdomain(LOCALE_DOMAIN, LOCALE_ROOT);
bind_textdomain_codeset(LOCALE_DOMAIN, 'UTF-8');
textdomain(LOCALE_DOMAIN);

View file

@ -1,63 +1,64 @@
<?php
include_once( 'includes/status_messages.php' );
include_once('includes/status_messages.php');
/**
*
*
*/
function DisplayNetworkingConfig(){
function DisplayNetworkingConfig()
{
$status = new StatusMessages();
$status = new StatusMessages();
exec("ls /sys/class/net | grep -v lo", $interfaces);
exec("ls /sys/class/net | grep -v lo", $interfaces);
foreach($interfaces as $interface) {
exec("ip a show $interface",$$interface);
}
foreach ($interfaces as $interface) {
exec("ip a show $interface", $$interface);
}
CSRFToken();
CSRFToken();
?>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel panel-heading">
<i class="fa fa-sitemap fa-fw"></i> <?php echo _("Configure networking"); ?></div>
<i class="fa fa-sitemap fa-fw"></i> <?php echo _("Configure networking"); ?></div>
<div class="panel-body">
<div id="msgNetworking"></div>
<ul class="nav nav-tabs">
<li role="presentation" class="active"><a href="#summary" aria-controls="summary" role="tab" data-toggle="tab"><?php echo _("Summary"); ?></a></li>
<li role="presentation" class="active"><a href="#summary" aria-controls="summary" role="tab" data-toggle="tab"><?php echo _("Summary"); ?></a></li>
<?php
foreach($interfaces as $interface) {
echo '<li role="presentation"><a href="#'.htmlspecialchars($interface, ENT_QUOTES).'" aria-controls="'.htmlspecialchars($interface, ENT_QUOTES).'" role="tab" data-toggle="tab">'.htmlspecialchars($interface, ENT_QUOTES).'</a></li>';
}
foreach ($interfaces as $interface) {
echo '<li role="presentation"><a href="#'.htmlspecialchars($interface, ENT_QUOTES).'" aria-controls="'.htmlspecialchars($interface, ENT_QUOTES).'" role="tab" data-toggle="tab">'.htmlspecialchars($interface, ENT_QUOTES).'</a></li>';
}
?>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="summary">
<h4><?php echo _("Current settings"); ?></h4>
<h4><?php echo _("Current settings"); ?></h4>
<div class="row">
<?php
foreach($interfaces as $interface) {
echo '<div class="col-md-6">
<?php
foreach ($interfaces as $interface) {
echo '<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">'.htmlspecialchars($interface, ENT_QUOTES).'</div>
<div class="panel-body" id="'.htmlspecialchars($interface, ENT_QUOTES).'-summary"></div>
</div>
</div>';
}
?>
?>
</div><!-- /.row -->
<div class="col-lg-12">
<div class="row">
<a href="#" class="btn btn-outline btn-primary" id="btnSummaryRefresh"><i class="fa fa-refresh"></i> <?php echo _("Refresh"); ?></a>
<a href="#" class="btn btn-outline btn-primary" id="btnSummaryRefresh"><i class="fa fa-refresh"></i> <?php echo _("Refresh"); ?></a>
</div><!-- /.row -->
</div><!-- /.col-lg-12 -->
</div><!-- /.tab-pane -->
<?php
foreach($interfaces as $interface) {
echo '
foreach ($interfaces as $interface) {
echo '
<div role="tabpanel" class="tab-pane fade in" id="'.htmlspecialchars($interface, ENT_QUOTES).'">
<div class="row">
<div class="col-lg-6">
@ -110,11 +111,11 @@ function DisplayNetworkingConfig(){
</div>
</div><!-- /.tab-panel -->
</div>';
}
}
?>
</div><!-- /.tab-content -->
</div><!-- /.panel-body -->
<div class="panel-footer"><?php echo _("Information provided by /sys/class/net"); ?></div>
<div class="panel-footer"><?php echo _("Information provided by /sys/class/net"); ?></div>
</div><!-- /.panel-primary -->
</div><!-- /.col-lg-12 -->
</div>

View file

@ -1,22 +1,30 @@
<?php
class StatusMessages {
public $messages = array();
class StatusMessages
{
public $messages = array();
public function addMessage($message, $level='success', $dismissable=true) {
$status = '<div class="alert alert-'.$level;
if ($dismissable) $status .= ' alert-dismissable';
$status .= '">'. _($message);
if ($dismissable) $status .= '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>';
$status .= '</div>';
public function addMessage($message, $level = 'success', $dismissable = true)
{
$status = '<div class="alert alert-'.$level;
if ($dismissable) {
$status .= ' alert-dismissable';
}
$status .= '">'. _($message);
if ($dismissable) {
$status .= '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>';
}
$status .= '</div>';
array_push($this->messages, $status);
}
public function showMessages($clear = true) {
foreach($this->messages as $message) {
echo $message;
array_push($this->messages, $status);
}
public function showMessages($clear = true)
{
foreach ($this->messages as $message) {
echo $message;
}
if ($clear) {
$this->messages = array();
}
}
if ( $clear ) $this->messages = array();
}
}
?>

View file

@ -1,6 +1,6 @@
<?php
include_once( 'includes/status_messages.php' );
include_once('includes/status_messages.php');
/**
*
@ -9,9 +9,10 @@ include_once( 'includes/status_messages.php' );
*
*/
function RPiVersion() {
// Lookup table from http://www.raspberrypi-spy.co.uk/2012/09/checking-your-raspberry-pi-board-version/
$revisions = array(
function RPiVersion()
{
// Lookup table from http://www.raspberrypi-spy.co.uk/2012/09/checking-your-raspberry-pi-board-version/
$revisions = array(
'0002' => 'Model B Revision 1.0',
'0003' => 'Model B Revision 1.0 + ECN0001',
'0004' => 'Model B Revision 2.0 (256 MB)',
@ -40,39 +41,40 @@ function RPiVersion() {
'a220a0' => 'Compute Module 3',
'a020a0' => 'Compute Module 3',
'a02100' => 'Compute Module 3+',
);
);
$cpuinfo_array = '';
exec('cat /proc/cpuinfo', $cpuinfo_array);
$rev = trim(array_pop(explode(':',array_pop(preg_grep("/^Revision/", $cpuinfo_array)))));
if (array_key_exists($rev, $revisions)) {
return $revisions[$rev];
} else {
return 'Unknown Pi';
}
$cpuinfo_array = '';
exec('cat /proc/cpuinfo', $cpuinfo_array);
$rev = trim(array_pop(explode(':', array_pop(preg_grep("/^Revision/", $cpuinfo_array)))));
if (array_key_exists($rev, $revisions)) {
return $revisions[$rev];
} else {
return 'Unknown Pi';
}
}
/**
*
*
*/
function DisplaySystem(){
function DisplaySystem()
{
$status = new StatusMessages();
$status = new StatusMessages();
if( isset($_POST['SaveLanguage']) ) {
if (CSRFValidate()) {
if(isset($_POST['locale'])) {
$_SESSION['locale'] = $_POST['locale'];
$status->addMessage('Language setting saved', 'success');
}
} else {
error_log('CSRF violation');
if (isset($_POST['SaveLanguage'])) {
if (CSRFValidate()) {
if (isset($_POST['locale'])) {
$_SESSION['locale'] = $_POST['locale'];
$status->addMessage('Language setting saved', 'success');
}
} else {
error_log('CSRF violation');
}
}
}
// define locales
$arrLocales = array(
// define locales
$arrLocales = array(
'en_GB.UTF-8' => 'English',
'de_DE.UTF-8' => 'Deutsch',
'fr_FR.UTF-8' => 'Français',
@ -86,40 +88,54 @@ function DisplaySystem(){
'es_MX.UTF-8' => 'Español',
'fi_FI.UTF-8' => 'Finnish',
'si_LK.UTF-8' => 'Sinhala'
);
);
// hostname
exec("hostname -f", $hostarray);
$hostname = $hostarray[0];
// hostname
exec("hostname -f", $hostarray);
$hostname = $hostarray[0];
// uptime
$uparray = explode(" ", exec("cat /proc/uptime"));
$seconds = round($uparray[0], 0);
$minutes = $seconds / 60;
$hours = $minutes / 60;
$days = floor($hours / 24);
$hours = floor($hours - ($days * 24));
$minutes = floor($minutes - ($days * 24 * 60) - ($hours * 60));
$uptime= '';
if ($days != 0) { $uptime .= $days . ' day' . (($days > 1)? 's ':' '); }
if ($hours != 0) { $uptime .= $hours . ' hour' . (($hours > 1)? 's ':' '); }
if ($minutes != 0) { $uptime .= $minutes . ' minute' . (($minutes > 1)? 's ':' '); }
// uptime
$uparray = explode(" ", exec("cat /proc/uptime"));
$seconds = round($uparray[0], 0);
$minutes = $seconds / 60;
$hours = $minutes / 60;
$days = floor($hours / 24);
$hours = floor($hours - ($days * 24));
$minutes = floor($minutes - ($days * 24 * 60) - ($hours * 60));
$uptime= '';
if ($days != 0) {
$uptime .= $days . ' day' . (($days > 1)? 's ':' ');
}
if ($hours != 0) {
$uptime .= $hours . ' hour' . (($hours > 1)? 's ':' ');
}
if ($minutes != 0) {
$uptime .= $minutes . ' minute' . (($minutes > 1)? 's ':' ');
}
// mem used
$memused_status = "primary";
exec("free -m | awk '/Mem:/ { total=$2 ; used=$3 } END { print used/total*100}'", $memarray);
$memused = floor($memarray[0]);
if ($memused > 90) { $memused_status = "danger"; }
elseif ($memused > 75) { $memused_status = "warning"; }
elseif ($memused > 0) { $memused_status = "success"; }
// mem used
$memused_status = "primary";
exec("free -m | awk '/Mem:/ { total=$2 ; used=$3 } END { print used/total*100}'", $memarray);
$memused = floor($memarray[0]);
if ($memused > 90) {
$memused_status = "danger";
} elseif ($memused > 75) {
$memused_status = "warning";
} elseif ($memused > 0) {
$memused_status = "success";
}
// cpu load
$cores = exec("grep -c ^processor /proc/cpuinfo");
$loadavg = exec("awk '{print $1}' /proc/loadavg");
$cpuload = floor(($loadavg * 100) / $cores);
if ($cpuload > 90) { $cpuload_status = "danger"; }
elseif ($cpuload > 75) { $cpuload_status = "warning"; }
elseif ($cpuload > 0) { $cpuload_status = "success"; }
// cpu load
$cores = exec("grep -c ^processor /proc/cpuinfo");
$loadavg = exec("awk '{print $1}' /proc/loadavg");
$cpuload = floor(($loadavg * 100) / $cores);
if ($cpuload > 90) {
$cpuload_status = "danger";
} elseif ($cpuload > 75) {
$cpuload_status = "warning";
} elseif ($cpuload > 0) {
$cpuload_status = "success";
}
?>
<div class="row">
@ -129,14 +145,14 @@ function DisplaySystem(){
<div class="panel-body">
<?php
if (isset($_POST['system_reboot'])) {
if (isset($_POST['system_reboot'])) {
echo '<div class="alert alert-warning">' . _("System Rebooting Now!") . '</div>';
$result = shell_exec("sudo /sbin/reboot");
}
if (isset($_POST['system_shutdown'])) {
}
if (isset($_POST['system_shutdown'])) {
echo '<div class="alert alert-warning">' . _("System Shutting Down Now!") . '</div>';
$result = shell_exec("sudo /sbin/shutdown -h now");
}
}
?>
<div class="row">
@ -187,7 +203,7 @@ function DisplaySystem(){
<div role="tabpanel" class="tab-pane" id="language">
<h4><?php echo _("Language settings") ;?></h4>
<?php CSRFToken() ?>
<?php CSRFToken() ?>
<div class="row">
<div class="form-group col-md-4">
<label for="code"><?php echo _("Select a language"); ?></label>

View file

@ -3,25 +3,26 @@
*
*
*/
function DisplayThemeConfig(){
function DisplayThemeConfig()
{
$cselected = '';
$hselected = '';
$tselected = '';
$cselected = '';
$hselected = '';
$tselected = '';
switch( $_COOKIE['theme'] ) {
case "custom.css":
$cselected = ' selected="selected"';
break;
case "hackernews.css":
$hselected = ' selected="selected"';
break;
case "terminal.css":
$tselected = ' selected="selected"';
break;
}
switch ($_COOKIE['theme']) {
case "custom.css":
$cselected = ' selected="selected"';
break;
case "hackernews.css":
$hselected = ' selected="selected"';
break;
case "terminal.css":
$tselected = ' selected="selected"';
break;
}
?>
?>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
@ -57,6 +58,6 @@ function DisplayThemeConfig(){
</div><!-- /.panel-primary -->
</div><!-- /.col-lg-12 -->
</div><!-- /.row -->
<?php
<?php
}

164
index.php
View file

@ -9,7 +9,7 @@
* lighttpd (I have version 1.4.31-2 installed via apt)
* php5-cgi (I have version 5.4.4-12 installed via apt)
* along with their supporting packages, php5 will also need to be enabled.
*
*
* @author Lawrence Yau <sirlagz@gmail.com>
* @author Bill Zimmerman <billzimmerman@gmail.com>
* @license GNU General Public License, version 3 (GPL-3.0)
@ -20,21 +20,21 @@
session_start();
include_once( 'includes/config.php' );
include_once( RASPI_CONFIG.'/raspap.php' );
include_once( 'includes/locale.php');
include_once( 'includes/functions.php' );
include_once( 'includes/dashboard.php' );
include_once( 'includes/authenticate.php' );
include_once( 'includes/admin.php' );
include_once( 'includes/dhcp.php' );
include_once( 'includes/hostapd.php' );
include_once( 'includes/system.php' );
include_once( 'includes/configure_client.php' );
include_once( 'includes/networking.php' );
include_once( 'includes/themes.php' );
include_once( 'includes/data_usage.php' );
include_once( 'includes/about.php' );
include_once('includes/config.php');
include_once(RASPI_CONFIG.'/raspap.php');
include_once('includes/locale.php');
include_once('includes/functions.php');
include_once('includes/dashboard.php');
include_once('includes/authenticate.php');
include_once('includes/admin.php');
include_once('includes/dhcp.php');
include_once('includes/hostapd.php');
include_once('includes/system.php');
include_once('includes/configure_client.php');
include_once('includes/networking.php');
include_once('includes/themes.php');
include_once('includes/data_usage.php');
include_once('includes/about.php');
$output = $return = 0;
$page = $_GET['page'];
@ -48,7 +48,7 @@ if (empty($_SESSION['csrf_token'])) {
}
$csrf_token = $_SESSION['csrf_token'];
if(!isset($_COOKIE['theme'])) {
if (!isset($_COOKIE['theme'])) {
$theme = "custom.css";
} else {
$theme = $_COOKIE['theme'];
@ -111,7 +111,7 @@ $theme_url = 'dist/css/'.htmlspecialchars($theme, ENT_QUOTES);
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php"><?php echo _("RaspAP Wifi Portal"); ?> v<?php echo RASPI_VERSION; ?></a>
<a class="navbar-brand" href="index.php"><?php echo _("RaspAP Wifi Portal"); ?> v<?php echo RASPI_VERSION; ?></a>
</div>
<!-- /.navbar-header -->
@ -122,51 +122,51 @@ $theme_url = 'dist/css/'.htmlspecialchars($theme, ENT_QUOTES);
<li>
<a href="index.php?page=wlan0_info"><i class="fa fa-dashboard fa-fw"></i> <?php echo _("Dashboard"); ?></a>
</li>
<?php if ( RASPI_WIFICLIENT_ENABLED ) : ?>
<?php if (RASPI_WIFICLIENT_ENABLED) : ?>
<li>
<a href="index.php?page=wpa_conf"><i class="fa fa-wifi fa-fw"></i> <?php echo _("Configure WiFi client"); ?></a>
</li>
<?php endif; ?>
<?php if ( RASPI_HOTSPOT_ENABLED ) : ?>
</li>
<?php endif; ?>
<?php if (RASPI_HOTSPOT_ENABLED) : ?>
<li>
<a href="index.php?page=hostapd_conf"><i class="fa fa-dot-circle-o fa-fw"></i> <?php echo _("Configure hotspot"); ?></a>
</li>
<?php endif; ?>
<?php if ( RASPI_NETWORK_ENABLED ) : ?>
<?php endif; ?>
<?php if (RASPI_NETWORK_ENABLED) : ?>
<li>
<a href="index.php?page=network_conf"><i class="fa fa-sitemap fa-fw"></i> <?php echo _("Configure networking"); ?></a>
<a href="index.php?page=network_conf"><i class="fa fa-sitemap fa-fw"></i> <?php echo _("Configure networking"); ?></a>
</li>
<?php endif; ?>
<?php if ( RASPI_DHCP_ENABLED ) : ?>
<?php endif; ?>
<?php if (RASPI_DHCP_ENABLED) : ?>
<li>
<a href="index.php?page=dhcpd_conf"><i class="fa fa-exchange fa-fw"></i> <?php echo _("Configure DHCP Server"); ?></a>
</li>
<?php endif; ?>
<?php if ( RASPI_OPENVPN_ENABLED ) : ?>
<?php endif; ?>
<?php if (RASPI_OPENVPN_ENABLED) : ?>
<li>
<a href="index.php?page=openvpn_conf"><i class="fa fa-lock fa-fw"></i> <?php echo _("Configure OpenVPN"); ?></a>
</li>
<?php endif; ?>
<?php if ( RASPI_TORPROXY_ENABLED ) : ?>
<?php endif; ?>
<?php if (RASPI_TORPROXY_ENABLED) : ?>
<li>
<a href="index.php?page=torproxy_conf"><i class="fa fa-eye-slash fa-fw"></i> <?php echo _("Configure TOR proxy"); ?></a>
</li>
<?php endif; ?>
<?php if ( RASPI_CONFAUTH_ENABLED ) : ?>
<?php endif; ?>
<?php if (RASPI_CONFAUTH_ENABLED) : ?>
<li>
<a href="index.php?page=auth_conf"><i class="fa fa-lock fa-fw"></i> <?php echo _("Configure Auth"); ?></a>
</li>
<?php endif; ?>
<?php if ( RASPI_CHANGETHEME_ENABLED ) : ?>
<?php endif; ?>
<?php if (RASPI_CHANGETHEME_ENABLED) : ?>
<li>
<a href="index.php?page=theme_conf"><i class="fa fa-wrench fa-fw"></i> <?php echo _("Change Theme"); ?></a>
</li>
<?php endif; ?>
<?php if ( RASPI_VNSTAT_ENABLED ) : ?>
<?php endif; ?>
<?php if (RASPI_VNSTAT_ENABLED) : ?>
<li>
<a href="index.php?page=data_use"><i class="fa fa-bar-chart fa-fw"></i> <?php echo _("Data usage"); ?></a>
</li>
<?php endif; ?>
<?php endif; ?>
<li>
<a href="index.php?page=system_info"><i class="fa fa-cube fa-fw"></i> <?php echo _("System"); ?></a>
</li>
@ -189,51 +189,51 @@ $theme_url = 'dist/css/'.htmlspecialchars($theme, ENT_QUOTES);
</div>
</div><!-- /.row -->
<?php
$extraFooterScripts = array();
<?php
$extraFooterScripts = array();
// handle page actions
switch( $page ) {
case "wlan0_info":
DisplayDashboard();
break;
case "dhcpd_conf":
DisplayDHCPConfig();
break;
case "wpa_conf":
DisplayWPAConfig();
break;
case "network_conf":
DisplayNetworkingConfig();
break;
case "hostapd_conf":
DisplayHostAPDConfig();
break;
case "openvpn_conf":
DisplayOpenVPNConfig();
break;
case "torproxy_conf":
DisplayTorProxyConfig();
break;
case "auth_conf":
DisplayAuthConfig($config['admin_user'], $config['admin_pass']);
break;
case "save_hostapd_conf":
SaveTORAndVPNConfig();
break;
case "theme_conf":
DisplayThemeConfig();
break;
case "data_use":
DisplayDataUsage($extraFooterScripts);
break;
case "system_info":
DisplaySystem();
break;
case "about":
DisplayAbout();
break;
default:
DisplayDashboard();
switch ($page) {
case "wlan0_info":
DisplayDashboard();
break;
case "dhcpd_conf":
DisplayDHCPConfig();
break;
case "wpa_conf":
DisplayWPAConfig();
break;
case "network_conf":
DisplayNetworkingConfig();
break;
case "hostapd_conf":
DisplayHostAPDConfig();
break;
case "openvpn_conf":
DisplayOpenVPNConfig();
break;
case "torproxy_conf":
DisplayTorProxyConfig();
break;
case "auth_conf":
DisplayAuthConfig($config['admin_user'], $config['admin_pass']);
break;
case "save_hostapd_conf":
SaveTORAndVPNConfig();
break;
case "theme_conf":
DisplayThemeConfig();
break;
case "data_use":
DisplayDataUsage($extraFooterScripts);
break;
case "system_info":
DisplaySystem();
break;
case "about":
DisplayAbout();
break;
default:
DisplayDashboard();
}
?>

View file

@ -1,15 +1,14 @@
<?php
$config = array(
'admin_user' => 'admin',
'admin_pass' => '$2y$10$YKIyWAmnQLtiJAy6QgHQ.eCpY4m.HCEbiHaTgN6.acNC6bDElzt.i'
'admin_user' => 'admin',
'admin_pass' => '$2y$10$YKIyWAmnQLtiJAy6QgHQ.eCpY4m.HCEbiHaTgN6.acNC6bDElzt.i'
);
if(file_exists(RASPI_CONFIG.'/raspap.auth')) {
if ( $auth_details = fopen(RASPI_CONFIG.'/raspap.auth', 'r') ) {
$config['admin_user'] = trim(fgets($auth_details));
$config['admin_pass'] = trim(fgets($auth_details));
fclose($auth_details);
if (file_exists(RASPI_CONFIG.'/raspap.auth')) {
if ($auth_details = fopen(RASPI_CONFIG.'/raspap.auth', 'r')) {
$config['admin_user'] = trim(fgets($auth_details));
$config['admin_pass'] = trim(fgets($auth_details));
fclose($auth_details);
}
}
?>