From: Stricted Date: Fri, 30 Oct 2015 17:01:49 +0000 (+0100) Subject: more :D X-Git-Url: https://git.stricted.de/?a=commitdiff_plain;h=bd99ec80b08fdfbc1bdc1659115f83f038ee371f;p=GitHub%2FStricted%2FSpeedportHybridControl.git more :D --- diff --git a/SpeedportHybridControl.Implementations/Settings.cs b/SpeedportHybridControl.Implementations/Settings.cs index f98cf60..bb2434f 100644 --- a/SpeedportHybridControl.Implementations/Settings.cs +++ b/SpeedportHybridControl.Implementations/Settings.cs @@ -74,5 +74,5 @@ namespace SpeedportHybridControl.Implementations { public SettingsModel () { } - } + } } diff --git a/SpeedportHybridControl.Implementations/SpeedportHybridAPI.cs b/SpeedportHybridControl.Implementations/SpeedportHybridAPI.cs deleted file mode 100644 index 8e88fbc..0000000 --- a/SpeedportHybridControl.Implementations/SpeedportHybridAPI.cs +++ /dev/null @@ -1,872 +0,0 @@ -using Newtonsoft.Json.Linq; -using System; -using System.Linq; -using System.IO; -using System.Net; -using System.Text; -using System.Text.RegularExpressions; -using System.Windows; -using System.Threading; -using System.Collections.Generic; - -namespace SpeedportHybridControl.Implementations { - public class SpeedportHybridAPI : SingletonFactory { - public string _ip = "speedport.ip"; - private DateTime _lastReboot = DateTime.MinValue; - private bool _checkIsActive = false; - public string _password; - public string _challenge; - public string _hash; - public string _derivedk; - public CookieContainer _cookie = new CookieContainer(); - - public string ip { - get { return _ip; } - set { _ip = value; } - } - - /** - * Requests the password-challenge from the router. - * - * @return string - */ - public string getChallenge () { - string response = sendRequest("data/Login.json", "csrf_token=nulltoken&showpw=0&challengev=null"); - if (response.IsNullOrEmpty()) - return string.Empty; - - string challenge = string.Empty; - try { - JToken jArray = JToken.Parse(response); - - challenge = jArray.getVar("challengev"); - jArray = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - - return challenge; - } - - /** - * calculate the derivedk - * - * @param string $password - * @return string - */ - public string getDerviedk () { - return _password.sha256().pbkdf2(_challenge.Substring(0, 16)); - } - - /** - * login into the router with the given password - * - * @param string $password - * @return bool - */ - public bool login (string passwort) { - if (passwort.IsNullOrEmpty()) { - return false; - } - - _cookie = new CookieContainer(); - - _password = passwort; - _challenge = getChallenge(); - _hash = string.Concat(_challenge, ":", _password).sha256(); - - string response = sendRequest("data/Login.json", string.Concat("csrf_token=nulltoken&showpw=0&password=", _hash)); - if (response.IsNullOrEmpty()) - return false; - - _cookie.Add(new Cookie("challengev", _challenge) { Domain = "speedport.ip" }); - - bool login = false; - try { - JToken jArray = JToken.Parse(response); - if (jArray.getVar("login").Equals("success")) { - if (isLoggedin().Equals(false)) { - login = false; - } - else { - login = true; - _derivedk = getDerviedk(); - _lastReboot = getLastReboot(); - } - } - jArray = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - - return login; - } - - /** - * logout - * - * @return bool - */ - public bool logout () { - string response = sendRequest("data/Login.json", string.Concat("csrf_token=", getToken(), "&logout=byby")); - if (response.IsNullOrEmpty()) - return false; - - bool logout = false; - try { - JToken jArray = JToken.Parse(response); - if (jArray.getVar("status").Equals("ok")) { - if (isLoggedin().Equals(true)) { - logout = false; - } - else { - logout = true; - _password = ""; - _challenge = ""; - _cookie = new CookieContainer(); - _lastReboot = DateTime.MinValue; - _hash = ""; - _derivedk = ""; - } - } - - jArray = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - - return logout; - } - - /** - * check if we are logged in - * - * @return bool - */ - public bool checkLogin () { - // TODO: - - /* - if (_checkIsActive.Equals(false)) { - _checkIsActive = true; - if (isLoggedin().Equals(false)) { - Console.WriteLine("Session expired, try to relogin"); - - Thread.Sleep(400); - - if (login(_password).Equals(false)) { - // should we try to relogin? login(_password);... - new Thread(() => { LogManager.WriteToLog("Session expired."); }).Start(); - _password = ""; - _challenge = ""; - _cookie = new CookieContainer(); - _lastReboot = DateTime.MinValue; - _hash = ""; - _derivedk = ""; - - util.logout(); - new Thread(() => { MessageBox.Show("Session expired.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start(); - _checkIsActive = false; - return false; - } - } - - _checkIsActive = false; - } - else { - Console.WriteLine("check allready in progress"); - } - */ - - return true; - } - - /** - * check if we are logged in - * - * @param bool ischeck - * @return bool - */ - public bool isLoggedin () { - string response = sendRequest("data/SecureStatus.json"); - if (response.IsNullOrEmpty()) - return false; - - bool login = false; - try { - JToken jArray = JToken.Parse(response); - - if (jArray.getVar("loginstate").Equals("1")/* && jArray.getVar("login").Equals("true")*/) { - login = true; - } - - jArray = null; - } - - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - - return login; - } - - /** - * reboot the router - */ - public void reboot () { - // TODO: - /* - if (checkLogin().Equals(false)) - return; - - string response = sendRequest("data/Reboot.json", string.Concat("csrf_token=", Uri.EscapeUriString(getToken()), "&reboot_device=true")); - if (response.IsNullOrEmpty()) - return; - try { - JToken jArray = JToken.Parse(response); - if (jArray.getVar("status").Equals("ok")) { - new Thread(() => { MessageBox.Show("Router Reboot.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start(); - LogManager.WriteToLog("Router Reboot."); - _password = ""; - _challenge = ""; - _cookie = new CookieContainer(); - _hash = ""; - _derivedk = ""; - - util.logout(); - } - - jArray = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - */ - } - - /** - * reconnect LTE - * - * @return bool - */ - public bool reconnectLte () { - if (checkLogin().Equals(false)) - return false; - - Thread.Sleep(400); - - string response = sendEnryptedRequest("data/modules.json", string.Concat("lte_reconn=1&csrf_token=", Uri.EscapeUriString(getToken()))); - if (response.IsNullOrEmpty()) - return false; - - try { - JToken jArray = JToken.Parse(response); - - response = null; - - if (jArray.getVar("status").Equals("ok")) { - jArray = null; - return true; - } - - jArray = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - - return false; - } - - /** - * reconnect DSL - * - * @return bool - */ - public bool reconnectDSL () { - if (checkLogin().Equals(false)) - return false; - - Thread.Sleep(400); - - string response = sendEnryptedRequest("data/Connect.json", string.Concat("csrf_token=", Uri.EscapeUriString(getToken()), "&showpw=0&password=", _hash, "&req_connect=offline")); - if (response.IsNullOrEmpty()) - return false; - - bool offline = false; - try { - JToken jArray = JToken.Parse(response); - - response = null; - - if (jArray.getVar("status").Equals("ok")) { - offline = true; - } - - jArray = null; - - if (offline.Equals(true)) { - response = sendEnryptedRequest("data/Connect.json", string.Concat("csrf_token=", Uri.EscapeUriString(getToken()), "&showpw=0&password=", _hash, "&req_connect=online")); - jArray = JToken.Parse(response); - if (jArray.getVar("status").Equals("ok")) { - jArray = null; - return true; - } - } - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - - return false; - } - - /** - * change dsl connection status - * - * @param string status - * @return bool - */ - public bool changeDSLStatus (string status) { - if (checkLogin().Equals(false)) - return false; - - if (status.Equals("online") || status.Equals("offline")) { - - string response = sendEnryptedRequest("data/Connect.json", string.Concat("req_connect=", status, "&csrf_token=", Uri.EscapeUriString(getToken()))); - if (response.IsNullOrEmpty()) - return false; - try { - JToken jArray = JToken.Parse(response); - - response = null; - - if (jArray.getVar("status").Equals("ok")) { - jArray = null; - return true; - } - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - } - - return false; - } - - /** - * change lte connection status - * - * @param string status - * @return bool - */ - public bool changeLTEStatus (string status) { - if (checkLogin().Equals(false)) - return false; - - if (status.Equals("online") || status.Equals("offline")) { - if (status.Equals("online")) - status = "1"; - - if (status.Equals("offline")) - status = "0"; - - string response = sendEnryptedRequest("data/Modules.json", string.Concat("use_lte=", status, "&csrf_token=", Uri.EscapeUriString(getToken()))); - if (response.IsNullOrEmpty()) - return false; - try { - JToken jArray = JToken.Parse(response); - - response = null; - - if (jArray.getVar("status").Equals("ok")) { - jArray = null; - return true; - } - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - } - - return false; - } - - /** - * reset the router to Factory Default - * not tested - * - * @return bool - */ - public bool resetToFactoryDefault () { - if (checkLogin().Equals(false)) - return false; - - Thread.Sleep(400); - - string response = sendEnryptedRequest("data/resetAllSetting.json", string.Concat("csrf_token=nulltoken&showpw=0&password=", _hash, "&reset_all=true")); - if (response.IsNullOrEmpty()) - return false; - - try { - JToken jArray = JToken.Parse(response); - if (jArray.getVar("status").Equals("ok")) { - return true; - } - - jArray = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - - return false; - } - - /** - * check for firmware update - */ - public void checkFirmware () { - if (checkLogin().Equals(false)) - return; - - Thread.Sleep(400); - - string response = sendRequest("data/checkfirm.json"); - if (response.IsNullOrEmpty()) - return; - - try { - bool fw_isActual = false; - JToken jArray = JToken.Parse(response); - - if (jArray.getVar("fw_isActual").Equals("1")) { - fw_isActual = true; - } - - if (fw_isActual.Equals(true)) { - // Die Firmware ist aktuell. - MessageBox.Show("Die Firmware ist aktuell.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); - } - else { - // Es liegt eine neuere Firmware-Version vor. Möchten Sie diese Version jetzt installieren? - MessageBox.Show("Es liegt eine neuere Firmware-Version vor.\nMöchten Sie diese Version jetzt installieren?", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Warning); - } - - jArray = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - } - - /** - * flush dns cache - */ - public void flushDNS () { - if (checkLogin().Equals(false)) - return; - - Thread.Sleep(400); - - string response = sendEnryptedRequest("data/dns.json", "op_type=flush_dns_cache"); - if (response.IsNullOrEmpty()) - return; - - try { - JToken jArray = JToken.Parse(response); - - if (jArray["DCI"].Count().Equals(0)) { - new Thread(() => { MessageBox.Show("DNS cache geleert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start(); - } - else { - new Thread(() => { MessageBox.Show("unable to flush dns cache", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start(); - } - - - jArray = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - } - - /** - * clear the Syslog - */ - public void clearSyslog () { - if (checkLogin().Equals(false)) - return; - - Thread.Sleep(400); - - string response = sendEnryptedRequest("data/SystemMessages.json", string.Concat("action_clearlist=true&clear_type=0&", "csrf_token=", getToken())); - if (response.IsNullOrEmpty()) - return; - - try { - JToken jArray = JToken.Parse(response); - - if (jArray.getVar("status").Equals("ok")) { - // ok - new Thread(() => { MessageBox.Show("Syslog geleert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start(); - } - else { - // fail - new Thread(() => { MessageBox.Show("Konnte Syslog nicht leeren.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start(); - } - - jArray = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - } - - /** - * set QueueSkbTimeOut - * - * @param string value - */ - public void setQueueSkbTimeOut (string value) { - // TODO: - /* - if (checkLogin().Equals(false)) - return; - - string response = sendEnryptedRequest("data/bonding_tr181.json", string.Concat("bonding_QueueSkbTimeOut=", value)); - if (response.IsNullOrEmpty()) - return; - try { - TR181 obj = JsonConvert.DeserializeObject(response); - - if (obj.QueueSkbTimeOut.Equals(value)) { - new Thread(() => { MessageBox.Show("QueueSkbTimeOut geändert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start(); - } - else { - new Thread(() => { MessageBox.Show("unable to change QueueSkbTimeOut", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start(); - } - - obj = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - */ - } - - /** - * set Antenna Mode - * - * @param string value - */ - public void setAntennaMode (string value) { - // TODO: - /* - if (checkLogin().Equals(false)) - return; - - string response = sendEnryptedRequest("data/lteinfo.json", string.Concat("mode_select=", value)); - if (response.IsNullOrEmpty()) - return; - try { - LTE obj = JsonConvert.DeserializeObject(response); - - string antenna_mode; - if (obj.antenna_mode.Equals("Antennal set to internal")) { - antenna_mode = "Inner"; - } - else if (obj.antenna_mode.Equals("Antennal set to external")) { - antenna_mode = "Outer"; - } - else { - antenna_mode = "Auto"; - } - - if (antenna_mode.Equals(value)) { - new Thread(() => { MessageBox.Show("Antennen Modus geändert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start(); - } - else { - new Thread(() => { MessageBox.Show("Antennen Modus ändern Fehlgeschlagen", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start(); - } - - antenna_mode = null; - - obj = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - response = null; - */ - } - - /** - * get Last Reboot time - * - * @return DateTime - */ - public DateTime getLastReboot () { - if (_lastReboot.Equals(DateTime.MinValue).Equals(false)) { - return _lastReboot; - } - - string response = sendRequest("data/Reboot.json"); - - if (response.IsNullOrEmpty()) - return DateTime.Now; - - JToken jArray = JToken.Parse(response); - - DateTime lastReboot = DateTime.Parse(string.Concat(jArray.getVar("reboot_date"), " ", jArray.getVar("reboot_time"))); - - jArray = null; - - return lastReboot; - } - - /** - * get the csrf token from router - * - * @return string - */ - public string getToken () { - string response = sendRequest("html/content/overview/index.html"); - if (response.IsNullOrEmpty()) - return string.Empty; - - string a = "csrf_token = \""; - string b = "\";"; - string token = response.Substring((response.IndexOf(a) + a.Length), (response.IndexOf(b) - response.IndexOf(a) - a.Length)); - - response = null; - a = null; - b = null; - - Console.WriteLine("csrf_token: " + token); - return token; - } - - /** - * send encrypted request to the router - * - * @param string path - * @param string post - * @param bool cookie - * @return string - */ - public string sendEnryptedRequest (string path, string post = "", bool cookie = true) { - string response = string.Empty; - - try { - sjcl sjcl = new sjcl(); - - string iv = _challenge.Substring(16, 16); - string adata = _challenge.Substring(32, 16); - string dKey = _derivedk; - - - // TODO: check if we need this really? - if (post.IsNullOrEmpty().Equals(false)) { - post = sjcl.encrypt(dKey, post, iv, adata); - } - - - response = sendRequest(path, post, cookie); - // check if the return value is hex (hex = enrypted) - if (Regex.IsMatch(response, @"\A\b[0-9a-fA-F]+\b\Z").Equals(true)) { - response = sjcl.decrypt(dKey, response, iv, adata); - } - - post = null; - iv = null; - adata = null; - dKey = null; - sjcl = null; - - } - catch (ArgumentOutOfRangeException ex) { - LogManager.WriteToLog(ex.Message); - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - return response; - } - - /** - * send request to the router - * - * @param string path - * @param string post - * @param bool cookie - * @return string - */ - public string sendRequest (string path, string post = "", bool cookie = true) { - string response = string.Empty; - try { - string url = string.Concat("http://", ip, "/", path, "?lang=de"); - - HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; - /* set timeout to 10 seconds */ - webRequest.Timeout = 10000; - - if (cookie.Equals(true)) { - webRequest.CookieContainer = _cookie; - } - - if (post.IsNullOrEmpty().Equals(false)) { - webRequest.Method = "POST"; - byte[] dataStream = Encoding.UTF8.GetBytes(post); - webRequest.ContentLength = dataStream.Length; - Stream newStream = webRequest.GetRequestStream(); - newStream.Write(dataStream, 0, dataStream.Length); - newStream.Close(); - newStream.Dispose(); - newStream = null; - dataStream = null; - } - - WebResponse webResponse = webRequest.GetResponse(); - StreamReader reader = new StreamReader(webResponse.GetResponseStream()); - response = reader.ReadToEnd().ToString(); - - webResponse.Dispose(); - reader.Dispose(); - reader = null; - webRequest = null; - webResponse = null; - post = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - return response; - } - - public string sendRequest2 (string path, Dictionary files, string post = "", bool cookie = true) { - string response = string.Empty; - - try { - string url = string.Concat("http://", ip, "/", path, "?lang=de"); - - string boundary = string.Concat("---------------------------", DateTime.Now.Ticks.ToString("x")); - byte[] boundaryBytes = Encoding.ASCII.GetBytes(string.Concat("\r\n--", boundary, "\r\n")); - - HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; - request.ContentType = string.Concat("multipart/form-data; boundary=", boundary); - request.Method = "POST"; - request.KeepAlive = true; - - if (cookie.Equals(true)) { - request.CookieContainer = _cookie; - } - - Stream requestStream = request.GetRequestStream(); - - if (string.IsNullOrEmpty(post).Equals(false)) { - byte[] dataStream = Encoding.UTF8.GetBytes(post); - requestStream.Write(dataStream, 0, dataStream.Length); - dataStream = null; - } - - if (files != null && files.Count > 0) { - foreach (KeyValuePair pair in files) { - requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); - if (pair.Value is FormFile) { - FormFile file = pair.Value as FormFile; - string header = string.Concat("Content-Disposition: form-data; name=\"", pair.Key, "\"; filename=\"", file.Name, "\"\r\nContent-Type: ", file.ContentType, "\r\n\r\n"); - byte[] bytes = Encoding.UTF8.GetBytes(header); - requestStream.Write(bytes, 0, bytes.Length); - byte[] buffer = new byte[32768]; - int bytesRead; - if (file.Stream == null) { - // upload from file - FileStream fileStream = File.OpenRead(file.FilePath); - while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { - requestStream.Write(buffer, 0, bytesRead); - } - fileStream.Close(); - } - else { - // upload from given stream - while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0) - requestStream.Write(buffer, 0, bytesRead); - } - } - else { - string data = string.Concat("Content-Disposition: form-data; name=\"", pair.Key, "\"\r\n\r\n", pair.Value); - byte[] bytes = Encoding.UTF8.GetBytes(data); - requestStream.Write(bytes, 0, bytes.Length); - } - } - - byte[] trailer = Encoding.ASCII.GetBytes(string.Concat("\r\n--", boundary, "--\r\n")); - requestStream.Write(trailer, 0, trailer.Length); - requestStream.Close(); - - } - - WebResponse webResponse = request.GetResponse(); - Stream responseStream = webResponse.GetResponseStream(); - StreamReader reader = new StreamReader(responseStream); - response = reader.ReadToEnd(); - - webResponse.Dispose(); - reader.Dispose(); - reader = null; - request = null; - webResponse = null; - } - catch (Exception ex) { - LogManager.WriteToLog(ex.Message); - } - - return response; - } - } - - public class FormFile { - public string Name { get; set; } - - public string ContentType { get; set; } - - public string FilePath { get; set; } - - public Stream Stream { get; set; } - } -} \ No newline at end of file diff --git a/SpeedportHybridControl.Implementations/SpeedportHybridControl.Implementations.csproj b/SpeedportHybridControl.Implementations/SpeedportHybridControl.Implementations.csproj index 5312a9a..ea9fc19 100644 --- a/SpeedportHybridControl.Implementations/SpeedportHybridControl.Implementations.csproj +++ b/SpeedportHybridControl.Implementations/SpeedportHybridControl.Implementations.csproj @@ -62,7 +62,6 @@ - diff --git a/SpeedportHybridControl.Implementations/sjcl.cs b/SpeedportHybridControl.Implementations/sjcl.cs index 53b31e8..fd67089 100644 --- a/SpeedportHybridControl.Implementations/sjcl.cs +++ b/SpeedportHybridControl.Implementations/sjcl.cs @@ -1,7 +1,7 @@ using Noesis.Javascript; namespace SpeedportHybridControl.Implementations { - class sjcl { + public class sjcl { private string jssjcl; public sjcl () { jssjcl = string.Concat( diff --git a/SpeedportHybridControl/Data/SpeedportHybrid.cs b/SpeedportHybridControl/Data/SpeedportHybrid.cs new file mode 100644 index 0000000..fac5cdb --- /dev/null +++ b/SpeedportHybridControl/Data/SpeedportHybrid.cs @@ -0,0 +1,812 @@ +using System; +using Newtonsoft.Json; +using System.Collections.Generic; +using Newtonsoft.Json.Linq; +using System.Linq; +using System.Windows; +using SpeedportHybridControl.Model; +using SpeedportHybridControl.Implementations; + +namespace SpeedportHybridControl.Data { + public class SpeedportHybrid { + public SpeedportHybrid() { } + + public static void initOverview () { + try { + if (SpeedportHybridAPI.getInstance().checkLogin().Equals(false)) + return; + + OverviewModel overview = Application.Current.FindResource("OverviewModel") as OverviewModel; + + string response = SpeedportHybridAPI.getInstance().sendEnryptedRequest("data/Overview.json"); + if (response.IsNullOrEmpty()) + return; + + JToken jArray = JToken.Parse(response); + response = null; + + DateTime time = DateTime.Now; + string format = "dd.MM.yyyy HH:mm:ss"; + + string onlinestatus = jArray.getVar("onlinestatus"); + if (onlinestatus.Equals("offline")) { + overview.onlinestatus = "DSL-Verbindung getrennt"; + } + else if (onlinestatus.Equals("disabled")) { + overview.onlinestatus = "DSL-Verbindung gesperrt"; + } + else if (onlinestatus.Equals("online")) { + overview.onlinestatus = "DSL-Verbindung aktiv"; + } + else if (onlinestatus.Equals("fail")) { + overview.onlinestatus = "DSL-Verbindung getrennt"; + } + else { + overview.onlinestatus = "DSL-Verbindung nicht eingerichtet"; + } + + if (jArray.getVar("dsl_link_status").Equals("online")) { + overview.dsl_link_status = "DSL-Link synchron"; + } + else { + overview.dsl_link_status = "DSL-Link nicht synchron"; + } + + overview.lte_image = string.Concat("../assets/lte", jArray.getVar("lte_signal"), ".png"); + + if (onlinestatus.Equals("online") || jArray.getVar("gre_status").Equals("1")) { + bool chk = true; + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("addipnumber")) { + if (jToken["varvalue"].getVar("number_status").Equals("ok").Equals(false)) { + chk = false; + } + } + + varid = null; + } + + if (chk.Equals(true)) { + overview.number_status = "Internet Telefonie aktiv"; + } + else { + overview.number_status = "Internet Telefonie aus"; + } + } + else { + overview.number_status = "Telefonie nicht nutzbar"; + } + + if (jArray.getVar("use_dect").Equals("0")) { + overview.use_dect = "DECT-Basisstation aus"; + } + else { + overview.use_dect = "DECT-Basisstation an"; + } + + int c = 0; + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("adddect")) { + c++; + } + + varid = null; + } + + if (c.Equals(1)) { + overview.dect_devices = "1 angemeldetes Schnurlostelefon"; + } + else { + overview.dect_devices = string.Concat(c.ToString(), " angemeldete Schnurlostelefone"); + } + + int wc = 0; + if (jArray.getVar("use_wlan").Equals("1")) { + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("addmdevice")) { + if (jToken["varvalue"].getVar("mdevice_type").Equals("1") && jToken["varvalue"].getVar("mdevice_connected").Equals("1")) { + wc++; + } + } + + varid = null; + } + } + + if (jArray.getVar("use_wlan_5ghz").Equals("1")) { + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("addmdevice")) { + if (jToken["varvalue"].getVar("mdevice_type").Equals("2") && jToken["varvalue"].getVar("mdevice_connected").Equals("1")) { + wc++; + } + } + + varid = null; + } + } + + int lc = 0; + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("addmdevice")) { + if (jToken["varvalue"].getVar("mdevice_type").Equals("0") && jToken["varvalue"].getVar("mdevice_connected").Equals("1")) { + lc++; + } + } + + varid = null; + } + + int uc = 0; + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("addotherdevice")) { + if (jToken["varvalue"].getVar("nas_device_connection").Equals("USB")) { + uc++; + } + } + + varid = null; + } + + overview.devices = string.Concat(wc.ToString(), " an WLAN, ", lc.ToString(), " an LAN, ", uc.ToString(), " an USB"); + + if (jArray.getVar("use_wlan").Equals("1")) { + overview.use_wlan = "2,4-GHz-Frequenzband an"; + } + else { + overview.use_wlan = "2,4-GHz-Frequenzband aus"; + } + + if (jArray.getVar("use_wlan_5ghz").Equals("1")) { + overview.use_wlan_5ghz = "5-GHz-Frequenzband an"; + } + else { + overview.use_wlan_5ghz = "5-GHz-Frequenzband aus"; + } + + if (jArray.getVar("wlan_enc").Equals("0")) { + overview.wlan_enc = "WLAN unverschlüsselt"; + } + else { + overview.wlan_enc = "WLAN verschlüsselt"; + } + + if (jArray.getVar("wlan_power").Equals("0")) { + overview.wlan_power = "Sendeleistung hoch"; + } + else if (jArray.getVar("wlan_power").Equals("1")) { + overview.wlan_power = "Sendeleistung mittel"; + } + else { + overview.wlan_power = "Sendeleistung niedrig"; + } + + int ec = 0; + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("addotherdevice")) { + if (jToken["varvalue"].getVar("nas_device_type").Equals("NAS")) { + ec++; + } + } + + varid = null; + } + + if (ec.Equals(1)) { + overview.external_devices = "1 externer Datenträger verfügbar"; + } + else { + overview.external_devices = string.Concat(ec.ToString(), " externe Datenträger verfügbar"); + } + + if (jArray.getVar("nas_sync_active").Equals("true")) { + overview.nas_sync_active = "Ordner synchronisieren an"; + } + else { + overview.nas_sync_active = "Ordner synchronisieren aus"; + } + + if (jArray.getVar("nas_backup_active").Equals("true")) { + overview.nas_backup_active = "Daten sichern an"; + } + else { + overview.nas_backup_active = "Daten sichern aus"; + } + + if (jArray.getVar("mc_password").IsNullOrEmpty()) { + overview.mc_state = "Verbindung mit Mediencenter nicht eingerichtet"; + } + else { + if (jArray.getVar("mc_allow_connect").Equals("0")) { + overview.mc_state = "Verbindung mit Mediencenter nicht erlaubt"; + } + else { + if (jArray.getVar("mc_login_success").Equals("1")) { + overview.mc_state = "Verbindung mit Mediencenter eingerichtet"; + } + else { + overview.mc_state = "Verbindung mit Mediencenter fehlgeschlagen"; + } + } + } + + // overview.days_online = ""; // TODO + + overview.datetime = time.ToString(format); + + jArray = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + } + + public static void initTR181 () { + try { + if (SpeedportHybridAPI.getInstance().checkLogin().Equals(false)) + return; + + TR181 tr181 = Application.Current.FindResource("TR181") as TR181; + + string response = SpeedportHybridAPI.getInstance().sendEnryptedRequest("data/bonding_tr181.json"); + if (response.IsNullOrEmpty()) + return; + + TR181 obj = JsonConvert.DeserializeObject(response); + response = null; + + tr181.enable1 = obj.enable1; + tr181.status1 = obj.status1; + tr181.mode = obj.mode; + tr181.servername = obj.servername; + tr181.severip = obj.severip; + tr181.bw = obj.bw; + tr181.errorinfo = obj.errorinfo; + tr181.hellostatus = obj.hellostatus; + tr181.QueueSkbTimeOut = obj.QueueSkbTimeOut; + + response = SpeedportHybridAPI.getInstance().sendEnryptedRequest("data/bonding_tunnel.json"); + + obj = JsonConvert.DeserializeObject(response); + response = null; + + tr181.lte_tunnel = obj.lte_tunnel; + tr181.dsl_tunnel = obj.dsl_tunnel; + tr181.bonding = obj.bonding; + + response = SpeedportHybridAPI.getInstance().sendEnryptedRequest("data/bonding_client.json"); + bonding_client obj2 = JsonConvert.DeserializeObject(response); + + tr181.bypass_up_bw = obj2.hybrid_show[4].bypass_up_bw; + tr181.bypass_dw_bw = obj2.hybrid_show[4].bypass_dw_bw; + tr181.bypass_up_rb = obj2.hybrid_show[4].bypass_up_rb; + tr181.bypass_dw_rb = obj2.hybrid_show[4].bypass_dw_rb; + tr181.bypass_check = obj2.hybrid_show[4].bypass_check; + + DateTime time = DateTime.Now; + string format = "dd.MM.yyyy HH:mm:ss"; + tr181.datetime = time.ToString(format); + + obj = null; + obj2 = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + } + + public static void initLTE (bool popup = false) { + try { + if (SpeedportHybridAPI.getInstance().checkLogin().Equals(false)) + return; + + LTE lte = null; + if (popup.Equals(true)) { + lte = Application.Current.FindResource("LTE2") as LTE; + } + else { + lte = Application.Current.FindResource("LTE") as LTE; + } + + string response = SpeedportHybridAPI.getInstance().sendEnryptedRequest("data/lteinfo.json"); + if (response.IsNullOrEmpty()) + return; + + LTE obj = JsonConvert.DeserializeObject(response); + response = null; + + lte.imei = obj.imei; + lte.imsi = obj.imsi; + lte.device_status = obj.device_status; + lte.card_status = obj.card_status; + lte.antenna_mode = obj.antenna_mode; + + if (obj.antenna_mode.Equals("Antennal set to internal")) { + lte.antenna_mode2 = "Inner"; + } + else if (obj.antenna_mode.Equals("Antennal set to external")) { + lte.antenna_mode2 = "Outer"; + } + else { + lte.antenna_mode2 = "Auto"; + } + + lte.phycellid = obj.phycellid; + lte.cellid = obj.cellid; + lte.rsrp = obj.rsrp; + lte.rsrp_bg = util.getRSRPColor(obj.rsrp.ToInt()); + lte.rsrq = obj.rsrq; + lte.rsrq_bg = util.getRSRQColor(obj.rsrq.ToInt()); + lte.service_status = obj.service_status; + lte.tac = obj.tac; + + DateTime time = DateTime.Now; + string format = "dd.MM.yyyy HH:mm:ss"; + lte.datetime = time.ToString(format); + if (popup.Equals(false)) { + initSyslog(true); + } + + obj = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + } + + public static void initDSL () { + if (SpeedportHybridAPI.getInstance().checkLogin().Equals(false)) + return; + + DSLViewModel dsl = Application.Current.FindResource("DSL") as DSLViewModel; + + string response = SpeedportHybridAPI.getInstance().sendEnryptedRequest("data/dsl.json"); + if (response.IsNullOrEmpty()) + return; + + try { + DSLViewModel obj = JsonConvert.DeserializeObject(response); + + double difference = Math.Ceiling((DateTime.Now - SpeedportHybridAPI.getInstance().getLastReboot()).TotalSeconds) / 60; + + obj.Line.uCRCsec = Math.Ceiling(obj.Line.uCRC / difference); + obj.Line.dCRCsec = Math.Ceiling(obj.Line.dCRC / difference); + + obj.Line.uHECsec = Math.Ceiling(obj.Line.uHEC / difference); + obj.Line.dHECsec = Math.Ceiling(obj.Line.dHEC / difference); + + obj.Line.uFECsec = Math.Ceiling(obj.Line.uFEC / difference); + obj.Line.dFECsec = Math.Ceiling(obj.Line.dFEC / difference); + + dsl.Connection = obj.Connection; + dsl.Line = obj.Line; + + DateTime time = DateTime.Now; + string format = "dd.MM.yyyy HH:mm:ss"; + dsl.datetime = time.ToString(format); + + obj = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + } + + public static void initStatus() { + try { + Status status = Application.Current.FindResource("Status") as Status; + string response = SpeedportHybridAPI.getInstance().sendRequest("data/status.json"); + if (response.IsNullOrEmpty()) + return; + + JToken jArray = JToken.Parse(response); + response = null; + + DateTime time = DateTime.Now; + string format = "dd.MM.yyyy HH:mm:ss"; + string ltesignal = jArray.getVar("lte_signal"); + + status.device_name = jArray.getVar("device_name"); + + if (jArray.getVar("use_lte").Equals("0")) { + status.lte_status = "Deaktiviert"; + } + else { + if (jArray.getVar("lte_status").Equals("10") || jArray.getVar("lte_status").Equals("11")) { + status.lte_status = "Aktiv"; + } + else { + status.lte_status = "Nicht aktiv"; + } + } + + status.lte_signal = string.Concat(ltesignal.ToInt() * 20, " %"); + status.lte_image = string.Concat("../assets/lte", ltesignal, ".png"); + status.datetime = time.ToString(format); + status.imei = jArray.getVar("imei"); + + if (jArray.getVar("dsl_link_status").Equals("online")) { + status.dsl_link_status = "Synchron"; + } + else { + status.dsl_link_status = "Nicht synchron"; // check size + } + + if (jArray.getVar("status").Equals("online")) { + status.status = "Aktiv"; + } + else { + status.status = "Getrennt"; + } + + status.dsl_downstream = string.Concat(jArray.getVar("dsl_downstream"), " kBit/s"); + status.dsl_upstream = string.Concat(jArray.getVar("dsl_upstream"), " kBit/s"); + + List statusPhoneList = new List(); + status.addphonenumber = null; + + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("addphonenumber")) { + string pnumber = jToken["varvalue"].getVar("phone_number"); + string pstatus = string.Empty; + if (jToken["varvalue"].getVar("status").Equals("ok")) { + pstatus = "Aktiv"; + } + else { + pstatus = "Nicht aktiv"; + } + + statusPhoneList.Add(new StatusPhoneList() { number = pnumber, status = pstatus }); + } + } + + status.addphonenumber = statusPhoneList; + + if (jArray.getVar("use_dect").Equals("0")) { + status.use_dect = "Nicht aktiv"; + } + else { + status.use_dect = "Aktiv"; + } + + int c = 0; + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("adddect")) { + c++; + } + } + + status.dect_devices = c.ToString(); + + status.wlan_ssid = jArray.getVar("wlan_ssid"); + status.wlan_5ghz_ssid = jArray.getVar("wlan_5ghz_ssid"); + + if (jArray.getVar("use_wlan").Equals("0")) { + status.use_wlan = "Aus"; + } + else { + status.use_wlan = "Eingeschaltet"; + } + + if (jArray.getVar("use_wlan_5ghz").Equals("0")) { + status.use_wlan_5ghz = "Aus"; + } + else { + status.use_wlan_5ghz = "Eingeschaltet"; + } + + status.wlan_devices = jArray.getVar("wlan_devices"); + status.wlan_5ghz_devices = jArray.getVar("wlan_5ghz_devices"); + if (jArray.getVar("lan1_device").Equals("1")) { + status.lan1_device = "../assets/check.png"; + } + else { + status.lan1_device = "../assets/x.png"; + } + + if (jArray.getVar("lan2_device").Equals("1")) { + status.lan2_device = "../assets/check.png"; + } + else { + status.lan2_device = "../assets/x.png"; + } + + if (jArray.getVar("lan3_device").Equals("1")) { + status.lan3_device = "../assets/check.png"; + } + else { + status.lan3_device = "../assets/x.png"; + } + + if (jArray.getVar("lan4_device").Equals("1")) { + status.lan4_device = "../assets/check.png"; + } + else { + status.lan4_device = "../assets/x.png"; + } + + if (jArray.getVar("hsfon_status").Equals("2")) { + status.hsfon_status = "Aktiv"; + } + else { + status.hsfon_status = "Aus"; + } + + status.firmware_version = jArray.getVar("firmware_version"); + status.serial_number = jArray.getVar("serial_number"); + + + double difference = (DateTime.Now - SpeedportHybridAPI.getInstance().getLastReboot()).TotalSeconds; + TimeSpan uptime = TimeSpan.FromSeconds(difference); + status.uptime = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", uptime.Days, uptime.Hours, uptime.Minutes, uptime.Seconds); + + jArray = null; + statusPhoneList = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + } + + public static void initSyslog (bool isLTE = false) { + try { + if (SpeedportHybridAPI.getInstance().checkLogin().Equals(false)) + return; + + SyslogData syslog = Application.Current.FindResource("SyslogData") as SyslogData; + + string response = SpeedportHybridAPI.getInstance().sendEnryptedRequest("data/SystemMessages.json"); + if (response.IsNullOrEmpty()) + return; + + JToken jArray = JToken.Parse(response); + response = null; + + List syslogList = new List(); + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("addmessage")) { + var a = jToken["varvalue"]; + var stamp = a[1]["varvalue"]; + var msg = a[2]["varvalue"]; + + // login + if (msg.ToString().Contains("(G101)").Equals(true)) + continue; + + // logout + if (msg.ToString().Contains("(G102)").Equals(true)) + continue; + + // session timeout + if (msg.ToString().Contains("(G103)").Equals(true)) + continue; + + // dnsv6 error + if (msg.ToString().Contains("(P008)").Equals(true)) + continue; + + // Funkzellen Info + if (msg.ToString().Contains("(LT004)") && isLTE.Equals(true)) { + LTE lte = Application.Current.FindResource("LTE") as LTE; + //LTE lte2 = Application.Current.FindResource("LTE2") as LTE; + + string[] parts = msg.ToString().Split(','); + string frequenz = parts[2]; + + if (frequenz.Equals("20")) { + frequenz = "800 MHz"; + } + else if (frequenz.Equals("3")) { + frequenz = "1800 MHz"; + } + else if (frequenz.Equals("7")) { + frequenz = "2600 MHz"; + } + + lte.frequenz = frequenz; + //lte2.frequenz = frequenz; + + varid = null; + jArray = null; + a = null; + stamp = null; + msg = null; + syslogList = null; + return; + } + + syslogList.Add(new SyslogList() { timestamp = stamp.ToString(), message = msg.ToString() }); + + a = null; + stamp = null; + msg = null; + } + varid = null; + } + + syslog.syslogList = syslogList; + syslogList = null; + jArray = null; + + DateTime time = DateTime.Now; + string format = "dd.MM.yyyy HH:mm:ss"; + syslog.datetime = time.ToString(format); + + syslog = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + } + + public static void initPhone() { + try { + if (SpeedportHybridAPI.getInstance().checkLogin().Equals(false)) + return; + + PhoneCallData phone = Application.Current.FindResource("PhoneCallData") as PhoneCallData; + + List missedCalls = new List(); + List takenCalls = new List(); + List dialedCalls = new List(); + + string response = SpeedportHybridAPI.getInstance().sendEnryptedRequest("data/PhoneCalls.json"); + if (response.IsNullOrEmpty()) + return; + + JToken jArray = JToken.Parse(response); + response = null; + + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("addmissedcalls")) { + JToken a = jToken["varvalue"]; + int _id = a[0]["varvalue"].ToString().ToInt(); + string _date = a[1]["varvalue"].ToString(); + string _time = a[2]["varvalue"].ToString(); + string _who = a[3]["varvalue"].ToString(); + + missedCalls.Add(new PhoneCallList() { id = _id, date = _date, time = _time, who = _who }); + a = null; + _id = 0; + _date = null; + _time = null; + _who = null; + } + else if (varid.ToString().Equals("addtakencalls")) { + JToken a = jToken["varvalue"]; + int _id = a[0]["varvalue"].ToString().ToInt(); + string _date = a[1]["varvalue"].ToString(); + string _time = a[2]["varvalue"].ToString(); + string _who = a[3]["varvalue"].ToString(); + string _duration = a[4]["varvalue"].ToString(); + + takenCalls.Add(new PhoneCallList() { id = _id, date = _date, time = _time, who = _who, duration = _duration }); + a = null; + _id = 0; + _date = null; + _time = null; + _who = null; + _duration = null; + } + else if (varid.ToString().Equals("adddialedcalls")) { + JToken a = jToken["varvalue"]; + int _id = a[0]["varvalue"].ToString().ToInt(); + string _date = a[1]["varvalue"].ToString(); + string _time = a[2]["varvalue"].ToString(); + string _who = a[3]["varvalue"].ToString(); + string _duration = a[4]["varvalue"].ToString(); + + dialedCalls.Add(new PhoneCallList() { id = _id, date = _date, time = _time, who = _who, duration = _duration }); + a = null; + _id = 0; + _date = null; + _time = null; + _who = null; + _duration = null; + } + + varid = null; + } + + // sort calls + missedCalls.Sort((x, y) => y.id.CompareTo(x.id)); + takenCalls.Sort((x, y) => y.id.CompareTo(x.id)); + dialedCalls.Sort((x, y) => y.id.CompareTo(x.id)); + + missedCalls.OrderBy(x => x.time).ThenBy(x => x.date); + + phone.missedCalls = missedCalls; + phone.takenCalls = takenCalls; + phone.dialedCalls = dialedCalls; + + missedCalls = null; + takenCalls = null; + dialedCalls = null; + jArray = null; + + DateTime time = DateTime.Now; + string format = "dd.MM.yyyy HH:mm:ss"; + phone.datetime = time.ToString(format); + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + } + + public static void initLan () { + try { + if (SpeedportHybridAPI.getInstance().checkLogin().Equals(false)) + return; + + DeviceData deviceData = Application.Current.FindResource("DeviceData") as DeviceData; + + List deviceList = new List(); + + string response = SpeedportHybridAPI.getInstance().sendEnryptedRequest("data/LAN.json"); + if (response.IsNullOrEmpty()) + return; + + JToken jArray = JToken.Parse(response); + response = null; + + string ipv6_prefix = jArray.getVar("lan_ip_v6_prefix"); + string ipv6_range = jArray.getVar("lan_ip_v6_range"); + + foreach (JToken jToken in jArray) { + JToken varid = jToken["varid"]; + if (varid.ToString().Equals("addmdevice")) { + int id = jToken["varvalue"].getVar("id").ToInt(); + string name = jToken["varvalue"].getVar("mdevice_name"); + string mac = jToken["varvalue"].getVar("mdevice_mac"); + int type = jToken["varvalue"].getVar("mdevice_type").ToInt(); // 0 = lan, 1/2 = wlan + int connected = jToken["varvalue"].getVar("mdevice_connected").ToInt(); + string ipv4 = jToken["varvalue"].getVar("mdevice_ipv4"); + string ipv6 = jToken["varvalue"].getVar("mdevice_ipv6"); + int mstatic = jToken["varvalue"].getVar("mdevice_static").ToInt(); + + ipv6 = string.Concat(ipv6_prefix, ipv6_range, ":", ipv6); + + deviceList.Add(new DeviceList() { id = id, name = name, mac = mac, type = type, connected = connected, ipv4 = ipv4, ipv6 = ipv6, mstatic = mstatic }); + + id = 0; + name = null; + mac = null; + type = 0; + connected = 0; + ipv4 = null; + ipv6 = null; + mstatic = 0; + } + + varid = null; + } + + deviceData.deviceList = deviceList; + + jArray = null; + ipv6_prefix = null; + ipv6_range = null; + deviceList = null; + + DateTime time = DateTime.Now; + string format = "dd.MM.yyyy HH:mm:ss"; + deviceData.datetime = time.ToString(format); + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + } + } +} diff --git a/SpeedportHybridControl/Data/SpeedportHybridAPI.cs b/SpeedportHybridControl/Data/SpeedportHybridAPI.cs new file mode 100644 index 0000000..800c921 --- /dev/null +++ b/SpeedportHybridControl/Data/SpeedportHybridAPI.cs @@ -0,0 +1,865 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Linq; +using System.IO; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Windows; +using System.Threading; +using System.Collections.Generic; +using SpeedportHybridControl.Implementations; +using SpeedportHybridControl.Model; +using Newtonsoft.Json; + +namespace SpeedportHybridControl.Data { + public class SpeedportHybridAPI : SingletonFactory { + public string _ip = "speedport.ip"; + private DateTime _lastReboot = DateTime.MinValue; + private bool _checkIsActive = false; + public string _password; + public string _challenge; + public string _hash; + public string _derivedk; + public CookieContainer _cookie = new CookieContainer(); + + public string ip { + get { return _ip; } + set { _ip = value; } + } + + /** + * Requests the password-challenge from the router. + * + * @return string + */ + public string getChallenge () { + string response = sendRequest("data/Login.json", "csrf_token=nulltoken&showpw=0&challengev=null"); + if (response.IsNullOrEmpty()) + return string.Empty; + + string challenge = string.Empty; + try { + JToken jArray = JToken.Parse(response); + + challenge = jArray.getVar("challengev"); + jArray = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + + return challenge; + } + + /** + * calculate the derivedk + * + * @param string $password + * @return string + */ + public string getDerviedk () { + return _password.sha256().pbkdf2(_challenge.Substring(0, 16)); + } + + /** + * login into the router with the given password + * + * @param string $password + * @return bool + */ + public bool login (string passwort) { + if (passwort.IsNullOrEmpty()) { + return false; + } + + _cookie = new CookieContainer(); + + _password = passwort; + _challenge = getChallenge(); + _hash = string.Concat(_challenge, ":", _password).sha256(); + + string response = sendRequest("data/Login.json", string.Concat("csrf_token=nulltoken&showpw=0&password=", _hash)); + if (response.IsNullOrEmpty()) + return false; + + _cookie.Add(new Cookie("challengev", _challenge) { Domain = "speedport.ip" }); + + bool login = false; + try { + JToken jArray = JToken.Parse(response); + if (jArray.getVar("login").Equals("success")) { + if (isLoggedin().Equals(false)) { + login = false; + } + else { + login = true; + _derivedk = getDerviedk(); + _lastReboot = getLastReboot(); + } + } + jArray = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + + return login; + } + + /** + * logout + * + * @return bool + */ + public bool logout () { + string response = sendRequest("data/Login.json", string.Concat("csrf_token=", getToken(), "&logout=byby")); + if (response.IsNullOrEmpty()) + return false; + + bool logout = false; + try { + JToken jArray = JToken.Parse(response); + if (jArray.getVar("status").Equals("ok")) { + if (isLoggedin().Equals(true)) { + logout = false; + } + else { + logout = true; + _password = ""; + _challenge = ""; + _cookie = new CookieContainer(); + _lastReboot = DateTime.MinValue; + _hash = ""; + _derivedk = ""; + } + } + + jArray = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + + return logout; + } + + /** + * check if we are logged in + * + * @return bool + */ + public bool checkLogin () { + if (_checkIsActive.Equals(false)) { + _checkIsActive = true; + if (isLoggedin().Equals(false)) { + Console.WriteLine("Session expired, try to relogin"); + + Thread.Sleep(400); + + if (login(_password).Equals(false)) { + // should we try to relogin? login(_password);... + new Thread(() => { LogManager.WriteToLog("Session expired."); }).Start(); + _password = ""; + _challenge = ""; + _cookie = new CookieContainer(); + _lastReboot = DateTime.MinValue; + _hash = ""; + _derivedk = ""; + + LoginPageModel lpm = Application.Current.FindResource("LoginPageModel") as LoginPageModel; + lpm.LogoutAction(); + + new Thread(() => { MessageBox.Show("Session expired.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start(); + _checkIsActive = false; + return false; + } + } + + _checkIsActive = false; + } + else { + Console.WriteLine("check allready in progress"); + } + + return true; + } + + /** + * check if we are logged in + * + * @param bool ischeck + * @return bool + */ + public bool isLoggedin () { + string response = sendRequest("data/SecureStatus.json"); + if (response.IsNullOrEmpty()) + return false; + + bool login = false; + try { + JToken jArray = JToken.Parse(response); + + if (jArray.getVar("loginstate").Equals("1")/* && jArray.getVar("login").Equals("true")*/) { + login = true; + } + + jArray = null; + } + + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + + return login; + } + + /** + * reboot the router + */ + public void reboot () { + if (checkLogin().Equals(false)) + return; + + string response = sendRequest("data/Reboot.json", string.Concat("csrf_token=", Uri.EscapeUriString(getToken()), "&reboot_device=true")); + if (response.IsNullOrEmpty()) + return; + try { + JToken jArray = JToken.Parse(response); + if (jArray.getVar("status").Equals("ok")) { + new Thread(() => { MessageBox.Show("Router Reboot.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start(); + LogManager.WriteToLog("Router Reboot."); + _password = ""; + _challenge = ""; + _cookie = new CookieContainer(); + _hash = ""; + _derivedk = ""; + + LoginPageModel lpm = Application.Current.FindResource("LoginPageModel") as LoginPageModel; + lpm.LogoutAction(); + } + + jArray = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + } + + /** + * reconnect LTE + * + * @return bool + */ + public bool reconnectLte () { + if (checkLogin().Equals(false)) + return false; + + Thread.Sleep(400); + + string response = sendEnryptedRequest("data/modules.json", string.Concat("lte_reconn=1&csrf_token=", Uri.EscapeUriString(getToken()))); + if (response.IsNullOrEmpty()) + return false; + + try { + JToken jArray = JToken.Parse(response); + + response = null; + + if (jArray.getVar("status").Equals("ok")) { + jArray = null; + return true; + } + + jArray = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + + return false; + } + + /** + * reconnect DSL + * + * @return bool + */ + public bool reconnectDSL () { + if (checkLogin().Equals(false)) + return false; + + Thread.Sleep(400); + + string response = sendEnryptedRequest("data/Connect.json", string.Concat("csrf_token=", Uri.EscapeUriString(getToken()), "&showpw=0&password=", _hash, "&req_connect=offline")); + if (response.IsNullOrEmpty()) + return false; + + bool offline = false; + try { + JToken jArray = JToken.Parse(response); + + response = null; + + if (jArray.getVar("status").Equals("ok")) { + offline = true; + } + + jArray = null; + + if (offline.Equals(true)) { + response = sendEnryptedRequest("data/Connect.json", string.Concat("csrf_token=", Uri.EscapeUriString(getToken()), "&showpw=0&password=", _hash, "&req_connect=online")); + jArray = JToken.Parse(response); + if (jArray.getVar("status").Equals("ok")) { + jArray = null; + return true; + } + } + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + + return false; + } + + /** + * change dsl connection status + * + * @param string status + * @return bool + */ + public bool changeDSLStatus (string status) { + if (checkLogin().Equals(false)) + return false; + + if (status.Equals("online") || status.Equals("offline")) { + + string response = sendEnryptedRequest("data/Connect.json", string.Concat("req_connect=", status, "&csrf_token=", Uri.EscapeUriString(getToken()))); + if (response.IsNullOrEmpty()) + return false; + try { + JToken jArray = JToken.Parse(response); + + response = null; + + if (jArray.getVar("status").Equals("ok")) { + jArray = null; + return true; + } + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + } + + return false; + } + + /** + * change lte connection status + * + * @param string status + * @return bool + */ + public bool changeLTEStatus (string status) { + if (checkLogin().Equals(false)) + return false; + + if (status.Equals("online") || status.Equals("offline")) { + if (status.Equals("online")) + status = "1"; + + if (status.Equals("offline")) + status = "0"; + + string response = sendEnryptedRequest("data/Modules.json", string.Concat("use_lte=", status, "&csrf_token=", Uri.EscapeUriString(getToken()))); + if (response.IsNullOrEmpty()) + return false; + try { + JToken jArray = JToken.Parse(response); + + response = null; + + if (jArray.getVar("status").Equals("ok")) { + jArray = null; + return true; + } + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + } + + return false; + } + + /** + * reset the router to Factory Default + * not tested + * + * @return bool + */ + public bool resetToFactoryDefault () { + if (checkLogin().Equals(false)) + return false; + + Thread.Sleep(400); + + string response = sendEnryptedRequest("data/resetAllSetting.json", string.Concat("csrf_token=nulltoken&showpw=0&password=", _hash, "&reset_all=true")); + if (response.IsNullOrEmpty()) + return false; + + try { + JToken jArray = JToken.Parse(response); + if (jArray.getVar("status").Equals("ok")) { + return true; + } + + jArray = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + + return false; + } + + /** + * check for firmware update + */ + public void checkFirmware () { + if (checkLogin().Equals(false)) + return; + + Thread.Sleep(400); + + string response = sendRequest("data/checkfirm.json"); + if (response.IsNullOrEmpty()) + return; + + try { + bool fw_isActual = false; + JToken jArray = JToken.Parse(response); + + if (jArray.getVar("fw_isActual").Equals("1")) { + fw_isActual = true; + } + + if (fw_isActual.Equals(true)) { + // Die Firmware ist aktuell. + MessageBox.Show("Die Firmware ist aktuell.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); + } + else { + // Es liegt eine neuere Firmware-Version vor. Möchten Sie diese Version jetzt installieren? + MessageBox.Show("Es liegt eine neuere Firmware-Version vor.\nMöchten Sie diese Version jetzt installieren?", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Warning); + } + + jArray = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + } + + /** + * flush dns cache + */ + public void flushDNS () { + if (checkLogin().Equals(false)) + return; + + Thread.Sleep(400); + + string response = sendEnryptedRequest("data/dns.json", "op_type=flush_dns_cache"); + if (response.IsNullOrEmpty()) + return; + + try { + JToken jArray = JToken.Parse(response); + + if (jArray["DCI"].Count().Equals(0)) { + new Thread(() => { MessageBox.Show("DNS cache geleert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start(); + } + else { + new Thread(() => { MessageBox.Show("unable to flush dns cache", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start(); + } + + + jArray = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + } + + /** + * clear the Syslog + */ + public void clearSyslog () { + if (checkLogin().Equals(false)) + return; + + Thread.Sleep(400); + + string response = sendEnryptedRequest("data/SystemMessages.json", string.Concat("action_clearlist=true&clear_type=0&", "csrf_token=", getToken())); + if (response.IsNullOrEmpty()) + return; + + try { + JToken jArray = JToken.Parse(response); + + if (jArray.getVar("status").Equals("ok")) { + // ok + new Thread(() => { MessageBox.Show("Syslog geleert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start(); + } + else { + // fail + new Thread(() => { MessageBox.Show("Konnte Syslog nicht leeren.", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start(); + } + + jArray = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + } + + /** + * set QueueSkbTimeOut + * + * @param string value + */ + public void setQueueSkbTimeOut (string value) { + if (checkLogin().Equals(false)) + return; + + string response = sendEnryptedRequest("data/bonding_tr181.json", string.Concat("bonding_QueueSkbTimeOut=", value)); + if (response.IsNullOrEmpty()) + return; + try { + TR181 obj = JsonConvert.DeserializeObject(response); + + if (obj.QueueSkbTimeOut.Equals(value)) { + new Thread(() => { MessageBox.Show("QueueSkbTimeOut geändert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start(); + } + else { + new Thread(() => { MessageBox.Show("unable to change QueueSkbTimeOut", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start(); + } + + obj = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + } + + /** + * set Antenna Mode + * + * @param string value + */ + public void setAntennaMode (string value) { + if (checkLogin().Equals(false)) + return; + + string response = sendEnryptedRequest("data/lteinfo.json", string.Concat("mode_select=", value)); + if (response.IsNullOrEmpty()) + return; + try { + LTE obj = JsonConvert.DeserializeObject(response); + + string antenna_mode; + if (obj.antenna_mode.Equals("Antennal set to internal")) { + antenna_mode = "Inner"; + } + else if (obj.antenna_mode.Equals("Antennal set to external")) { + antenna_mode = "Outer"; + } + else { + antenna_mode = "Auto"; + } + + if (antenna_mode.Equals(value)) { + new Thread(() => { MessageBox.Show("Antennen Modus geändert", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information); }).Start(); + } + else { + new Thread(() => { MessageBox.Show("Antennen Modus ändern Fehlgeschlagen", "Confirmation", MessageBoxButton.OK, MessageBoxImage.Error); }).Start(); + } + + antenna_mode = null; + + obj = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + response = null; + } + + /** + * get Last Reboot time + * + * @return DateTime + */ + public DateTime getLastReboot () { + if (_lastReboot.Equals(DateTime.MinValue).Equals(false)) { + return _lastReboot; + } + + string response = sendRequest("data/Reboot.json"); + + if (response.IsNullOrEmpty()) + return DateTime.Now; + + JToken jArray = JToken.Parse(response); + + DateTime lastReboot = DateTime.Parse(string.Concat(jArray.getVar("reboot_date"), " ", jArray.getVar("reboot_time"))); + + jArray = null; + + return lastReboot; + } + + /** + * get the csrf token from router + * + * @return string + */ + public string getToken () { + string response = sendRequest("html/content/overview/index.html"); + if (response.IsNullOrEmpty()) + return string.Empty; + + string a = "csrf_token = \""; + string b = "\";"; + string token = response.Substring((response.IndexOf(a) + a.Length), (response.IndexOf(b) - response.IndexOf(a) - a.Length)); + + response = null; + a = null; + b = null; + + Console.WriteLine("csrf_token: " + token); + return token; + } + + /** + * send encrypted request to the router + * + * @param string path + * @param string post + * @param bool cookie + * @return string + */ + public string sendEnryptedRequest (string path, string post = "", bool cookie = true) { + string response = string.Empty; + + try { + sjcl sjcl = new sjcl(); + + string iv = _challenge.Substring(16, 16); + string adata = _challenge.Substring(32, 16); + string dKey = _derivedk; + + + // TODO: check if we need this really? + if (post.IsNullOrEmpty().Equals(false)) { + post = sjcl.encrypt(dKey, post, iv, adata); + } + + + response = sendRequest(path, post, cookie); + // check if the return value is hex (hex = enrypted) + if (Regex.IsMatch(response, @"\A\b[0-9a-fA-F]+\b\Z").Equals(true)) { + response = sjcl.decrypt(dKey, response, iv, adata); + } + + post = null; + iv = null; + adata = null; + dKey = null; + sjcl = null; + + } + catch (ArgumentOutOfRangeException ex) { + LogManager.WriteToLog(ex.Message); + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + return response; + } + + /** + * send request to the router + * + * @param string path + * @param string post + * @param bool cookie + * @return string + */ + public string sendRequest (string path, string post = "", bool cookie = true) { + string response = string.Empty; + try { + string url = string.Concat("http://", ip, "/", path, "?lang=de"); + + HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; + /* set timeout to 10 seconds */ + webRequest.Timeout = 10000; + + if (cookie.Equals(true)) { + webRequest.CookieContainer = _cookie; + } + + if (post.IsNullOrEmpty().Equals(false)) { + webRequest.Method = "POST"; + byte[] dataStream = Encoding.UTF8.GetBytes(post); + webRequest.ContentLength = dataStream.Length; + Stream newStream = webRequest.GetRequestStream(); + newStream.Write(dataStream, 0, dataStream.Length); + newStream.Close(); + newStream.Dispose(); + newStream = null; + dataStream = null; + } + + WebResponse webResponse = webRequest.GetResponse(); + StreamReader reader = new StreamReader(webResponse.GetResponseStream()); + response = reader.ReadToEnd().ToString(); + + webResponse.Dispose(); + reader.Dispose(); + reader = null; + webRequest = null; + webResponse = null; + post = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + return response; + } + + public string sendRequest2 (string path, Dictionary files, string post = "", bool cookie = true) { + string response = string.Empty; + + try { + string url = string.Concat("http://", ip, "/", path, "?lang=de"); + + string boundary = string.Concat("---------------------------", DateTime.Now.Ticks.ToString("x")); + byte[] boundaryBytes = Encoding.ASCII.GetBytes(string.Concat("\r\n--", boundary, "\r\n")); + + HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; + request.ContentType = string.Concat("multipart/form-data; boundary=", boundary); + request.Method = "POST"; + request.KeepAlive = true; + + if (cookie.Equals(true)) { + request.CookieContainer = _cookie; + } + + Stream requestStream = request.GetRequestStream(); + + if (string.IsNullOrEmpty(post).Equals(false)) { + byte[] dataStream = Encoding.UTF8.GetBytes(post); + requestStream.Write(dataStream, 0, dataStream.Length); + dataStream = null; + } + + if (files != null && files.Count > 0) { + foreach (KeyValuePair pair in files) { + requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); + if (pair.Value is FormFile) { + FormFile file = pair.Value as FormFile; + string header = string.Concat("Content-Disposition: form-data; name=\"", pair.Key, "\"; filename=\"", file.Name, "\"\r\nContent-Type: ", file.ContentType, "\r\n\r\n"); + byte[] bytes = Encoding.UTF8.GetBytes(header); + requestStream.Write(bytes, 0, bytes.Length); + byte[] buffer = new byte[32768]; + int bytesRead; + if (file.Stream == null) { + // upload from file + FileStream fileStream = File.OpenRead(file.FilePath); + while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { + requestStream.Write(buffer, 0, bytesRead); + } + fileStream.Close(); + } + else { + // upload from given stream + while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0) + requestStream.Write(buffer, 0, bytesRead); + } + } + else { + string data = string.Concat("Content-Disposition: form-data; name=\"", pair.Key, "\"\r\n\r\n", pair.Value); + byte[] bytes = Encoding.UTF8.GetBytes(data); + requestStream.Write(bytes, 0, bytes.Length); + } + } + + byte[] trailer = Encoding.ASCII.GetBytes(string.Concat("\r\n--", boundary, "--\r\n")); + requestStream.Write(trailer, 0, trailer.Length); + requestStream.Close(); + + } + + WebResponse webResponse = request.GetResponse(); + Stream responseStream = webResponse.GetResponseStream(); + StreamReader reader = new StreamReader(responseStream); + response = reader.ReadToEnd(); + + webResponse.Dispose(); + reader.Dispose(); + reader = null; + request = null; + webResponse = null; + } + catch (Exception ex) { + LogManager.WriteToLog(ex.Message); + } + + return response; + } + } + + public class FormFile { + public string Name { get; set; } + + public string ContentType { get; set; } + + public string FilePath { get; set; } + + public Stream Stream { get; set; } + } +} \ No newline at end of file diff --git a/SpeedportHybridControl/Model/LoginPageModel.cs b/SpeedportHybridControl/Model/LoginPageModel.cs index 59f5fc0..eea57b2 100644 --- a/SpeedportHybridControl/Model/LoginPageModel.cs +++ b/SpeedportHybridControl/Model/LoginPageModel.cs @@ -1,5 +1,6 @@ using System; using SpeedportHybridControl.Implementations; +using SpeedportHybridControl.Data; using System.Windows; using System.Threading; @@ -119,7 +120,7 @@ namespace SpeedportHybridControl.Model { } LoginFieldsVisibility = Visibility.Hidden; - mwm.ButtonOverviewPageIsActive = true; + mwm.ButtonOverviewPageIsActive = true; mwm.ButtonDSLPageIsActive = true; mwm.ButtonLteInfoPageIsActive = true; mwm.ButtonSyslogPageIsActive = true; @@ -139,23 +140,27 @@ namespace SpeedportHybridControl.Model { else { if (SpeedportHybridAPI.getInstance().logout().Equals(true)) { // TODO: util.logout(); - - LoginFieldsVisibility = Visibility.Visible; - mwm.ButtonOverviewPageIsActive = false; - mwm.ButtonDSLPageIsActive = false; - mwm.ButtonLteInfoPageIsActive = false; - mwm.ButtonSyslogPageIsActive = false; - mwm.ButtonTR181PageIsActive = false; - mwm.ButtonPhonePageIsActive = false; - mwm.ButtonLanPageIsActive = false; - mwm.ButtonControlsPageIsActive = false; - - LoginButtonText = "Login"; - mwm.LoginButtonContent = "Login"; + LogoutAction(); } } } + public void LogoutAction () { + MainWindowModel mwm = Application.Current.FindResource("MainWindowModel") as MainWindowModel; + LoginFieldsVisibility = Visibility.Visible; + mwm.ButtonOverviewPageIsActive = false; + mwm.ButtonDSLPageIsActive = false; + mwm.ButtonLteInfoPageIsActive = false; + mwm.ButtonSyslogPageIsActive = false; + mwm.ButtonTR181PageIsActive = false; + mwm.ButtonPhonePageIsActive = false; + mwm.ButtonLanPageIsActive = false; + mwm.ButtonControlsPageIsActive = false; + + LoginButtonText = "Login"; + mwm.LoginButtonContent = "Login"; + } + public LoginPageModel () { SettingsModel settings = Settings.load(); if (settings.ip.IsNullOrEmpty().Equals(false)) { @@ -167,7 +172,7 @@ namespace SpeedportHybridControl.Model { if (settings.password.IsNullOrEmpty().Equals(false)) { SavePassword = true; password = settings.password; - } + } ShowPasswordCommand = new DelegateCommand(new Action(OnShowPasswordCommandExecute)); SavePasswordCommand = new DelegateCommand(new Action(OnSavePasswordCommandExecute)); diff --git a/SpeedportHybridControl/SpeedportHybridControl.csproj b/SpeedportHybridControl/SpeedportHybridControl.csproj index 96aa704..e9e0c5b 100644 --- a/SpeedportHybridControl/SpeedportHybridControl.csproj +++ b/SpeedportHybridControl/SpeedportHybridControl.csproj @@ -62,6 +62,7 @@ MSBuild:Compile Designer + @@ -72,6 +73,7 @@ + MSBuild:Compile Designer diff --git a/SpeedportHybridControl/model/MainWindowModel.cs b/SpeedportHybridControl/model/MainWindowModel.cs index 75049bd..1c8a917 100644 --- a/SpeedportHybridControl/model/MainWindowModel.cs +++ b/SpeedportHybridControl/model/MainWindowModel.cs @@ -3,6 +3,8 @@ using SpeedportHybridControl.Implementations; using System.Windows.Controls; using SpeedportHybridControl.page; using System.Windows.Media; +using System.Threading; +using SpeedportHybridControl.Data; namespace SpeedportHybridControl.Model { class MainWindowModel : SuperViewModel { @@ -211,6 +213,7 @@ namespace SpeedportHybridControl.Model { private void OnSwitchToStatusPageExecute () { FrameSource = new StatusPage(); changeColor("status"); + new Thread(() => { SpeedportHybrid.initStatus(); }).Start(); } private void OnSwitchToOverviewPageExecute () { diff --git a/SpeedportHybridControl/page/LoginPage.xaml b/SpeedportHybridControl/page/LoginPage.xaml index 7a9768c..e51f2fe 100644 --- a/SpeedportHybridControl/page/LoginPage.xaml +++ b/SpeedportHybridControl/page/LoginPage.xaml @@ -15,8 +15,8 @@ - - + +