Processed with phpcbf

This commit is contained in:
billz 2020-02-15 17:57:46 +00:00
parent c0af41a53b
commit 457da91008
28 changed files with 1062 additions and 969 deletions

View file

@ -1,6 +1,6 @@
<?php <?php
require('../../includes/csrf.php'); require '../../includes/csrf.php';
require_once '../../includes/config.php'; require_once '../../includes/config.php';
require_once RASPI_CONFIG.'/raspap.php'; require_once RASPI_CONFIG.'/raspap.php';
@ -30,8 +30,10 @@ if (strlen($interface) > IFNAMSIZ) {
require_once './get_bandwidth_hourly.php'; require_once './get_bandwidth_hourly.php';
exec(sprintf('vnstat -i %s --json ', escapeshellarg($interface)), $jsonstdoutvnstat, exec(
$exitcodedaily); sprintf('vnstat -i %s --json ', escapeshellarg($interface)), $jsonstdoutvnstat,
$exitcodedaily
);
if ($exitcodedaily !== 0) { if ($exitcodedaily !== 0) {
exit('vnstat error'); exit('vnstat error');
} }
@ -53,12 +55,16 @@ echo '[ ';
$firstelm = true; $firstelm = true;
for ($i = count($jsonData) - 1; $i >= 0; --$i) { for ($i = count($jsonData) - 1; $i >= 0; --$i) {
if ($timeunits === 'm') { if ($timeunits === 'm') {
$dt = DateTime::createFromFormat('Y n', $jsonData[$i]['date']['year'].' '. $dt = DateTime::createFromFormat(
$jsonData[$i]['date']['month']); 'Y n', $jsonData[$i]['date']['year'].' '.
$jsonData[$i]['date']['month']
);
} else { } else {
$dt = DateTime::createFromFormat('Y n j', $jsonData[$i]['date']['year'].' '. $dt = DateTime::createFromFormat(
'Y n j', $jsonData[$i]['date']['year'].' '.
$jsonData[$i]['date']['month'].' '. $jsonData[$i]['date']['month'].' '.
$jsonData[$i]['date']['day']); $jsonData[$i]['date']['day']
);
} }
if ($firstelm) { if ($firstelm) {

View file

@ -1,6 +1,6 @@
<?php <?php
require('../../includes/csrf.php'); require '../../includes/csrf.php';
if (filter_input(INPUT_GET, 'tu') == 'h') { if (filter_input(INPUT_GET, 'tu') == 'h') {

View file

@ -1,9 +1,9 @@
<?php <?php
require('../../includes/csrf.php'); require '../../includes/csrf.php';
include_once('../../includes/config.php'); require_once '../../includes/config.php';
include_once('../../includes/functions.php'); require_once '../../includes/functions.php';
if (isset($_POST['generate'])) { if (isset($_POST['generate'])) {
$cnfNetworking = array_diff(scandir(RASPI_CONFIG_NETWORKING, 1), array('..','.','dhcpcd.conf')); $cnfNetworking = array_diff(scandir(RASPI_CONFIG_NETWORKING, 1), array('..','.','dhcpcd.conf'));

View file

@ -1,6 +1,6 @@
<?php <?php
require('../../includes/csrf.php'); require '../../includes/csrf.php';
exec("ls /sys/class/net | grep -v lo", $interfaces); exec("ls /sys/class/net | grep -v lo", $interfaces);
echo json_encode($interfaces); echo json_encode($interfaces);

View file

@ -1,7 +1,7 @@
<?php <?php
require('../../includes/csrf.php'); require '../../includes/csrf.php';
include_once('../../includes/config.php'); require_once '../../includes/config.php';
exec('cat '. RASPI_HOSTAPD_CONFIG, $hostapdconfig); exec('cat '. RASPI_HOSTAPD_CONFIG, $hostapdconfig);
$arrConfig = array(); $arrConfig = array();
@ -10,7 +10,7 @@ foreach ($hostapdconfig as $hostapdconfigline) {
if (strlen($hostapdconfigline) === 0) { if (strlen($hostapdconfigline) === 0) {
continue; continue;
} }
$arrLine = explode("=", $hostapdconfigline) ; $arrLine = explode("=", $hostapdconfigline);
$arrConfig[$arrLine[0]]=$arrLine[1]; $arrConfig[$arrLine[0]]=$arrLine[1];
}; };
$channel = intval($arrConfig['channel']); $channel = intval($arrConfig['channel']);

View file

@ -1,9 +1,9 @@
<?php <?php
require('../../includes/csrf.php'); require '../../includes/csrf.php';
include_once('../../includes/config.php'); require_once '../../includes/config.php';
include_once('../../includes/functions.php'); require_once '../../includes/functions.php';
if (isset($_POST['interface'])) { if (isset($_POST['interface'])) {

View file

@ -1,8 +1,8 @@
<?php <?php
require('../../includes/csrf.php'); require '../../includes/csrf.php';
include_once('../../includes/functions.php'); require_once '../../includes/functions.php';
if (isset($_POST['interface'])) { if (isset($_POST['interface'])) {
$int = preg_replace('/[^a-z0-9]/', '', $_POST['interface']); $int = preg_replace('/[^a-z0-9]/', '', $_POST['interface']);

View file

@ -1,9 +1,9 @@
<?php <?php
require('../../includes/csrf.php'); require '../../includes/csrf.php';
include_once('../../includes/config.php'); require_once '../../includes/config.php';
include_once('../../includes/functions.php'); require_once '../../includes/functions.php';
if (isset($_POST['interface'])) { if (isset($_POST['interface'])) {
$int = $_POST['interface']; $int = $_POST['interface'];

View file

@ -1,10 +1,10 @@
<?php <?php
require('../../includes/csrf.php'); require '../../includes/csrf.php';
include_once('../../includes/config.php'); require_once '../../includes/config.php';
include_once('../../includes/defaults.php'); require_once '../../includes/defaults.php';
include_once('../../includes/functions.php'); require_once '../../includes/functions.php';
include_once('../../includes/wifi_functions.php'); require_once '../../includes/wifi_functions.php';
$networks = []; $networks = [];
$network = null; $network = null;

View file

@ -1,9 +1,7 @@
<?php <?php
/** /**
*
* Displays info about the RaspAP project * Displays info about the RaspAP project
*
*/ */
function DisplayAbout() function DisplayAbout()
{ {

View file

@ -1,6 +1,6 @@
<?php <?php
include_once('includes/status_messages.php'); require_once 'includes/status_messages.php';
function DisplayAuthConfig($username, $password) function DisplayAuthConfig($username, $password)
{ {

View file

@ -1,12 +1,12 @@
<?php <?php
include_once('includes/status_messages.php'); require_once 'includes/status_messages.php';
include_once('includes/wifi_functions.php'); require_once 'includes/wifi_functions.php';
/** /**
* *
* *
*/ */
function DisplayWPAConfig() function DisplayWPAConfig()
{ {
$status = new StatusMessages(); $status = new StatusMessages();

View file

@ -1,7 +1,7 @@
<?php <?php
include_once('functions.php'); require_once 'functions.php';
include_once('session.php'); require_once 'session.php';
if (csrfValidateRequest() && !CSRFValidate()) { if (csrfValidateRequest() && !CSRFValidate()) {
handleInvalidCSRFToken(); handleInvalidCSRFToken();

View file

@ -3,8 +3,8 @@
require_once 'config.php'; require_once 'config.php';
/** /**
* Show dashboard page. * Show dashboard page.
*/ */
function DisplayDashboard(&$extraFooterScripts) function DisplayDashboard(&$extraFooterScripts)
{ {
@ -179,7 +179,8 @@ function DisplayDashboard(&$extraFooterScripts)
} }
} }
echo renderTemplate("dashboard", compact( echo renderTemplate(
"dashboard", compact(
"status", "status",
"ipv4Addrs", "ipv4Addrs",
"ipv4Netmasks", "ipv4Netmasks",
@ -197,7 +198,8 @@ function DisplayDashboard(&$extraFooterScripts)
"frequency", "frequency",
"strLinkQuality", "strLinkQuality",
"wlan0up" "wlan0up"
)); )
);
$extraFooterScripts[] = array('src'=>'app/js/dashboardchart.js', 'defer'=>false); $extraFooterScripts[] = array('src'=>'app/js/dashboardchart.js', 'defer'=>false);
} }

View file

@ -1,13 +1,11 @@
<?php <?php
include_once('includes/status_messages.php'); require_once 'includes/status_messages.php';
require_once 'config.php'; require_once 'config.php';
/** /**
* * Manage DHCP configuration
* Manage DHCP configuration */
*
*/
function DisplayDHCPConfig() function DisplayDHCPConfig()
{ {
@ -16,18 +14,21 @@ function DisplayDHCPConfig()
if (isset($_POST['savedhcpdsettings'])) { if (isset($_POST['savedhcpdsettings'])) {
$errors = ''; $errors = '';
define('IFNAMSIZ', 16); define('IFNAMSIZ', 16);
if (!preg_match('/^[a-zA-Z0-9]+$/', $_POST['interface']) || if (!preg_match('/^[a-zA-Z0-9]+$/', $_POST['interface'])
strlen($_POST['interface']) >= IFNAMSIZ) { || strlen($_POST['interface']) >= IFNAMSIZ
) {
$errors .= _('Invalid interface name.').'<br />'.PHP_EOL; $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']) && if (!preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/', $_POST['RangeStart'])
!empty($_POST['RangeStart'])) { // allow ''/null ? && !empty($_POST['RangeStart'])
) { // allow ''/null ?
$errors .= _('Invalid DHCP range start.').'<br />'.PHP_EOL; $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']) && if (!preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\z/', $_POST['RangeEnd'])
!empty($_POST['RangeEnd'])) { // allow ''/null ? && !empty($_POST['RangeEnd'])
) { // allow ''/null ?
$errors .= _('Invalid DHCP range end.').'<br />'.PHP_EOL; $errors .= _('Invalid DHCP range end.').'<br />'.PHP_EOL;
} }
@ -58,9 +59,9 @@ function DisplayDHCPConfig()
} }
} }
if ($_POST['DNS1']){ if ($_POST['DNS1']) {
$config .= "dhcp-option=6," . $_POST['DNS1']; $config .= "dhcp-option=6," . $_POST['DNS1'];
if ($_POST['DNS2']){ if ($_POST['DNS2']) {
$config .= ','.$_POST['DNS2']; $config .= ','.$_POST['DNS2'];
} }
$config .= PHP_EOL; $config .= PHP_EOL;
@ -126,13 +127,13 @@ function DisplayDHCPConfig()
$DNS1 = ''; $DNS1 = '';
$DNS2 = ''; $DNS2 = '';
if (isset($conf['dhcp-option'])){ if (isset($conf['dhcp-option'])) {
$arrDns = explode(",", $conf['dhcp-option']); $arrDns = explode(",", $conf['dhcp-option']);
if ($arrDns[0] == '6'){ if ($arrDns[0] == '6') {
if (count($arrDns) > 1){ if (count($arrDns) > 1) {
$DNS1 = $arrDns[1]; $DNS1 = $arrDns[1];
} }
if (count($arrDns) > 2){ if (count($arrDns) > 2) {
$DNS2 = $arrDns[2]; $DNS2 = $arrDns[2];
} }
} }
@ -162,7 +163,8 @@ function DisplayDHCPConfig()
exec("ip -o link show | awk -F': ' '{print $2}'", $interfaces); exec("ip -o link show | awk -F': ' '{print $2}'", $interfaces);
exec('cat ' . RASPI_DNSMASQ_LEASES, $leases); exec('cat ' . RASPI_DNSMASQ_LEASES, $leases);
echo renderTemplate("dhcp", compact( echo renderTemplate(
"dhcp", compact(
"status", "status",
"serviceStatus", "serviceStatus",
"RangeStart", "RangeStart",
@ -179,5 +181,6 @@ function DisplayDHCPConfig()
"dhcpHost", "dhcpHost",
"interfaces", "interfaces",
"leases" "leases"
)); )
);
} }

View file

@ -55,8 +55,8 @@ function safefilerewrite($fileName, $dataToSave)
} }
/** /**
* Saves a CSRF token in the session * Saves a CSRF token in the session
*/ */
function ensureCSRFSessionToken() function ensureCSRFSessionToken()
{ {
if (empty($_SESSION['csrf_token'])) { if (empty($_SESSION['csrf_token'])) {
@ -65,10 +65,8 @@ function ensureCSRFSessionToken()
} }
/** /**
* * Add CSRF Token to form
* Add CSRF Token to form */
*
*/
function CSRFTokenFieldTag() function CSRFTokenFieldTag()
{ {
$token = htmlspecialchars($_SESSION['csrf_token']); $token = htmlspecialchars($_SESSION['csrf_token']);
@ -76,8 +74,8 @@ function CSRFTokenFieldTag()
} }
/** /**
* Retuns a CSRF meta tag (for use with xhr, for example) * Retuns a CSRF meta tag (for use with xhr, for example)
*/ */
function CSRFMetaTag() function CSRFMetaTag()
{ {
$token = htmlspecialchars($_SESSION['csrf_token']); $token = htmlspecialchars($_SESSION['csrf_token']);
@ -85,10 +83,8 @@ function CSRFMetaTag()
} }
/** /**
* * Validate CSRF Token
* Validate CSRF Token */
*
*/
function CSRFValidate() function CSRFValidate()
{ {
$post_token = $_POST['csrf_token']; $post_token = $_POST['csrf_token'];
@ -112,8 +108,8 @@ function CSRFValidate()
} }
/** /**
* Should the request be CSRF-validated? * Should the request be CSRF-validated?
*/ */
function csrfValidateRequest() function csrfValidateRequest()
{ {
$request_method = strtolower($_SERVER['REQUEST_METHOD']); $request_method = strtolower($_SERVER['REQUEST_METHOD']);
@ -121,8 +117,8 @@ function csrfValidateRequest()
} }
/** /**
* Handle invalid CSRF * Handle invalid CSRF
*/ */
function handleInvalidCSRFToken() function handleInvalidCSRFToken()
{ {
header('HTTP/1.1 500 Internal Server Error'); header('HTTP/1.1 500 Internal Server Error');
@ -132,23 +128,23 @@ function handleInvalidCSRFToken()
} }
/** /**
* Test whether array is associative * Test whether array is associative
*/ */
function isAssoc($arr) function isAssoc($arr)
{ {
return array_keys($arr) !== range(0, count($arr) - 1); return array_keys($arr) !== range(0, count($arr) - 1);
} }
/** /**
* * Display a selector field for a form. Arguments are:
* Display a selector field for a form. Arguments are: *
* @param string $name: Field name * @param string $name: Field name
* @param array $options: Array of options * @param array $options: Array of options
* @param string $selected: Selected option (optional) * @param string $selected: Selected option (optional)
* @param string $id: $options is an associative array this should be the key * @param string $id: $options is an associative array this should be the key
* @param string $event: onChange event (optional) * @param string $event: onChange event (optional)
* @param string $disabled (optional) * @param string $disabled (optional)
*/ */
function SelectorOptions($name, $options, $selected = null, $id = null, $event = null, $disabled = null) function SelectorOptions($name, $options, $selected = null, $id = null, $event = null, $disabled = null)
{ {
echo '<select class="form-control" name="'.htmlspecialchars($name, ENT_QUOTES).'"'; echo '<select class="form-control" name="'.htmlspecialchars($name, ENT_QUOTES).'"';
@ -176,13 +172,13 @@ function SelectorOptions($name, $options, $selected = null, $id = null, $event =
} }
/** /**
* *
* @param string $input * @param string $input
* @param string $string * @param string $string
* @param int $offset * @param int $offset
* @param string $separator * @param string $separator
* @return $string * @return $string
*/ */
function GetDistString($input, $string, $offset, $separator) function GetDistString($input, $string, $offset, $separator)
{ {
$string = substr($input, strpos($input, $string)+$offset, strpos(substr($input, strpos($input, $string)+$offset), $separator)); $string = substr($input, strpos($input, $string)+$offset, strpos(substr($input, strpos($input, $string)+$offset), $separator));
@ -190,10 +186,10 @@ function GetDistString($input, $string, $offset, $separator)
} }
/** /**
* *
* @param array $arrConfig * @param array $arrConfig
* @return $config * @return $config
*/ */
function ParseConfig($arrConfig) function ParseConfig($arrConfig)
{ {
$config = array(); $config = array();
@ -218,10 +214,10 @@ function ParseConfig($arrConfig)
} }
/** /**
* *
* @param string $freq * @param string $freq
* @return $channel * @return $channel
*/ */
function ConvertToChannel($freq) function ConvertToChannel($freq)
{ {
if ($freq >= 2412 && $freq <= 2484) { if ($freq >= 2412 && $freq <= 2484) {
@ -241,10 +237,11 @@ function ConvertToChannel($freq)
} }
/** /**
* Converts WPA security string to readable format * Converts WPA security string to readable format
* @param string $security *
* @return string * @param string $security
*/ * @return string
*/
function ConvertToSecurity($security) function ConvertToSecurity($security)
{ {
$options = array(); $options = array();

View file

@ -1,13 +1,13 @@
<?php <?php
include_once('includes/status_messages.php'); require_once 'includes/status_messages.php';
include_once('app/lib/system.php'); require_once 'app/lib/system.php';
require_once 'config.php'; require_once 'config.php';
/** /**
* *
* *
*/ */
function DisplayHostAPDConfig() function DisplayHostAPDConfig()
{ {
$status = new StatusMessages(); $status = new StatusMessages();
@ -50,7 +50,7 @@ function DisplayHostAPDConfig()
exec('cat '. RASPI_HOSTAPD_CONFIG, $hostapdconfig); exec('cat '. RASPI_HOSTAPD_CONFIG, $hostapdconfig);
exec('iwgetid '. RASPI_WIFI_CLIENT_INTERFACE. ' -r', $wifiNetworkID); exec('iwgetid '. RASPI_WIFI_CLIENT_INTERFACE. ' -r', $wifiNetworkID);
if ( !empty($wifiNetworkID[0])) { if (!empty($wifiNetworkID[0])) {
$managedModeEnabled = true; $managedModeEnabled = true;
} }
$hostapdstatus = $system->hostapdStatus(); $hostapdstatus = $system->hostapdStatus();
@ -62,12 +62,13 @@ function DisplayHostAPDConfig()
} }
if ($hostapdconfigline[0] != "#") { if ($hostapdconfigline[0] != "#") {
$arrLine = explode("=", $hostapdconfigline) ; $arrLine = explode("=", $hostapdconfigline);
$arrConfig[$arrLine[0]]=$arrLine[1]; $arrConfig[$arrLine[0]]=$arrLine[1];
} }
}; };
echo renderTemplate("hostapd", compact( echo renderTemplate(
"hostapd", compact(
"status", "status",
"serviceStatus", "serviceStatus",
"hostapdstatus", "hostapdstatus",
@ -79,16 +80,18 @@ function DisplayHostAPDConfig()
"arrSecurity", "arrSecurity",
"arrEncType", "arrEncType",
"arrHostapdConf" "arrHostapdConf"
)); )
);
} }
function SaveHostAPDConfig($wpa_array, $enc_types, $modes, $interfaces, $status) function SaveHostAPDConfig($wpa_array, $enc_types, $modes, $interfaces, $status)
{ {
// It should not be possible to send bad data for these fields so clearly // It should not be possible to send bad data for these fields so clearly
// someone is up to something if they fail. Fail silently. // someone is up to something if they fail. Fail silently.
if (!(array_key_exists($_POST['wpa'], $wpa_array) && if (!(array_key_exists($_POST['wpa'], $wpa_array)
array_key_exists($_POST['wpa_pairwise'], $enc_types) && && array_key_exists($_POST['wpa_pairwise'], $enc_types)
array_key_exists($_POST['hw_mode'], $modes))) { && array_key_exists($_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 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; return false;
} }
@ -147,8 +150,9 @@ function SaveHostAPDConfig($wpa_array, $enc_types, $modes, $interfaces, $status)
$good_input = false; $good_input = false;
} }
if ($_POST['wpa'] !== 'none' && if ($_POST['wpa'] !== 'none'
(strlen($_POST['wpa_passphrase']) < 8 || strlen($_POST['wpa_passphrase']) > 63)) { && (strlen($_POST['wpa_passphrase']) < 8 || strlen($_POST['wpa_passphrase']) > 63)
) {
$status->addMessage('WPA passphrase must be between 8 and 63 characters', 'danger'); $status->addMessage('WPA passphrase must be between 8 and 63 characters', 'danger');
$good_input = false; $good_input = false;
} }

View file

@ -1,16 +1,15 @@
<?php <?php
/** /**
* Sets locale information for i18n support * Sets locale information for i18n support
* */
*/
/** /**
* Rudimentary language detection via the browser. * Rudimentary language detection via the browser.
* Accept-Language returns a list of weighted values with a quality (or 'q') parameter. * 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. * the languages supported by our platform.
* *
* Refer to: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 * Refer to: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
*/ */
if (empty($_SESSION['locale']) && strlen($_SERVER['HTTP_ACCEPT_LANGUAGE']) >= 2) { if (empty($_SESSION['locale']) && strlen($_SERVER['HTTP_ACCEPT_LANGUAGE']) >= 2) {
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

View file

@ -1,11 +1,11 @@
<?php <?php
include_once('includes/status_messages.php'); require_once 'includes/status_messages.php';
/** /**
* *
* *
*/ */
function DisplayNetworkingConfig() function DisplayNetworkingConfig()
{ {

View file

@ -1,12 +1,10 @@
<?php <?php
include_once('includes/status_messages.php'); require_once 'includes/status_messages.php';
require_once 'config.php'; require_once 'config.php';
/** /**
*
* Manage OpenVPN configuration * Manage OpenVPN configuration
*
*/ */
function DisplayOpenVPNConfig() function DisplayOpenVPNConfig()
{ {
@ -48,18 +46,19 @@ function DisplayOpenVPNConfig()
$authPassword = $auth[1]; $authPassword = $auth[1];
} }
echo renderTemplate("openvpn", compact( echo renderTemplate(
"openvpn", compact(
"status", "status",
"serviceStatus", "serviceStatus",
"openvpnstatus", "openvpnstatus",
"public_ip", "public_ip",
"authUser", "authUser",
"authPassword" "authPassword"
)); )
);
} }
/** /**
*
* Validates uploaded .ovpn file, adds auth-user-pass and * Validates uploaded .ovpn file, adds auth-user-pass and
* stores auth credentials in login.conf. Copies files from * stores auth credentials in login.conf. Copies files from
* tmp to OpenVPN * tmp to OpenVPN
@ -109,7 +108,8 @@ function SaveOpenVPNConfig($status, $file, $authUser, $authPassword)
'ovpn' => 'text/plain' 'ovpn' => 'text/plain'
), ),
true true
)) { )
) {
throw new RuntimeException('Invalid file format'); throw new RuntimeException('Invalid file format');
} }
@ -127,7 +127,8 @@ function SaveOpenVPNConfig($status, $file, $authUser, $authPassword)
'ovpnclient', 'ovpnclient',
$ext $ext
) )
)) { )
) {
throw new RuntimeException('Unable to move uploaded file'); throw new RuntimeException('Unable to move uploaded file');
} }
// Good file upload, update auth credentials if present // Good file upload, update auth credentials if present

View file

@ -1,6 +1,6 @@
<?php <?php
include_once('app/lib/system.php'); require_once 'app/lib/system.php';
$system = new System(); $system = new System();

View file

@ -1,13 +1,11 @@
<?php <?php
include_once('includes/status_messages.php'); require_once 'includes/status_messages.php';
require_once 'config.php'; require_once 'config.php';
/** /**
*
* Find the version of the Raspberry Pi * Find the version of the Raspberry Pi
* Currently only used for the system information page but may useful elsewhere * Currently only used for the system information page but may useful elsewhere
*
*/ */
function RPiVersion() function RPiVersion()
@ -98,7 +96,7 @@ function DisplaySystem()
} }
if (isset($_POST['RestartLighttpd'])) { if (isset($_POST['RestartLighttpd'])) {
$status->addMessage('Restarting lighttpd in 3 seconds...','info'); $status->addMessage('Restarting lighttpd in 3 seconds...', 'info');
exec('sudo /etc/raspap/lighttpd/configport.sh --restart'); exec('sudo /etc/raspap/lighttpd/configport.sh --restart');
} }
exec('cat '. RASPI_LIGHTTPD_CONFIG, $return); exec('cat '. RASPI_LIGHTTPD_CONFIG, $return);

View file

@ -1,8 +1,8 @@
<?php <?php
/** /**
* *
* *
*/ */
function DisplayThemeConfig() function DisplayThemeConfig()
{ {
$themes = [ $themes = [

View file

@ -1,12 +1,10 @@
<?php <?php
include_once('includes/status_messages.php'); require_once 'includes/status_messages.php';
/** /**
* * Manage Tor Proxy configuration
* Manage Tor Proxy configuration */
*
*/
function DisplayTorProxyConfig() function DisplayTorProxyConfig()
{ {
@ -16,21 +14,23 @@ function DisplayTorProxyConfig()
$arrConfig = array(); $arrConfig = array();
foreach ($return as $a) { foreach ($return as $a) {
if ($a[0] != "#") { if ($a[0] != "#") {
$arrLine = explode(" ", $a) ; $arrLine = explode(" ", $a);
$arrConfig[$arrLine[0]]=$arrLine[1]; $arrConfig[$arrLine[0]]=$arrLine[1];
} }
} }
echo renderTemplate("torproxy", compact( echo renderTemplate(
"torproxy", compact(
"status", "status",
"torproxystatus" "torproxystatus"
)); )
);
} }
/** /**
* *
* *
*/ */
function SaveTORAndVPNConfig() function SaveTORAndVPNConfig()
{ {
if (isset($_POST['SaveTORProxySettings'])) { if (isset($_POST['SaveTORProxySettings'])) {

View file

@ -59,13 +59,15 @@ $HOME_DIRECTORY = '';
* JSON RPC Server for Eaze * JSON RPC Server for Eaze
* *
* Reads $_GET['rawRequest'] or php://input for Request Data * Reads $_GET['rawRequest'] or php://input for Request Data
*
* @link http://www.jsonrpc.org/specification * @link http://www.jsonrpc.org/specification
* @link http://dojotoolkit.org/reference-guide/1.8/dojox/rpc/smd.html * @link http://dojotoolkit.org/reference-guide/1.8/dojox/rpc/smd.html
* @package Eaze * @package Eaze
* @subpackage Model * @subpackage Model
* @author Sergeyfast * @author Sergeyfast
*/ */
class BaseJsonRpcServer { class BaseJsonRpcServer
{
const ParseError = -32700, const ParseError = -32700,
InvalidRequest = -32600, InvalidRequest = -32600,
@ -75,42 +77,49 @@ $HOME_DIRECTORY = '';
/** /**
* Exposed Instances * Exposed Instances
*
* @var object[] namespace => method * @var object[] namespace => method
*/ */
protected $instances = array(); protected $instances = array();
/** /**
* Decoded Json Request * Decoded Json Request
*
* @var object|array * @var object|array
*/ */
protected $request; protected $request;
/** /**
* Array of Received Calls * Array of Received Calls
*
* @var array * @var array
*/ */
protected $calls = array(); protected $calls = array();
/** /**
* Array of Responses for Calls * Array of Responses for Calls
*
* @var array * @var array
*/ */
protected $response = array(); protected $response = array();
/** /**
* Has Calls Flag (not notifications) * Has Calls Flag (not notifications)
*
* @var bool * @var bool
*/ */
protected $hasCalls = false; protected $hasCalls = false;
/** /**
* Is Batch Call in using * Is Batch Call in using
*
* @var bool * @var bool
*/ */
private $isBatchCall = false; private $isBatchCall = false;
/** /**
* Hidden Methods * Hidden Methods
*
* @var array * @var array
*/ */
protected $hiddenMethods = array( protected $hiddenMethods = array(
@ -119,24 +128,28 @@ $HOME_DIRECTORY = '';
/** /**
* Content Type * Content Type
*
* @var string * @var string
*/ */
public $ContentType = 'application/json'; public $ContentType = 'application/json';
/** /**
* Allow Cross-Domain Requests * Allow Cross-Domain Requests
*
* @var bool * @var bool
*/ */
public $IsXDR = true; public $IsXDR = true;
/** /**
* Max Batch Calls * Max Batch Calls
*
* @var int * @var int
*/ */
public $MaxBatchCalls = 10; public $MaxBatchCalls = 10;
/** /**
* Error Messages * Error Messages
*
* @var array * @var array
*/ */
protected $errorMessages = array( protected $errorMessages = array(
@ -150,6 +163,7 @@ $HOME_DIRECTORY = '';
/** /**
* Cached Reflection Methods * Cached Reflection Methods
*
* @var ReflectionMethod[] * @var ReflectionMethod[]
*/ */
private $reflectionMethods = array(); private $reflectionMethods = array();
@ -157,32 +171,34 @@ $HOME_DIRECTORY = '';
/** /**
* Validate Request * Validate Request
*
* @return int error * @return int error
*/ */
private function getRequest() { private function getRequest()
{
$error = null; $error = null;
do { do {
if ( array_key_exists( 'REQUEST_METHOD', $_SERVER ) && $_SERVER['REQUEST_METHOD'] != 'POST' ) { if (array_key_exists('REQUEST_METHOD', $_SERVER) && $_SERVER['REQUEST_METHOD'] != 'POST' ) {
$error = self::InvalidRequest; $error = self::InvalidRequest;
break; break;
}; };
$request = !empty( $_GET['rawRequest'] ) ? $_GET['rawRequest'] : file_get_contents( 'php://input' ); $request = !empty($_GET['rawRequest']) ? $_GET['rawRequest'] : file_get_contents('php://input');
$this->request = json_decode( $request, false ); $this->request = json_decode($request, false);
if ( $this->request === null ) { if ($this->request === null ) {
$error = self::ParseError; $error = self::ParseError;
break; break;
} }
if ( $this->request === array() ) { if ($this->request === array() ) {
$error = self::InvalidRequest; $error = self::InvalidRequest;
break; break;
} }
// check for batch call // check for batch call
if ( is_array( $this->request ) ) { if (is_array($this->request) ) {
if( count( $this->request ) > $this->MaxBatchCalls ) { if(count($this->request) > $this->MaxBatchCalls ) {
$error = self::InvalidRequest; $error = self::InvalidRequest;
break; break;
} }
@ -200,18 +216,20 @@ $HOME_DIRECTORY = '';
/** /**
* Get Error Response * Get Error Response
*
* @param int $code * @param int $code
* @param mixed $id * @param mixed $id
* @param null $data * @param null $data
* @return array * @return array
*/ */
private function getError( $code, $id = null, $data = null ) { private function getError( $code, $id = null, $data = null )
{
return array( return array(
'jsonrpc' => '2.0', 'jsonrpc' => '2.0',
'id' => $id, 'id' => $id,
'error' => array( 'error' => array(
'code' => $code, 'code' => $code,
'message' => isset( $this->errorMessages[$code] ) ? $this->errorMessages[$code] : $this->errorMessages[self::InternalError], 'message' => isset($this->errorMessages[$code]) ? $this->errorMessages[$code] : $this->errorMessages[self::InternalError],
'data' => $data, 'data' => $data,
), ),
); );
@ -220,49 +238,53 @@ $HOME_DIRECTORY = '';
/** /**
* Check for jsonrpc version and correct method * Check for jsonrpc version and correct method
*
* @param object $call * @param object $call
* @return array|null * @return array|null
*/ */
private function validateCall( $call ) { private function validateCall( $call )
{
$result = null; $result = null;
$error = null; $error = null;
$data = null; $data = null;
$id = is_object( $call ) && property_exists( $call, 'id' ) ? $call->id : null; $id = is_object($call) && property_exists($call, 'id') ? $call->id : null;
do { do {
if ( !is_object( $call ) ) { if (!is_object($call) ) {
$error = self::InvalidRequest; $error = self::InvalidRequest;
break; break;
} }
// hack for inputEx smd tester // hack for inputEx smd tester
if ( property_exists( $call, 'version' ) ) { if (property_exists($call, 'version') ) {
if ( $call->version == 'json-rpc-2.0' ) { if ($call->version == 'json-rpc-2.0' ) {
$call->jsonrpc = '2.0'; $call->jsonrpc = '2.0';
} }
} }
if ( !property_exists( $call, 'jsonrpc' ) || $call->jsonrpc != '2.0' ) { if (!property_exists($call, 'jsonrpc') || $call->jsonrpc != '2.0' ) {
$error = self::InvalidRequest; $error = self::InvalidRequest;
break; break;
} }
$fullMethod = property_exists( $call, 'method' ) ? $call->method : ''; $fullMethod = property_exists($call, 'method') ? $call->method : '';
$methodInfo = explode( '.', $fullMethod, 2 ); $methodInfo = explode('.', $fullMethod, 2);
$namespace = array_key_exists( 1, $methodInfo ) ? $methodInfo[0] : ''; $namespace = array_key_exists(1, $methodInfo) ? $methodInfo[0] : '';
$method = $namespace ? $methodInfo[1] : $fullMethod; $method = $namespace ? $methodInfo[1] : $fullMethod;
if ( !$method || !array_key_exists( $namespace, $this->instances ) || !method_exists( $this->instances[$namespace], $method ) || in_array( strtolower( $method ), $this->hiddenMethods ) ) { if (!$method || !array_key_exists($namespace, $this->instances) || !method_exists($this->instances[$namespace], $method) || in_array(strtolower($method), $this->hiddenMethods) ) {
$error = self::MethodNotFound; $error = self::MethodNotFound;
break; break;
} }
if ( !array_key_exists( $fullMethod, $this->reflectionMethods ) ) { if (!array_key_exists($fullMethod, $this->reflectionMethods) ) {
$this->reflectionMethods[$fullMethod] = new ReflectionMethod( $this->instances[$namespace], $method ); $this->reflectionMethods[$fullMethod] = new ReflectionMethod($this->instances[$namespace], $method);
} }
/** @var $params array */ /**
$params = property_exists( $call, 'params' ) ? $call->params : null; * @var $params array
$paramsType = gettype( $params ); */
if ( $params !== null && $paramsType != 'array' && $paramsType != 'object' ) { $params = property_exists($call, 'params') ? $call->params : null;
$paramsType = gettype($params);
if ($params !== null && $paramsType != 'array' && $paramsType != 'object' ) {
$error = self::InvalidParams; $error = self::InvalidParams;
break; break;
} }
@ -273,19 +295,19 @@ $HOME_DIRECTORY = '';
$totalRequired = 0; $totalRequired = 0;
// doesn't hold required, null, required sequence of params // doesn't hold required, null, required sequence of params
foreach ( $this->reflectionMethods[$fullMethod]->getParameters() as $param ) { foreach ( $this->reflectionMethods[$fullMethod]->getParameters() as $param ) {
if ( !$param->isDefaultValueAvailable() ) { if (!$param->isDefaultValueAvailable() ) {
$totalRequired++; $totalRequired++;
} }
} }
if ( count( $params ) < $totalRequired ) { if (count($params) < $totalRequired ) {
$error = self::InvalidParams; $error = self::InvalidParams;
$data = sprintf( 'Check numbers of required params (got %d, expected %d)', count( $params ), $totalRequired ); $data = sprintf('Check numbers of required params (got %d, expected %d)', count($params), $totalRequired);
} }
break; break;
case 'object': case 'object':
foreach ( $this->reflectionMethods[$fullMethod]->getParameters() as $param ) { foreach ( $this->reflectionMethods[$fullMethod]->getParameters() as $param ) {
if ( !$param->isDefaultValueAvailable() && !array_key_exists( $param->getName(), $params ) ) { if (!$param->isDefaultValueAvailable() && !array_key_exists($param->getName(), $params) ) {
$error = self::InvalidParams; $error = self::InvalidParams;
$data = $param->getName() . ' not found'; $data = $param->getName() . ' not found';
@ -294,7 +316,7 @@ $HOME_DIRECTORY = '';
} }
break; break;
case 'NULL': case 'NULL':
if ( $this->reflectionMethods[$fullMethod]->getNumberOfRequiredParameters() > 0 ) { if ($this->reflectionMethods[$fullMethod]->getNumberOfRequiredParameters() > 0 ) {
$error = self::InvalidParams; $error = self::InvalidParams;
$data = 'Empty required params'; $data = 'Empty required params';
break 2; break 2;
@ -304,7 +326,7 @@ $HOME_DIRECTORY = '';
} while ( false ); } while ( false );
if ( $error ) { if ($error ) {
$result = array( $error, $id, $data ); $result = array( $error, $id, $data );
} }
@ -314,35 +336,37 @@ $HOME_DIRECTORY = '';
/** /**
* Process Call * Process Call
*
* @param $call * @param $call
* @return array|null * @return array|null
*/ */
private function processCall( $call ) { private function processCall( $call )
$id = property_exists( $call, 'id' ) ? $call->id : null; {
$params = property_exists( $call, 'params' ) ? $call->params : array(); $id = property_exists($call, 'id') ? $call->id : null;
$params = property_exists($call, 'params') ? $call->params : array();
$result = null; $result = null;
$namespace = substr( $call->method, 0, strpos( $call->method, '.' ) ); $namespace = substr($call->method, 0, strpos($call->method, '.'));
try { try {
// set named parameters // set named parameters
if ( is_object( $params ) ) { if (is_object($params) ) {
$newParams = array(); $newParams = array();
foreach ( $this->reflectionMethods[$call->method]->getParameters() as $param ) { foreach ( $this->reflectionMethods[$call->method]->getParameters() as $param ) {
$paramName = $param->getName(); $paramName = $param->getName();
$defaultValue = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null; $defaultValue = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null;
$newParams[] = property_exists( $params, $paramName ) ? $params->$paramName : $defaultValue; $newParams[] = property_exists($params, $paramName) ? $params->$paramName : $defaultValue;
} }
$params = $newParams; $params = $newParams;
} }
// invoke // invoke
$result = $this->reflectionMethods[$call->method]->invokeArgs( $this->instances[$namespace], $params ); $result = $this->reflectionMethods[$call->method]->invokeArgs($this->instances[$namespace], $params);
} catch ( Exception $e ) { } catch ( Exception $e ) {
return $this->getError( $e->getCode(), $id, $e->getMessage() ); return $this->getError($e->getCode(), $id, $e->getMessage());
} }
if ( !$id && $id !== 0 ) { if (!$id && $id !== 0 ) {
return null; return null;
} }
@ -356,24 +380,28 @@ $HOME_DIRECTORY = '';
/** /**
* Create new Instance * Create new Instance
*
* @param object $instance * @param object $instance
*/ */
public function __construct( $instance = null ) { public function __construct( $instance = null )
if ( get_parent_class( $this ) ) { {
$this->RegisterInstance( $this, '' ); if (get_parent_class($this) ) {
} else if ( $instance ) { $this->RegisterInstance($this, '');
$this->RegisterInstance( $instance, '' ); } else if ($instance ) {
$this->RegisterInstance($instance, '');
} }
} }
/** /**
* Register Instance * Register Instance
*
* @param object $instance * @param object $instance
* @param string $namespace default is empty string * @param string $namespace default is empty string
* @return $this * @return $this
*/ */
public function RegisterInstance( $instance, $namespace = '' ) { public function RegisterInstance( $instance, $namespace = '' )
{
$this->instances[$namespace] = $instance; $this->instances[$namespace] = $instance;
$this->instances[$namespace]->errorMessages = $this->errorMessages; $this->instances[$namespace]->errorMessages = $this->errorMessages;
@ -384,30 +412,31 @@ $HOME_DIRECTORY = '';
/** /**
* Handle Requests * Handle Requests
*/ */
public function Execute() { public function Execute()
{
do { do {
// check for SMD Discovery request // check for SMD Discovery request
if ( array_key_exists( 'smd', $_GET ) ) { if (array_key_exists('smd', $_GET) ) {
$this->response[] = $this->getServiceMap(); $this->response[] = $this->getServiceMap();
$this->hasCalls = true; $this->hasCalls = true;
break; break;
} }
$error = $this->getRequest(); $error = $this->getRequest();
if ( $error ) { if ($error ) {
$this->response[] = $this->getError( $error ); $this->response[] = $this->getError($error);
$this->hasCalls = true; $this->hasCalls = true;
break; break;
} }
foreach ( $this->calls as $call ) { foreach ( $this->calls as $call ) {
$error = $this->validateCall( $call ); $error = $this->validateCall($call);
if ( $error ) { if ($error ) {
$this->response[] = $this->getError( $error[0], $error[1], $error[2] ); $this->response[] = $this->getError($error[0], $error[1], $error[2]);
$this->hasCalls = true; $this->hasCalls = true;
} else { } else {
$result = $this->processCall( $call ); $result = $this->processCall($call);
if ( $result ) { if ($result ) {
$this->response[] = $result; $this->response[] = $result;
$this->hasCalls = true; $this->hasCalls = true;
} }
@ -416,25 +445,25 @@ $HOME_DIRECTORY = '';
} while ( false ); } while ( false );
// flush response // flush response
if ( $this->hasCalls ) { if ($this->hasCalls ) {
if ( !$this->isBatchCall ) { if (!$this->isBatchCall ) {
$this->response = reset( $this->response ); $this->response = reset($this->response);
} }
if ( !headers_sent() ) { if (!headers_sent() ) {
// Set Content Type // Set Content Type
if ( $this->ContentType ) { if ($this->ContentType ) {
header( 'Content-Type: ' . $this->ContentType ); header('Content-Type: ' . $this->ContentType);
} }
// Allow Cross Domain Requests // Allow Cross Domain Requests
if ( $this->IsXDR ) { if ($this->IsXDR ) {
header( 'Access-Control-Allow-Origin: *' ); header('Access-Control-Allow-Origin: *');
header( 'Access-Control-Allow-Headers: x-requested-with, content-type' ); header('Access-Control-Allow-Headers: x-requested-with, content-type');
} }
} }
echo json_encode( $this->response ); echo json_encode($this->response);
$this->resetVars(); $this->resetVars();
} }
} }
@ -442,13 +471,15 @@ $HOME_DIRECTORY = '';
/** /**
* Get Doc Comment * Get Doc Comment
*
* @param $comment * @param $comment
* @return string|null * @return string|null
*/ */
private function getDocDescription( $comment ) { private function getDocDescription( $comment )
{
$result = null; $result = null;
if ( preg_match( '/\*\s+([^@]*)\s+/s', $comment, $matches ) ) { if (preg_match('/\*\s+([^@]*)\s+/s', $comment, $matches) ) {
$result = str_replace( '*', "\n", trim( trim( $matches[1], '*' ) ) ); $result = str_replace('*', "\n", trim(trim($matches[1], '*')));
} }
return $result; return $result;
@ -458,30 +489,34 @@ $HOME_DIRECTORY = '';
/** /**
* Get Service Map * Get Service Map
* Maybe not so good realization of auto-discover via doc blocks * Maybe not so good realization of auto-discover via doc blocks
*
* @return array * @return array
*/ */
private function getServiceMap() { private function getServiceMap()
{
$result = array( $result = array(
'transport' => 'POST', 'transport' => 'POST',
'envelope' => 'JSON-RPC-2.0', 'envelope' => 'JSON-RPC-2.0',
'SMDVersion' => '2.0', 'SMDVersion' => '2.0',
'contentType' => 'application/json', 'contentType' => 'application/json',
'target' => !empty( $_SERVER['REQUEST_URI'] ) ? substr( $_SERVER['REQUEST_URI'], 0, strpos( $_SERVER['REQUEST_URI'], '?' ) ) : '', 'target' => !empty($_SERVER['REQUEST_URI']) ? substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) : '',
'services' => array(), 'services' => array(),
'description' => '', 'description' => '',
); );
foreach( $this->instances as $namespace => $instance ) { foreach( $this->instances as $namespace => $instance ) {
$rc = new ReflectionClass( $instance); $rc = new ReflectionClass($instance);
// Get Class Description // Get Class Description
if ( $rcDocComment = $this->getDocDescription( $rc->getDocComment() ) ) { if ($rcDocComment = $this->getDocDescription($rc->getDocComment()) ) {
$result['description'] .= $rcDocComment . PHP_EOL; $result['description'] .= $rcDocComment . PHP_EOL;
} }
foreach ( $rc->getMethods() as $method ) { foreach ( $rc->getMethods() as $method ) {
/** @var ReflectionMethod $method */ /**
if ( !$method->isPublic() || in_array( strtolower( $method->getName() ), $this->hiddenMethods ) ) { * @var ReflectionMethod $method
*/
if (!$method->isPublic() || in_array(strtolower($method->getName()), $this->hiddenMethods) ) {
continue; continue;
} }
@ -491,20 +526,20 @@ $HOME_DIRECTORY = '';
$result['services'][$methodName] = array( 'parameters' => array() ); $result['services'][$methodName] = array( 'parameters' => array() );
// set description // set description
if ( $rmDocComment = $this->getDocDescription( $docComment ) ) { if ($rmDocComment = $this->getDocDescription($docComment) ) {
$result['services'][$methodName]['description'] = $rmDocComment; $result['services'][$methodName]['description'] = $rmDocComment;
} }
// @param\s+([^\s]*)\s+([^\s]*)\s*([^\s\*]*) // @param\s+([^\s]*)\s+([^\s]*)\s*([^\s\*]*)
$parsedParams = array(); $parsedParams = array();
if ( preg_match_all( '/@param\s+([^\s]*)\s+([^\s]*)\s*([^\n\*]*)/', $docComment, $matches ) ) { if (preg_match_all('/@param\s+([^\s]*)\s+([^\s]*)\s*([^\n\*]*)/', $docComment, $matches) ) {
foreach ( $matches[2] as $number => $name ) { foreach ( $matches[2] as $number => $name ) {
$type = $matches[1][$number]; $type = $matches[1][$number];
$desc = $matches[3][$number]; $desc = $matches[3][$number];
$name = trim( $name, '$' ); $name = trim($name, '$');
$param = array( 'type' => $type, 'description' => $desc ); $param = array( 'type' => $type, 'description' => $desc );
$parsedParams[$name] = array_filter( $param ); $parsedParams[$name] = array_filter($param);
} }
}; };
@ -512,11 +547,11 @@ $HOME_DIRECTORY = '';
foreach ( $method->getParameters() as $parameter ) { foreach ( $method->getParameters() as $parameter ) {
$name = $parameter->getName(); $name = $parameter->getName();
$param = array( 'name' => $name, 'optional' => $parameter->isDefaultValueAvailable() ); $param = array( 'name' => $name, 'optional' => $parameter->isDefaultValueAvailable() );
if ( array_key_exists( $name, $parsedParams ) ) { if (array_key_exists($name, $parsedParams) ) {
$param += $parsedParams[$name]; $param += $parsedParams[$name];
} }
if ( $param['optional'] ) { if ($param['optional'] ) {
$param['default'] = $parameter->getDefaultValue(); $param['default'] = $parameter->getDefaultValue();
} }
@ -524,9 +559,9 @@ $HOME_DIRECTORY = '';
} }
// set return type // set return type
if ( preg_match( '/@return\s+([^\s]+)\s*([^\n\*]+)/', $docComment, $matches ) ) { if (preg_match('/@return\s+([^\s]+)\s*([^\n\*]+)/', $docComment, $matches) ) {
$returns = array( 'type' => $matches[1], 'description' => trim( $matches[2] ) ); $returns = array( 'type' => $matches[1], 'description' => trim($matches[2]) );
$result['services'][$methodName]['returns'] = array_filter( $returns ); $result['services'][$methodName]['returns'] = array_filter($returns);
} }
} }
} }
@ -538,37 +573,47 @@ $HOME_DIRECTORY = '';
/** /**
* Reset Local Class Vars after Execute * Reset Local Class Vars after Execute
*/ */
private function resetVars() { private function resetVars()
{
$this->response = $this->calls = array(); $this->response = $this->calls = array();
$this->hasCalls = $this->isBatchCall = false; $this->hasCalls = $this->isBatchCall = false;
} }
} }
?> ?>
<?php <?php
// Initializing // Initializing
if (!isset($NO_LOGIN)) $NO_LOGIN = false; if (!isset($NO_LOGIN)) { $NO_LOGIN = false;
if (!isset($ACCOUNTS)) $ACCOUNTS = array(); }
if (isset($USER) && isset($PASSWORD) && $USER && $PASSWORD) $ACCOUNTS[$USER] = $PASSWORD; if (!isset($ACCOUNTS)) { $ACCOUNTS = array();
if (!isset($PASSWORD_HASH_ALGORITHM)) $PASSWORD_HASH_ALGORITHM = ''; }
if (!isset($HOME_DIRECTORY)) $HOME_DIRECTORY = ''; if (isset($USER) && isset($PASSWORD) && $USER && $PASSWORD) { $ACCOUNTS[$USER] = $PASSWORD;
}
if (!isset($PASSWORD_HASH_ALGORITHM)) { $PASSWORD_HASH_ALGORITHM = '';
}
if (!isset($HOME_DIRECTORY)) { $HOME_DIRECTORY = '';
}
$IS_CONFIGURED = ($NO_LOGIN || count($ACCOUNTS) >= 1) ? true : false; $IS_CONFIGURED = ($NO_LOGIN || count($ACCOUNTS) >= 1) ? true : false;
// Utilities // Utilities
function is_empty_string($string) { function is_empty_string($string)
{
return strlen($string) <= 0; return strlen($string) <= 0;
} }
function is_equal_strings($string1, $string2) { function is_equal_strings($string1, $string2)
{
return strcmp($string1, $string2) == 0; return strcmp($string1, $string2) == 0;
} }
function get_hash($algorithm, $string) { function get_hash($algorithm, $string)
{
return hash($algorithm, trim((string) $string)); return hash($algorithm, trim((string) $string));
} }
// Command execution // Command execution
function execute_command($command) { function execute_command($command)
{
$descriptors = array( $descriptors = array(
0 => array('pipe', 'r'), // STDIN 0 => array('pipe', 'r'), // STDIN
1 => array('pipe', 'w'), // STDOUT 1 => array('pipe', 'w'), // STDOUT
@ -576,7 +621,8 @@ function execute_command($command) {
); );
$process = proc_open($command . ' 2>&1', $descriptors, $pipes); $process = proc_open($command . ' 2>&1', $descriptors, $pipes);
if (!is_resource($process)) die("Can't execute command."); if (!is_resource($process)) { die("Can't execute command.");
}
// Nothing to push to STDIN // Nothing to push to STDIN
fclose($pipes[0]); fclose($pipes[0]);
@ -594,7 +640,8 @@ function execute_command($command) {
} }
// Command parsing // Command parsing
function parse_command($command) { function parse_command($command)
{
$value = ltrim((string) $command); $value = ltrim((string) $command);
if (!is_empty_string($value)) { if (!is_empty_string($value)) {
@ -607,8 +654,9 @@ function parse_command($command) {
for ($index = $values_total - 2; $index >= 0; $index--) { for ($index = $values_total - 2; $index >= 0; $index--) {
$value_item = $values[$index]; $value_item = $values[$index];
if (substr($value_item, -1) == '\\') $value = $value_item . ' ' . $value; if (substr($value_item, -1) == '\\') { $value = $value_item . ' ' . $value;
else break; } else { break;
}
} }
} }
} }
@ -617,15 +665,18 @@ function parse_command($command) {
} }
// RPC Server // RPC Server
class WebConsoleRPCServer extends BaseJsonRpcServer { class WebConsoleRPCServer extends BaseJsonRpcServer
{
protected $home_directory = ''; protected $home_directory = '';
private function error($message) { private function error($message)
{
throw new Exception($message); throw new Exception($message);
} }
// Authentication // Authentication
private function authenticate_user($user, $password) { private function authenticate_user($user, $password)
{
$user = trim((string) $user); $user = trim((string) $user);
$password = trim((string) $password); $password = trim((string) $password);
@ -633,19 +684,23 @@ class WebConsoleRPCServer extends BaseJsonRpcServer {
global $ACCOUNTS, $PASSWORD_HASH_ALGORITHM; global $ACCOUNTS, $PASSWORD_HASH_ALGORITHM;
if (isset($ACCOUNTS[$user]) && !is_empty_string($ACCOUNTS[$user])) { if (isset($ACCOUNTS[$user]) && !is_empty_string($ACCOUNTS[$user])) {
if ($PASSWORD_HASH_ALGORITHM) $password = get_hash($PASSWORD_HASH_ALGORITHM, $password); if ($PASSWORD_HASH_ALGORITHM) { $password = get_hash($PASSWORD_HASH_ALGORITHM, $password);
}
if (is_equal_strings($password, $ACCOUNTS[$user])) if (is_equal_strings($password, $ACCOUNTS[$user])) {
return $user . ':' . get_hash('sha256', $password); return $user . ':' . get_hash('sha256', $password);
} }
} }
}
throw new Exception("Incorrect user or password"); throw new Exception("Incorrect user or password");
} }
private function authenticate_token($token) { private function authenticate_token($token)
{
global $NO_LOGIN; global $NO_LOGIN;
if ($NO_LOGIN) return true; if ($NO_LOGIN) { return true;
}
$token = trim((string) $token); $token = trim((string) $token);
$token_parts = explode(':', $token, 2); $token_parts = explode(':', $token, 2);
@ -659,7 +714,8 @@ class WebConsoleRPCServer extends BaseJsonRpcServer {
if (isset($ACCOUNTS[$user]) && !is_empty_string($ACCOUNTS[$user])) { if (isset($ACCOUNTS[$user]) && !is_empty_string($ACCOUNTS[$user])) {
$real_password_hash = get_hash('sha256', $ACCOUNTS[$user]); $real_password_hash = get_hash('sha256', $ACCOUNTS[$user]);
if (is_equal_strings($password_hash, $real_password_hash)) return $user; if (is_equal_strings($password_hash, $real_password_hash)) { return $user;
}
} }
} }
} }
@ -667,81 +723,99 @@ class WebConsoleRPCServer extends BaseJsonRpcServer {
throw new Exception("Incorrect user or password"); throw new Exception("Incorrect user or password");
} }
private function get_home_directory($user) { private function get_home_directory($user)
{
global $HOME_DIRECTORY; global $HOME_DIRECTORY;
if (is_string($HOME_DIRECTORY)) { if (is_string($HOME_DIRECTORY)) {
if (!is_empty_string($HOME_DIRECTORY)) return $HOME_DIRECTORY; if (!is_empty_string($HOME_DIRECTORY)) { return $HOME_DIRECTORY;
} }
else if (is_string($user) && !is_empty_string($user) && isset($HOME_DIRECTORY[$user]) && !is_empty_string($HOME_DIRECTORY[$user])) }
else if (is_string($user) && !is_empty_string($user) && isset($HOME_DIRECTORY[$user]) && !is_empty_string($HOME_DIRECTORY[$user])) {
return $HOME_DIRECTORY[$user]; return $HOME_DIRECTORY[$user];
}
return getcwd(); return getcwd();
} }
// Environment // Environment
private function get_environment() { private function get_environment()
{
$hostname = function_exists('gethostname') ? gethostname() : null; $hostname = function_exists('gethostname') ? gethostname() : null;
return array('path' => getcwd(), 'hostname' => $hostname); return array('path' => getcwd(), 'hostname' => $hostname);
} }
private function set_environment($environment) { private function set_environment($environment)
{
$environment = !empty($environment) ? (array) $environment : array(); $environment = !empty($environment) ? (array) $environment : array();
$path = (isset($environment['path']) && !is_empty_string($environment['path'])) ? $environment['path'] : $this->home_directory; $path = (isset($environment['path']) && !is_empty_string($environment['path'])) ? $environment['path'] : $this->home_directory;
if (!is_empty_string($path)) { if (!is_empty_string($path)) {
if (is_dir($path)) { if (is_dir($path)) {
if (!@chdir($path)) return array('output' => "Unable to change directory to current working directory, updating current directory", if (!@chdir($path)) { return array('output' => "Unable to change directory to current working directory, updating current directory",
'environment' => $this->get_environment()); 'environment' => $this->get_environment());
} }
else return array('output' => "Current working directory not found, updating current directory", }
else { return array('output' => "Current working directory not found, updating current directory",
'environment' => $this->get_environment()); 'environment' => $this->get_environment());
} }
} }
}
// Initialization // Initialization
private function initialize($token, $environment) { private function initialize($token, $environment)
{
$user = $this->authenticate_token($token); $user = $this->authenticate_token($token);
$this->home_directory = $this->get_home_directory($user); $this->home_directory = $this->get_home_directory($user);
$result = $this->set_environment($environment); $result = $this->set_environment($environment);
if ($result) return $result; if ($result) { return $result;
}
} }
// Methods // Methods
public function login($user, $password) { public function login($user, $password)
{
$result = array('token' => $this->authenticate_user($user, $password), $result = array('token' => $this->authenticate_user($user, $password),
'environment' => $this->get_environment()); 'environment' => $this->get_environment());
$home_directory = $this->get_home_directory($user); $home_directory = $this->get_home_directory($user);
if (!is_empty_string($home_directory)) { if (!is_empty_string($home_directory)) {
if (is_dir($home_directory)) $result['environment']['path'] = $home_directory; if (is_dir($home_directory)) { $result['environment']['path'] = $home_directory;
else $result['output'] = "Home directory not found: ". $home_directory; } else { $result['output'] = "Home directory not found: ". $home_directory;
}
} }
return $result; return $result;
} }
public function cd($token, $environment, $path) { public function cd($token, $environment, $path)
{
$result = $this->initialize($token, $environment); $result = $this->initialize($token, $environment);
if ($result) return $result; if ($result) { return $result;
}
$path = trim((string) $path); $path = trim((string) $path);
if (is_empty_string($path)) $path = $this->home_directory; if (is_empty_string($path)) { $path = $this->home_directory;
}
if (!is_empty_string($path)) { if (!is_empty_string($path)) {
if (is_dir($path)) { if (is_dir($path)) {
if (!@chdir($path)) return array('output' => "cd: ". $path . ": Unable to change directory"); if (!@chdir($path)) { return array('output' => "cd: ". $path . ": Unable to change directory");
}
}
else { return array('output' => "cd: ". $path . ": No such directory");
} }
else return array('output' => "cd: ". $path . ": No such directory");
} }
return array('environment' => $this->get_environment()); return array('environment' => $this->get_environment());
} }
public function completion($token, $environment, $pattern, $command) { public function completion($token, $environment, $pattern, $command)
{
$result = $this->initialize($token, $environment); $result = $this->initialize($token, $environment);
if ($result) return $result; if ($result) { return $result;
}
$scan_path = ''; $scan_path = '';
$completion_prefix = ''; $completion_prefix = '';
@ -750,18 +824,22 @@ class WebConsoleRPCServer extends BaseJsonRpcServer {
if (!empty($pattern)) { if (!empty($pattern)) {
if (!is_dir($pattern)) { if (!is_dir($pattern)) {
$pattern = dirname($pattern); $pattern = dirname($pattern);
if ($pattern == '.') $pattern = ''; if ($pattern == '.') { $pattern = '';
}
} }
if (!empty($pattern)) { if (!empty($pattern)) {
if (is_dir($pattern)) { if (is_dir($pattern)) {
$scan_path = $completion_prefix = $pattern; $scan_path = $completion_prefix = $pattern;
if (substr($completion_prefix, -1) != '/') $completion_prefix .= '/'; if (substr($completion_prefix, -1) != '/') { $completion_prefix .= '/';
} }
} }
else $scan_path = getcwd();
} }
else $scan_path = getcwd(); else { $scan_path = getcwd();
}
}
else { $scan_path = getcwd();
}
if (!empty($scan_path)) { if (!empty($scan_path)) {
// Loading directory listing // Loading directory listing
@ -770,13 +848,15 @@ class WebConsoleRPCServer extends BaseJsonRpcServer {
// Prefix // Prefix
if (!empty($completion_prefix) && !empty($completion)) { if (!empty($completion_prefix) && !empty($completion)) {
foreach ($completion as &$value) $value = $completion_prefix . $value; foreach ($completion as &$value) { $value = $completion_prefix . $value;
}
} }
// Pattern // Pattern
if (!empty($pattern) && !empty($completion)) { if (!empty($pattern) && !empty($completion)) {
// For PHP version that does not support anonymous functions (available since PHP 5.3.0) // For PHP version that does not support anonymous functions (available since PHP 5.3.0)
function filter_pattern($value) { function filter_pattern($value)
{
global $pattern; global $pattern;
return !strncmp($pattern, $value, strlen($pattern)); return !strncmp($pattern, $value, strlen($pattern));
} }
@ -788,12 +868,15 @@ class WebConsoleRPCServer extends BaseJsonRpcServer {
return array('completion' => $completion); return array('completion' => $completion);
} }
public function run($token, $environment, $command) { public function run($token, $environment, $command)
{
$result = $this->initialize($token, $environment); $result = $this->initialize($token, $environment);
if ($result) return $result; if ($result) { return $result;
}
$output = ($command && !is_empty_string($command)) ? execute_command($command) : ''; $output = ($command && !is_empty_string($command)) ? execute_command($command) : '';
if ($output && substr($output, -1) == "\n") $output = substr($output, 0, -1); if ($output && substr($output, -1) == "\n") { $output = substr($output, 0, -1);
}
return array('output' => $output); return array('output' => $output);
} }
@ -805,7 +888,7 @@ if (array_key_exists('REQUEST_METHOD', $_SERVER) && $_SERVER['REQUEST_METHOD'] =
$rpc_server->Execute(); $rpc_server->Execute();
} }
else if (!$IS_CONFIGURED) { else if (!$IS_CONFIGURED) {
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
@ -830,7 +913,7 @@ else if (!$IS_CONFIGURED) {
</div> </div>
</body> </body>
</html> </html>
<?php <?php
} }
else { ?> else { ?>
<!DOCTYPE html> <!DOCTYPE html>

View file

@ -1,6 +1,6 @@
<?php <?php
include_once('functions.php'); require_once 'functions.php';
function knownWifiStations(&$networks) function knownWifiStations(&$networks)
{ {
@ -51,7 +51,8 @@ function nearbyWifiStations(&$networks, $cached = true)
deleteCache($cacheKey); deleteCache($cacheKey);
} }
$scan_results = cache($cacheKey, function () { $scan_results = cache(
$cacheKey, function () {
exec('sudo wpa_cli -i ' . RASPI_WIFI_CLIENT_INTERFACE . ' scan'); exec('sudo wpa_cli -i ' . RASPI_WIFI_CLIENT_INTERFACE . ' scan');
sleep(3); sleep(3);
@ -59,7 +60,8 @@ function nearbyWifiStations(&$networks, $cached = true)
array_shift($stdout); array_shift($stdout);
return implode("\n", $stdout); return implode("\n", $stdout);
}); }
);
foreach (explode("\n", $scan_results) as $network) { foreach (explode("\n", $scan_results) as $network) {
$arrNetwork = preg_split("/[\t]+/", $network); // split result into array $arrNetwork = preg_split("/[\t]+/", $network); // split result into array

View file

@ -18,28 +18,28 @@
* @see http://sirlagz.net/2013/02/08/raspap-webgui/ * @see http://sirlagz.net/2013/02/08/raspap-webgui/
*/ */
require('includes/csrf.php'); require 'includes/csrf.php';
ensureCSRFSessionToken(); ensureCSRFSessionToken();
include_once('includes/config.php'); require_once 'includes/config.php';
include_once('includes/defaults.php'); require_once 'includes/defaults.php';
include_once(RASPI_CONFIG.'/raspap.php'); require_once RASPI_CONFIG.'/raspap.php';
include_once('includes/locale.php'); require_once 'includes/locale.php';
include_once('includes/functions.php'); require_once 'includes/functions.php';
include_once('includes/dashboard.php'); require_once 'includes/dashboard.php';
include_once('includes/authenticate.php'); require_once 'includes/authenticate.php';
include_once('includes/admin.php'); require_once 'includes/admin.php';
include_once('includes/dhcp.php'); require_once 'includes/dhcp.php';
include_once('includes/hostapd.php'); require_once 'includes/hostapd.php';
include_once('includes/system.php'); require_once 'includes/system.php';
include_once('includes/sysstats.php'); require_once 'includes/sysstats.php';
include_once('includes/configure_client.php'); require_once 'includes/configure_client.php';
include_once('includes/networking.php'); require_once 'includes/networking.php';
include_once('includes/themes.php'); require_once 'includes/themes.php';
include_once('includes/data_usage.php'); require_once 'includes/data_usage.php';
include_once('includes/about.php'); require_once 'includes/about.php';
include_once('includes/openvpn.php'); require_once 'includes/openvpn.php';
include_once('includes/torproxy.php'); require_once 'includes/torproxy.php';
$output = $return = 0; $output = $return = 0;
$page = $_GET['page']; $page = $_GET['page'];