remove and add some exceptions, add getUptime and fix derivedk alculation
[GitHub/Stricted/speedport-hybrid-php-api.git] / SpeedportHybrid.class.php
index 319b97d13172b6717a8b4463af0a384c722c80f5..1bcc4fbf11cc1f3c04b368b4994549939a64ef82 100644 (file)
@@ -1,10 +1,19 @@
 <?php
+require_once('RebootException.class.php');
+require_once('RouterException.class.php');
+
 /**
  * @author      Jan Altensen (Stricted)
  * @license     GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
  * @copyright   2015 Jan Altensen (Stricted)
  */
 class SpeedportHybrid {
+       /**
+        *
+        *
+        */
+       const VERSION = '1.0.2';
+       
        /**
         * password-challenge
         * @var string
@@ -27,7 +36,7 @@ class SpeedportHybrid {
         * session cookie
         * @var string
         */
-       private $session = '';
+       private $cookie = '';
        
        /**
         * router url
@@ -41,25 +50,14 @@ class SpeedportHybrid {
         */
        private $derivedk = '';
        
-       public function __construct ($password, $url = 'http://speedport.ip/') {
+       public function __construct ($url = 'http://speedport.ip/') {
                $this->url = $url;
-               $this->getChallenge();
-               
-               if (empty($this->challenge)) {
-                       throw new Exception('unable to get the challenge from the router');
-               }
-               
-               $login = $this->login($password);
-               
-               if ($login === false) {
-                       throw new Exception('unable to login');
-               }
        }
        
        /**
         * Requests the password-challenge from the router.
         */
-       public function getChallenge () {
+       private function getChallenge () {
                $path = 'data/Login.json';
                $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'challengev' => 'null');
                $data = $this->sentRequest($path, $fields);
@@ -67,7 +65,10 @@ class SpeedportHybrid {
                $data = $this->getValues($data);
                
                if (isset($data['challengev']) && !empty($data['challengev'])) {
-                       $this->challenge = $data['challengev'];
+                       return $data['challengev'];
+               }
+               else {
+                       throw new RouterExeption('unable to get the challenge from the router');
                }
        }
        
@@ -78,35 +79,24 @@ class SpeedportHybrid {
         * @return      boolean
         */
        public function login ($password) {
+               $this->challenge = $this->getChallenge();
+               
                $path = 'data/Login.json';
                $this->hash = hash('sha256', $this->challenge.':'.$password);
                $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash);
                $data = $this->sentRequest($path, $fields);
                $json = json_decode($data['body'], true);
                $json = $this->getValues($json);
+               
                if (isset($json['login']) && $json['login'] == 'success') {
-                       if (isset($data['header']['Set-Cookie']) && !empty($data['header']['Set-Cookie'])) {
-                               preg_match('/^.*(SessionID_R3=[a-z0-9]*).*/i', $data['header']['Set-Cookie'], $match);
-                               if (isset($match[1]) && !empty($match[1])) {
-                                       $this->session = $match[1];
-                               }
-                               else {
-                                       throw new Exception('unable to get the session cookie from the router');
-                               }
-                               
-                               // calculate derivedk
-                               if (version_compare(phpversion(), '5.5.0', '<')) {
-                                       require_once 'CryptLib/CryptLib.php';
-                                       $pbkdf2 = new CryptLib\Key\Derivation\PBKDF\PBKDF2();
-                                       $this->derivedk = $pbkdf2->derive(hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
-                               }
-                               else {
-                                       $this->derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
-                               }
-                               
-                               // get the csrf_token
-                               $this->token = $this->getToken();
-                               
+                       $this->cookie = $this->getCookie($data);
+                       
+                       $this->derivedk = $this->getDerviedk($password);
+                       
+                       // get the csrf_token
+                       $this->token = $this->getToken();
+                       
+                       if ($this->checkLogin(false) === true) {
                                return true;
                        }
                }
@@ -114,63 +104,135 @@ class SpeedportHybrid {
                return false;
        }
        
+       /**
+        * check if we are logged in
+        *
+        * @param       boolean $exception
+        * @return      boolean
+        */
+       public function checkLogin ($exception = true) {
+               // check if challenge or session is empty
+               if (empty($this->challenge) || empty($this->cookie)) {
+                       if ($exception === true) {
+                               throw new RouterExeption('you musst be logged in to use this method');
+                       }
+                       
+                       return false;
+               }
+               
+               $path = 'data/SecureStatus.json';
+               $fields = array();
+               $data = $this->sentRequest($path, $fields, true);
+               
+               if (empty($data['body'])) {
+                       throw new RouterExeption('unable to get SecureStatus data');
+               }
+               
+               $json = json_decode($data['body'], true);
+               $json = $this->getValues($json);
+               
+               if ($json['loginstate'] != 1) {
+                       if ($exception === true) {
+                               throw new RouterExeption('you musst be logged in to use this method');
+                       }
+                       
+                       return false;
+               }
+               
+               return true;
+       }
+       
        /**
         * logout
         * 
-        * @return      array
+        * @return      boolean
         */
        public function logout () {
-               $path = 'data/Login.json';
-               $fields = array('logout' => 'byby');
-               $data = $this->sentRequest($path, $fields);
-               // reset challenge and session
-               $this->challenge = '';
-               $this->session = '';
-               $this->token = "";
+               $this->checkLogin();
                
-               $json = json_decode($data['body'], true);
+               $path = 'data/Login.json';
+               $fields = array('csrf_token' =>  $this->token, 'logout' => 'byby');
+               $this->sentRequest($path, $fields, true);
+               if ($this->checkLogin(false) === false) {
+                       // reset challenge and session
+                       $this->challenge = '';
+                       $this->cookie = '';
+                       $this->token = '';
+                       $this->derivedk = '';
+                       
+                       return true;
+               }
                
-               return $json;
+               return false;
        }
        
        /**
         * reboot the router
         * 
-        * @return      array
+        * @return      boolean
         */
        public function reboot () {
+               $this->checkLogin();
+               
                $path = 'data/Reboot.json';
-               $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reboot_device' => 'true');
-               $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-               $data = $this->sentRequest($path, $fields, $cookie);
+               $fields = array('csrf_token' => $this->token, 'reboot_device' => 'true');
+               $data = $this->sentEncryptedRequest($path, $fields, true);
                
                $json = json_decode($data['body'], true);
+               $json = $this->getValues($json);
                
-               return $json;
+               if ($json['status'] == 'ok') {
+                       // throw an exception because router is unavailable for other tasks
+                       // like $this->logout() or $this->checkLogin
+                       throw new RebootException('Router Reboot');
+               }
+               
+               return false;
        }
        
        /**
         * change dsl connection status
         * 
         * @param       string  $status
+        * @return      boolean
         */
        public function changeConnectionStatus ($status) {
+               $this->checkLogin();
+               
                $path = 'data/Connect.json';
                
                if ($status == 'online' || $status == 'offline') {
                        $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'req_connect' => $status);
-                       $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-                       $data = $this->sentRequest($path, $fields, $cookie);
+                       $data = $this->sentRequest($path, $fields, true);
                        
-                       $json = json_decode($this->decrypt($data['body']), true);
+                       $json = json_decode($data['body'], true);
+                       $json = $this->getValues($json);
                        
-                       return $json;
+                       if ($json['status'] == 'ok') {
+                               return true;
+                       }
+                       else {
+                               return false;
+                       }
                }
                else {
-                       throw new Exception();
+                       throw new RouterExeption();
                }
        }
        
+       /**
+        * get uptime based on online (connection) time
+        *
+        * @return      string
+        */
+       public function getUptime () {
+               // TODO: search for a better solution, calling Connect.json need some time
+               $data = $this->getData('Connect');
+               $data = $this->getValues($data);
+               
+               return $data['days_online'];
+       }
+       
        /**
         * return the given json as array
         * 
@@ -178,13 +240,14 @@ class SpeedportHybrid {
         * @return      array
         */
        public function getData ($file) {
+               if ($file != 'Status') $this->checkLogin();
+               
                $path = 'data/'.$file.'.json';
                $fields = array();
-               $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-               $data = $this->sentRequest($path, $fields, $cookie);
+               $data = $this->sentRequest($path, $fields, true);
                
                if (empty($data['body'])) {
-                       throw new Exception('unable to get '.$file.' data');
+                       throw new RouterExeption('unable to get '.$file.' data');
                }
                
                $json = json_decode($data['body'], true);
@@ -198,16 +261,7 @@ class SpeedportHybrid {
         * @return      array
         */
        public function getSyslog() {
-               $path = 'data/Syslog.json';
-               $fields = array('exporttype' => '0');
-               $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-               $data = $this->sentRequest($path, $fields, $cookie);
-               
-               if (empty($data['body'])) {
-                       throw new Exception('unable to get syslog data');
-               }
-               
-               return explode("\n", $data['body']);
+               return $this->exportData('0');
        }
        
        /**
@@ -216,16 +270,7 @@ class SpeedportHybrid {
         * @return      array
         */
        public function getMissedCalls() {
-               $path = 'data/ExportMissedCalls.json';
-               $fields = array('exporttype' => '1');
-               $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-               $data = $this->sentRequest($path, $fields, $cookie);
-               
-               if (empty($data['body'])) {
-                       throw new Exception('unable to get syslog data');
-               }
-               
-               return explode("\n", $data['body']);
+               return $this->exportData('1');
        }
        
        /**
@@ -234,16 +279,7 @@ class SpeedportHybrid {
         * @return      array
         */
        public function getTakenCalls() {
-               $path = 'data/ExportTakenCalls.json';
-               $fields = array('exporttype' => '2');
-               $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-               $data = $this->sentRequest($path, $fields, $cookie);
-               
-               if (empty($data['body'])) {
-                       throw new Exception('unable to get syslog data');
-               }
-               
-               return explode("\n", $data['body']);
+               return $this->exportData('2');
        }
        
        /**
@@ -252,13 +288,23 @@ class SpeedportHybrid {
         * @return      array
         */
        public function getDialedCalls() {
-               $path = 'data/ExportDialedCalls.json';
-               $fields = array('exporttype' => '3');
-               $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-               $data = $this->sentRequest($path, $fields, $cookie);
+               return $this->exportData('3');
+       }
+       
+       /**
+        * export data from router
+        * 
+        * @return      array
+        */
+       private function exportData ($type) {
+               $this->checkLogin();
+               
+               $path = 'data/Syslog.json';
+               $fields = array('exporttype' => $type);
+               $data = $this->sentRequest($path, $fields, true);
                
                if (empty($data['body'])) {
-                       throw new Exception('unable to get syslog data');
+                       throw new RouterExeption('unable to get export data');
                }
                
                return explode("\n", $data['body']);
@@ -270,11 +316,11 @@ class SpeedportHybrid {
         * @return      array
         */
        public function reconnectLte () {
+               $this->checkLogin();
+               
                $path = 'data/modules.json';
                $fields = array('csrf_token' => $this->token, 'lte_reconn' => '1');
-               $fields = $this->encrypt($fields);
-               $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-               $data = $this->sentRequest($path, $fields, $cookie, 2);
+               $data = $this->sentEncryptedRequest($path, $fields, true);
                $json = json_decode($data['body'], true);
                
                return $json;
@@ -287,10 +333,11 @@ class SpeedportHybrid {
         * @return      array
         */
        public function resetToFactoryDefault () {
+               $this->checkLogin();
+               
                $path = 'data/resetAllSetting.json';
                $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reset_all' => 'true');
-               $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-               $data = $this->sentRequest($path, $fields, $cookie);
+               $data = $this->sentRequest($path, $fields, true);
                $json = json_decode($data['body'], true);
                
                return $json;
@@ -303,13 +350,14 @@ class SpeedportHybrid {
         * @return      array
         */
        public function checkFirmware () {
+               $this->checkLogin();
+               
                $path = 'data/checkfirmware.json';
                $fields = array('checkfirmware' => 'true');
-               $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-               $data = $this->sentRequest($path, $fields, $cookie);
+               $data = $this->sentRequest($path, $fields, true);
                
                if (empty($data['body'])) {
-                       throw new Exception('unable to get checkfirmware data');
+                       throw new RouterExeption('unable to get checkfirmware data');
                }
                
                $json = json_decode($data['body'], true);
@@ -372,12 +420,31 @@ class SpeedportHybrid {
        private function getValues($array) {
                $data = array();
                foreach ($array as $item) {
-                       $data[$item['varid']] = $item['varvalue'];
+                       if (is_array($item['varvalue'])) {
+                               $data[$item['varid']] = $this->getValues($item['varvalue']);
+                       }
+                       else {
+                               $data[$item['varid']] = $item['varvalue'];
+                       }
                }
                
                return $data;
        }
        
+       /**
+        * sends the encrypted request to router
+        * 
+        * @param       string  $path
+        * @param       mixed   $fields
+        * @param       string  $cookie
+        * @return      array
+        */
+       private function sentEncryptedRequest ($path, $fields, $cookie = false) {
+               $count = count($fields);
+               $fields = $this->encrypt($fields);
+               return $this->sentRequest($path, $fields, $cookie, $count);
+       }
+       
        /**
         * sends the request to router
         * 
@@ -387,8 +454,8 @@ class SpeedportHybrid {
         * @param       integer $count
         * @return      array
         */
-       private function sentRequest ($path, $fields, $cookie = '', $count = 0) {
-               $url = $this->url.$path;
+       private function sentRequest ($path, $fields, $cookie = false, $count = 0) {
+               $url = $this->url.$path.'?lang=en';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                
@@ -403,8 +470,8 @@ class SpeedportHybrid {
                        }
                }
                
-               if (!empty($cookie)) {
-                       curl_setopt($ch, CURLOPT_COOKIE, $cookie);
+               if ($cookie === true) {
+                       curl_setopt($ch, CURLOPT_COOKIE, 'challengev='.$this->challenge.'; '.$this->cookie);
                }
                
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@@ -421,8 +488,12 @@ class SpeedportHybrid {
                $body = substr($result, $header_size);
                curl_close($ch);
                
-               // fix invalid json
+               // check if body is encrypted (hex instead of json)
+               if (ctype_xdigit($body)) {
+                       $body = $this->decrypt($body);
+               }
                
+               // fix invalid json
                $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
                $body = preg_replace('/\'/i', '"', $body);
                $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
@@ -437,13 +508,14 @@ class SpeedportHybrid {
         * @return      string
         */
        private function getToken () {
-               $path = 'html/content/overview/index.html?lang=de';
+               $this->checkLogin();
+               
+               $path = 'html/content/overview/index.html';
                $fields = array();
-               $cookie = 'challengev='.$this->challenge.'; '.$this->session;
-               $data = $this->sentRequest($path, $fields, $cookie);
+               $data = $this->sentRequest($path, $fields, true);
                
                if (empty($data['body'])) {
-                       throw new Exception('unable to get csrf_token');
+                       throw new RouterExeption('unable to get csrf_token');
                }
                
                $a = explode('csrf_token = "', $data['body']);
@@ -453,8 +525,57 @@ class SpeedportHybrid {
                        return $a[0];
                }
                else {
-                       throw new Exception('unable to get csrf_token');
+                       throw new RouterExeption('unable to get csrf_token');
+               }
+       }
+       
+       /**
+        * calculate the derivedk
+        *
+        * @param       string  $password
+        * @return      string
+        */
+       private function getDerviedk ($password) {
+               $derivedk = '';
+               
+               // calculate derivedk
+               if (!function_exists('hash_pbkdf2')) {
+                       require_once 'CryptLib/CryptLib.php';
+                       $pbkdf2 = new CryptLib\Key\Derivation\PBKDF\PBKDF2(array('hash' => 'sha1'));
+                       $derivedk = bin2hex($pbkdf2->derive(hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32));
+                       $derivedk = substr($derivedk, 0, 32);
                }
+               else {
+                       $derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
+               }
+               
+               if (empty($derivedk)) {
+                       throw new RouterException('unable to calculate derivedk');
+               }
+               
+               return $derivedk;
+       }
+       
+       /**
+        * get cookie from header data
+        *
+        * @param       array   $data
+        * @return      string
+        */
+       private function getCookie ($data) {
+               $cookie = '';
+               if (isset($data['header']['Set-Cookie']) && !empty($data['header']['Set-Cookie'])) {
+                       preg_match('/^.*(SessionID_R3=[a-z0-9]*).*/i', $data['header']['Set-Cookie'], $match);
+                       if (isset($match[1]) && !empty($match[1])) {
+                               $cookie = $match[1];
+                       }
+               }
+               
+               if (empty($cookie)) {
+                       throw new RouterExeption('unable to get the session cookie from the router');
+               }
+               
+               return $cookie;
        }
        
        /**