private void saveTheShit() { var fff = new SaveFileDialog() { //CheckFileExists = true, Filter = "WAV|*.wav", }; var result = fff.ShowDialog(); if (result != DialogResult.OK) { return; } LastFolder = Path.GetDirectoryName(fff.FileName); // save xml logicShit.cleanUpFilenames(fff.FileName); XmlFactory.WriteToFile <XmlAudiobook>(logicShit.AudiobookXml, fff.FileName + ".xml"); // save wav AudiobookerMp3Utils.SaveMusicMp3ToSegmentedFile(fff.FileName, logicShit.AudiobookXml); UtilsCore.OpenWinExplorerAndSelectThisFile(fff.FileName); }
public List <string> GetBootstrapUrls() { List <string> urls = new List <string>(); // Manual Urls foreach (string url in Engine.Instance.Storage.Get("bootstrap.urls").Split(';')) { string sUrl = url.Trim(); if (sUrl != "") { if (IpAddress.IsIP(sUrl)) { sUrl = "http://" + sUrl; } string host = UtilsCore.HostFromUrl(sUrl); if (host != "") { urls.Add(sUrl); } } } // Manifest Urls if (Manifest != null) { XmlNodeList nodesUrls = Manifest.SelectNodes("//urls/url"); foreach (XmlNode nodeUrl in nodesUrls) { urls.Add(nodeUrl.Attributes["address"].Value); } } return(urls); }
public string GetStatsString() { Dictionary <string, ConnectionInfo> servers; lock (Engine.Instance.Connections) servers = new Dictionary <string, ConnectionInfo>(Engine.Instance.Connections); int timeNow = UtilsCore.UnixTimeStamp(); int interval = Engine.Instance.Storage.GetInt("discover.interval"); int nTotal = 0; int nPending = 0; foreach (ConnectionInfo infoServer in servers.Values) { if (infoServer.NeedDiscover) { nTotal++; if (timeNow - infoServer.LastDiscover >= interval) { nPending++; } } } return(nPending + " pending / " + nTotal); }
public PingerStats GetStats() { PingerStats stats = new PingerStats(); int timeNow = UtilsCore.UnixTimeStamp(); int iTotal = 0; List <ConnectionInfo> connections = GetConnectionsToPing(); foreach (ConnectionInfo infoConnection in connections) { int deltaValid = GetPingerDelayValid(infoConnection); if ((stats.OlderCheckDate == 0) || (stats.OlderCheckDate > infoConnection.LastPingResult)) { stats.OlderCheckDate = infoConnection.LastPingResult; } if ((stats.LatestCheckDate == 0) || (stats.LatestCheckDate < infoConnection.LastPingResult)) { stats.LatestCheckDate = infoConnection.LastPingResult; } iTotal++; if ((infoConnection.CanPing()) && (timeNow - infoConnection.LastPingResult > deltaValid)) { stats.Invalid++; } } stats.Valid = (stats.Invalid == 0); return(stats); }
public override void OnBuildConnections() { base.OnBuildConnections(); lock (Manifest) { foreach (XmlNode nodeServer in Manifest.SelectNodes("//servers/server")) { string code = UtilsCore.HashSHA256(nodeServer.Attributes["name"].Value); ConnectionInfo infoServer = Engine.Instance.GetConnectionInfo(code, this); // Update info infoServer.DisplayName = TitleForDisplay + nodeServer.Attributes["name"].Value; infoServer.ProviderName = nodeServer.Attributes["name"].Value; infoServer.IpsEntry.Set(UtilsXml.XmlGetAttributeString(nodeServer, "ips_entry", "")); infoServer.IpsExit.Set(UtilsXml.XmlGetAttributeString(nodeServer, "ips_exit", "")); infoServer.CountryCode = UtilsXml.XmlGetAttributeString(nodeServer, "country_code", ""); infoServer.Location = UtilsXml.XmlGetAttributeString(nodeServer, "location", ""); infoServer.ScoreBase = UtilsXml.XmlGetAttributeInt64(nodeServer, "scorebase", 0); infoServer.Bandwidth = UtilsXml.XmlGetAttributeInt64(nodeServer, "bw", 0); infoServer.BandwidthMax = UtilsXml.XmlGetAttributeInt64(nodeServer, "bw_max", 1); infoServer.Users = UtilsXml.XmlGetAttributeInt64(nodeServer, "users", 0); infoServer.WarningOpen = UtilsXml.XmlGetAttributeString(nodeServer, "warning_open", ""); infoServer.WarningClosed = UtilsXml.XmlGetAttributeString(nodeServer, "warning_closed", ""); infoServer.SupportIPv4 = UtilsXml.XmlGetAttributeBool(nodeServer, "support_ipv4", false); infoServer.SupportIPv6 = UtilsXml.XmlGetAttributeBool(nodeServer, "support_ipv6", false); infoServer.SupportCheck = UtilsXml.XmlGetAttributeBool(nodeServer, "support_check", false); infoServer.OvpnDirectives = UtilsXml.XmlGetAttributeString(nodeServer, "openvpn_directives", ""); } } RefreshModes(); }
public void PingResult(ConnectionInfo infoServer, Int64 result) { infoServer.PingTests++; infoServer.LastPingResult = UtilsCore.UnixTimeStamp(); if (result == -1) { infoServer.PingFailedConsecutive++; if (infoServer.PingFailedConsecutive >= 5) { infoServer.Ping = -1; } } else { infoServer.LastPingSuccess = infoServer.LastPingResult; infoServer.PingFailedConsecutive = 0; if (infoServer.Ping == -1) { infoServer.Ping = result; } else { infoServer.Ping = (infoServer.Ping + result) / 2; } } Engine.Instance.MarkServersListUpdated(); }
public override string Refresh() { base.Refresh(); try { Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters["act"] = "manifest"; parameters["ts"] = Conversions.ToString(m_lastFetchTime); XmlDocument xmlDoc = Fetch(Messages.ManifestUpdate, parameters); lock (Storage) { if (Manifest != null) { Storage.DocumentElement.RemoveChild(Manifest); } Manifest = Storage.ImportNode(xmlDoc.DocumentElement, true); Storage.DocumentElement.AppendChild(Manifest); // Update with the local time Manifest.Attributes["time"].Value = UtilsCore.UnixTimeStamp().ToString(); m_lastFetchTime = UtilsCore.UnixTimeStamp(); } return(""); } catch (Exception e) { return(MessagesFormatter.Format(Messages.ManifestFailed, e.Message)); } }
public override void OnRun() { Dictionary <string, ConnectionInfo> servers; lock (Engine.Instance.Connections) servers = new Dictionary <string, ConnectionInfo>(Engine.Instance.Connections); int timeNow = UtilsCore.UnixTimeStamp(); int interval = Engine.Instance.Storage.GetInt("discover.interval"); foreach (ConnectionInfo infoServer in servers.Values) { if (m_cancelRequested) { return; } if (infoServer.NeedDiscover) { if (timeNow - infoServer.LastDiscover >= interval) { DiscoverIp(infoServer); } } } m_timeEvery = 60000; }
public override bool OnCheckSingleInstance() { try { int currentId = Process.GetCurrentProcess().Id; string path = UtilsCore.GetTempPath() + "/" + Constants.Name + "_" + Constants.AppID + ".pid"; if (File.Exists(path) == false) { } else { int otherId; if (int.TryParse(Platform.Instance.FileContentsReadText(path), out otherId)) { string procFile = "/proc/" + otherId.ToString() + "/cmdline"; if (File.Exists(procFile)) { return(false); } } } Platform.Instance.FileContentsWriteText(path, currentId.ToString(), Encoding.ASCII); return(true); } catch (Exception e) { Engine.Instance.Logs.Log(e); return(true); } }
public void cleanUpFilenames(string filenameBig) { var newFolderName = UtilsCore.GetFullPathWithoutExtension(filenameBig); foreach (var seg in AudiobookXml.Segments) { seg.Filename = seg.Filename.Replace(DumpFolder + "/", ""); } if (Directory.Exists(newFolderName)) Directory.Delete(newFolderName, true); Directory.Move(DumpFolder, newFolderName); }
public void DiscoverIp(ConnectionInfo connection) { IpAddress ip = connection.IpsEntry.FirstPreferIPv4; if (ip != null) { Json jDoc = DiscoverIpData(ip.Address, ""); if (jDoc != null) { // Node parsing if (jDoc.HasKey("country_code")) { string countryCode = Conversions.ToString(jDoc["country_code"].Value).Trim().ToLowerInvariant(); if (CountriesManager.IsCountryCode(countryCode)) { if (connection.CountryCode != countryCode) { connection.CountryCode = countryCode; Engine.Instance.MarkServersListUpdated(); Engine.Instance.MarkAreasListUpdated(); } } } if (jDoc.HasKey("city_name")) { string cityName = Conversions.ToString(jDoc["city_name"].Value).Trim(); if (cityName == "N/A") { cityName = ""; } if (cityName != "") { connection.Location = cityName; Engine.Instance.MarkServersListUpdated(); } } if ((jDoc.HasKey("latitude")) && (jDoc.HasKey("longitude"))) { double latitude = Conversions.ToDouble(jDoc["latitude"].Value); double longitude = Conversions.ToDouble(jDoc["longitude"].Value); connection.Latitude = latitude; connection.Longitude = longitude; Engine.Instance.MarkServersListUpdated(); } } } connection.LastDiscover = UtilsCore.UnixTimeStamp(); connection.Provider.OnChangeConnection(connection); }
public override void ExceptionIfRequired() { if (Available() == false) { throw new Exception(Messages.ToolsCurlRequired); } if (UtilsCore.CompareVersions(Version, minVersionRequired) == -1) { throw new Exception(GetRequiredVersionMessage()); } }
public override void OnRun() { if (m_lastVersionNotification == "") { m_lastVersionNotification = Constants.VersionDesc; } string channel = Engine.Instance.Storage.Get("updater.channel"); try { HttpRequest request = new HttpRequest(); request.Url = Constants.WebSite + "/download/"; request.Url += "?mode=info"; request.Url += "&platform=" + Platform.Instance.GetCodeInstaller(); request.Url += "&arch=" + Platform.Instance.GetArchitecture(); request.Url += "&ui=" + "ui"; request.Url += "&format=updater"; request.Url += "&version=" + channel; HttpResponse response = Engine.Instance.FetchUrl(request); Json j = null; if (Json.TryParse(response.GetBody(), out j)) { string latestVersion = j["version"].Value as string; int compare = UtilsCore.CompareVersions(m_lastVersionNotification, latestVersion); if (compare == -1) { Json jUpdaterAvailable = new Json(); jUpdaterAvailable["command"].Value = "ui.updater.available"; Engine.Instance.UiManager.Broadcast(jUpdaterAvailable); } m_lastVersionNotification = latestVersion; m_timeEvery = 60 * 60 * 24 * 1000; } else { // Error, retry later m_timeEvery = 60 * 60 * 3 * 1000; } } catch { // Error, retry later m_timeEvery = 60 * 60 * 3 * 1000; } }
private void PhotographBookReader_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop, false)) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); var firstFile = files.FirstOrDefault(); if (UtilsCore.IsFilenameImage(firstFile)) { e.Effect = DragDropEffects.Copy; } //string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); } }
public void LoadImage(string firstFile) { if (!File.Exists(firstFile)) { return; } loadPage(firstFile); filenamesAll = Directory.GetFiles(Path.GetDirectoryName(firstFile)) .Where(f => UtilsCore.IsFilenameImage(f)) .OrderBy(f => f) .ToArray(); curIndex = filenamesAll.IndexOf(firstFile, (x, y) => x == y); }
public override bool GetNeedRefresh() { int minInterval = RefreshInterval; if (minInterval == -1) { minInterval = 60 * 60 * 24; } if (m_lastTryRefresh + minInterval > UtilsCore.UnixTimeStamp()) { return(false); } return(true); }
// Override public Platform() { try { m_monoVersion = NativeMethods.GetMonoVersion(); } catch { m_monoVersion = "2-generic"; } if (UtilsCore.CompareVersions(m_monoVersion, "5.10.1.45") < 0) { // Workaround for https://github.com/mono/mono/issues/6752 Environment.SetEnvironmentVariable("TERM", "XTERM", EnvironmentVariableTarget.Process); } }
public override string OnRefresh() { base.OnRefresh(); // Engine.Instance.Logs.LogVerbose(MessagesFormatter.Format(Messages.ProviderRefreshStart, Title)); try { Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters["act"] = "manifest"; parameters["ts"] = Conversions.ToString(m_lastFetchTime); XmlDocument xmlDoc = Fetch(MessagesFormatter.Format(Messages.ProviderRefreshStart, Title), parameters); lock (Storage) { if (Manifest != null) { Storage.DocumentElement.RemoveChild(Manifest); } Manifest = Storage.ImportNode(xmlDoc.DocumentElement, true); Storage.DocumentElement.AppendChild(Manifest); // Update with the local time Manifest.Attributes["time"].Value = UtilsCore.UnixTimeStamp().ToString(); m_lastFetchTime = UtilsCore.UnixTimeStamp(); } Engine.Instance.Logs.LogVerbose(MessagesFormatter.Format(Messages.ProviderRefreshDone, Title)); string msg = GetFrontMessage(); if ((msg != "") && (m_frontMessages.Contains(msg) == false)) { Engine.Instance.OnFrontMessage(msg); m_frontMessages.Add(msg); } return(""); } catch (Exception e) { Engine.Instance.Logs.LogVerbose(MessagesFormatter.Format(Messages.ProviderRefreshFail, Title, e.Message)); return(MessagesFormatter.Format(Messages.ProviderRefreshFail, Title, e.Message)); } }
public override void OnRun() { Dictionary <string, ConnectionInfo> servers; for (;;) { m_checkNow = false; lock (Engine.Connections) servers = new Dictionary <string, ConnectionInfo>(Engine.Connections); int timeNow = UtilsCore.UnixTimeStamp(); int interval = Engine.Instance.Storage.GetInt("discover.interval"); foreach (ConnectionInfo infoServer in servers.Values) { if (CancelRequested) { return; } if (infoServer.NeedDiscover) { if (timeNow - infoServer.LastDiscover >= interval) { DiscoverIp(infoServer); } } } for (int i = 0; i < 600; i++) // Every minute { Sleep(100); if (CancelRequested) { return; } if (m_checkNow) { break; } } } }
public void Hit(long d, long u) { int ts = UtilsCore.UnixTimeStamp(); lock (this) { foreach (Chart c in ChartsList) { c.Hit(d, u, ts); } } if (UpdateEvent != null) { UpdateEvent(this, null); } }
public override IpAddresses GetNetworkLockAllowedIps() { IpAddresses result = base.GetNetworkLockAllowedIps(); List <string> urls = GetBootstrapUrls(); foreach (string url in urls) { string host = UtilsCore.HostFromUrl(url); if (host != "") { result.Add(host); } } return(result); }
public override void OnBuildConnections() { base.OnBuildConnections(); lock (Manifest) { foreach (XmlNode nodeServer in Manifest.SelectNodes("//servers/server")) { string code = UtilsCore.HashSHA256(nodeServer.Attributes["name"].Value); string group = nodeServer.GetAttributeString("group", ""); XmlNode nodeServerGroup = Manifest.SelectSingleNode("//servers_groups/servers_group[@group=\"" + group + "\"]"); ConnectionInfo infoServer = Engine.Instance.GetConnectionInfo(code, this); // Update info infoServer.DisplayName = TitleForDisplay + nodeServer.Attributes["name"].Value; infoServer.ProviderName = nodeServer.Attributes["name"].Value; infoServer.IpsEntry.Set(XmlGetServerAttributeString(nodeServer, nodeServerGroup, "ips_entry", "")); infoServer.IpsExit.Set(XmlGetServerAttributeString(nodeServer, nodeServerGroup, "ips_exit", "")); infoServer.CountryCode = XmlGetServerAttributeString(nodeServer, nodeServerGroup, "country_code", ""); infoServer.Location = XmlGetServerAttributeString(nodeServer, nodeServerGroup, "location", ""); infoServer.ScoreBase = XmlGetServerAttributeInt64(nodeServer, nodeServerGroup, "scorebase", 0); infoServer.Bandwidth = XmlGetServerAttributeInt64(nodeServer, nodeServerGroup, "bw", 0); infoServer.BandwidthMax = XmlGetServerAttributeInt64(nodeServer, nodeServerGroup, "bw_max", 1); infoServer.Users = XmlGetServerAttributeInt64(nodeServer, nodeServerGroup, "users", 0); infoServer.WarningOpen = XmlGetServerAttributeString(nodeServer, nodeServerGroup, "warning_open", ""); infoServer.WarningClosed = XmlGetServerAttributeString(nodeServer, nodeServerGroup, "warning_closed", ""); infoServer.SupportIPv4 = XmlGetServerAttributeBool(nodeServer, nodeServerGroup, "support_ipv4", false); infoServer.SupportIPv6 = XmlGetServerAttributeBool(nodeServer, nodeServerGroup, "support_ipv6", false); infoServer.SupportCheck = XmlGetServerAttributeBool(nodeServer, nodeServerGroup, "support_check", false); infoServer.OvpnDirectives = XmlGetServerAttributeString(nodeServer, nodeServerGroup, "openvpn_directives", ""); infoServer.CiphersTls = XmlGetServerAttributeString(nodeServer, nodeServerGroup, "ciphers_tls", "").StringToList(":"); infoServer.CiphersTlsSuites = XmlGetServerAttributeString(nodeServer, nodeServerGroup, "ciphers_tlssuites", "").StringToList(":"); infoServer.CiphersData = XmlGetServerAttributeString(nodeServer, nodeServerGroup, "ciphers_data", "").StringToList(":"); } } RefreshModes(); }
public override void OnCheckSingleInstanceClear() { try { int currentId = Process.GetCurrentProcess().Id; string path = UtilsCore.GetTempPath() + "/" + Constants.Name + "_" + Constants.AppID + ".pid"; if (File.Exists(path)) { int otherId; if (int.TryParse(Platform.Instance.FileContentsReadText(path), out otherId)) { if (otherId == currentId) { Platform.Instance.FileDelete(path); } } } } catch (Exception e) { Engine.Instance.Logs.Log(e); } }
public override bool GetNeedRefresh() { int minInterval = RefreshInterval; { // Temp until option migration minInterval = Engine.Instance.Storage.GetInt("advanced.manifest.refresh"); if (minInterval == 0) { return(false); } if (minInterval != -1) { minInterval *= 60; } } if ((Manifest != null) && (minInterval == -1)) // Pick server recommended { minInterval = Manifest.GetAttributeInt("next_update", -1); if (minInterval != -1) { minInterval *= 60; } } if (minInterval == -1) { minInterval = 60 * 60 * 24; } if (m_lastTryRefresh + minInterval > UtilsCore.UnixTimeStamp()) { return(false); } return(true); }
public override void Start() { ServiceEdition = false; ServiceUninstallAtEnd = false; string tempPathToDelete = ""; try { if (Connect(Constants.ElevatedServiceTcpPort) == false) // Will work if the service is active { Engine.Instance.UiManager.Broadcast("init.step", "message", LanguageManager.GetText("InitStepRaiseSystemPrivileges")); Engine.Instance.Logs.LogVerbose(LanguageManager.GetText("InitStepRaiseSystemPrivileges")); string helperPath = Platform.Instance.GetElevatedHelperPath(); // Special environment: AppImage // pkexec/sudo can't see the file. Workaround: Copy, execute, remove. bool appImageEnvironment = Platform.Instance.NeedExecuteOutsideAppPath(helperPath); if (appImageEnvironment) { tempPathToDelete = UtilsCore.GetTempPath() + "/eddie-cli-elevated-" + RandomGenerator.GetHash(); if (File.Exists(tempPathToDelete)) { File.Delete(tempPathToDelete); } File.Copy(helperPath, tempPathToDelete); helperPath = tempPathToDelete; } int pid = Platform.Instance.StartProcessAsRoot(helperPath, new string[] { "spot" }, Engine.Instance.ConsoleMode); System.Diagnostics.Process process = null; if (pid > 0) { process = System.Diagnostics.Process.GetProcessById(pid); } for (; ;) { System.Threading.Thread.Sleep(1000); if (process == null) { throw new Exception("Unable to start (1)"); } if (process.HasExited) { throw new Exception("Unable to start (2)"); } if (Connect(9345)) { break; } } } else { ServiceEdition = true; } base.Start(); } catch (Exception ex) { Stop(); throw new Exception(LanguageManager.GetText("HelperPrivilegesFailed", ex.Message)); } finally { if (tempPathToDelete != "") { Platform.Instance.FileDelete(tempPathToDelete); } } }
public override string OnRefresh() { base.OnRefresh(); // Engine.Instance.Logs.LogVerbose(LanguageManager.GetText("ProviderRefreshStart, Title)); try { Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters["act"] = "manifest"; parameters["ts"] = Conversions.ToString(m_lastFetchTime); XmlDocument xmlDoc = Fetch(LanguageManager.GetText("ProviderRefreshStart", Title), parameters); lock (Storage) { if (Manifest != null) { Storage.DocumentElement.RemoveChild(Manifest); } Manifest = Storage.ImportNode(xmlDoc.DocumentElement, true); Storage.DocumentElement.AppendChild(Manifest); // Update with the local time Manifest.Attributes["time"].Value = UtilsCore.UnixTimeStamp().ToString(); m_lastFetchTime = UtilsCore.UnixTimeStamp(); } Engine.Instance.Logs.LogVerbose(LanguageManager.GetText("ProviderRefreshDone", Title)); // Show important messages foreach (XmlElement xmlMessage in Manifest.SelectNodes("messages/message")) { if ((xmlMessage.HasAttribute("from_time")) && (UtilsCore.UnixTimeStamp() < Conversions.ToInt64(xmlMessage.GetAttribute("from_time")))) { continue; } if ((xmlMessage.HasAttribute("to_time")) && (UtilsCore.UnixTimeStamp() > Conversions.ToInt64(xmlMessage.GetAttribute("to_time")))) { continue; } Json jMessage = new Json(); jMessage["text"].Value = xmlMessage.GetAttribute("text"); jMessage["url"].Value = xmlMessage.GetAttribute("url"); jMessage["link"].Value = xmlMessage.GetAttribute("link"); jMessage["html"].Value = xmlMessage.GetAttribute("html"); string text = jMessage["text"].Value as string; if (m_frontMessages.Contains(text) == false) { Json jCommand = new Json(); jCommand["command"].Value = "ui.frontmessage"; jCommand["message"].Value = jMessage; Engine.Instance.UiManager.Broadcast(jCommand); m_frontMessages.Add(text); } } return(""); } catch (Exception e) { Engine.Instance.Logs.LogVerbose(LanguageManager.GetText("ProviderRefreshFail", Title, e.Message)); return(LanguageManager.GetText("ProviderRefreshFail", Title, e.Message)); } }
public override void OnRun() { if (GetCanRun() == false) { m_timeEvery = 1000; } else { Dictionary <string, ConnectionInfo> connections; // Note: If Pinger is not enabled, works like all ping results is 0. bool enabled = GetEnabled(); int timeNow = UtilsCore.UnixTimeStamp(); int jobsLimit = Engine.Instance.Storage.GetInt("pinger.jobs"); lock (Engine.Instance.Connections) connections = new Dictionary <string, ConnectionInfo>(Engine.Instance.Connections); bool startOne = false; foreach (ConnectionInfo connectionInfo in connections.Values) { if (GetCanRun() == false) { break; } int delaySuccess = GetPingerDelaySuccess(connectionInfo); int delayRetry = GetPingerDelayRetry(connectionInfo); int delay = delaySuccess; if (connectionInfo.PingFailedConsecutive > 0) { delay = delayRetry; } if (timeNow - connectionInfo.LastPingTest >= delay) { bool canPingServer = enabled; if (connectionInfo.CanPing() == false) { canPingServer = false; } if (canPingServer) { if (Jobs.Count < jobsLimit) { connectionInfo.LastPingTest = timeNow; PingerJob job = new PingerJob(); job.Server = connectionInfo; ThreadPool.QueueUserWorkItem(new WaitCallback(DoPing), job); startOne = true; } } else { if (connectionInfo.Ping != -1) { //connectionInfo.LastPingTest = timeNow; // <2.13.4 connectionInfo.LastPingTest = 0; connectionInfo.PingTests = 0; connectionInfo.PingFailedConsecutive = 0; connectionInfo.Ping = -1; connectionInfo.LastPingResult = connectionInfo.LastPingTest; connectionInfo.LastPingSuccess = connectionInfo.LastPingTest; Engine.Instance.MarkServersListUpdated(); } } } if (m_cancelRequested) { return; } } if (startOne) { m_timeEvery = 100; } else { m_timeEvery = 1000; } } }
public override void OnUpdateIps() { base.OnUpdateIps(); // Remember: Rules must be in order: options, normalization, queueing, translation, filtering string pf = ""; pf += "# " + Engine.Instance.GenerateFileHeader() + "\n"; pf += "# Block policy, RST for quickly notice\n"; pf += "set block-policy return\n"; // 2.9 pf += "# Skip interfaces: lo0 and utun (only when connected)\n"; // 2.9 if (m_connected) { pf += "set skip on { lo0 " + Engine.Instance.ConnectionActive.InterfaceId + " }\n"; } else { pf += "set skip on { lo0 }\n"; } pf += "# Scrub\n"; pf += "scrub in all\n"; // 2.9 pf += "# General rule\n"; if (Engine.Instance.Storage.Get("netlock.incoming") == "allow") { pf += "pass in all\n"; } else { pf += "block in all\n"; } if (Engine.Instance.Storage.Get("netlock.outgoing") == "allow") { pf += "pass out all\n"; } else { pf += "block out all\n"; } if (Engine.Instance.Storage.GetBool("netlock.allow_private")) { pf += "# IPv4 - Private networks\n"; pf += "pass out quick inet from 192.168.0.0/16 to 192.168.0.0/16\n"; pf += "pass in quick inet from 192.168.0.0/16 to 192.168.0.0/16\n"; pf += "pass out quick inet from 172.16.0.0/12 to 172.16.0.0/12\n"; pf += "pass in quick inet from 172.16.0.0/12 to 172.16.0.0/12\n"; pf += "pass out quick inet from 10.0.0.0/8 to 10.0.0.0/8\n"; pf += "pass in quick inet from 10.0.0.0/8 to 10.0.0.0/8\n"; pf += "# IPv4 - Multicast\n"; pf += "pass out quick inet from 192.168.0.0/16 to 224.0.0.0/24\n"; pf += "pass out quick inet from 172.16.0.0/12 to 224.0.0.0/24\n"; pf += "pass out quick inet from 10.0.0.0/8 to 224.0.0.0/24\n"; pf += "# IPv4 - Simple Service Discovery Protocol address\n"; pf += "pass out quick inet from 192.168.0.0/16 to 239.255.255.250/32\n"; pf += "pass out quick inet from 172.16.0.0/12 to 239.255.255.250/32\n"; pf += "pass out quick inet from 10.0.0.0/8 to 239.255.255.250/32\n"; pf += "# IPv4 - Service Location Protocol version 2 address\n"; pf += "pass out quick inet from 192.168.0.0/16 to 239.255.255.253/32\n"; pf += "pass out quick inet from 172.16.0.0/12 to 239.255.255.253/32\n"; pf += "pass out quick inet from 10.0.0.0/8 to 239.255.255.253/32\n"; pf += "# IPv6 - Allow Link-Local addresses\n"; pf += "pass out quick inet6 from fe80::/10 to fe80::/10\n"; pf += "pass in quick inet6 from fe80::/10 to fe80::/10\n"; pf += "# IPv6 - Allow Link-Local addresses\n"; pf += "pass out quick inet6 from ff00::/8 to ff00::/8\n"; pf += "pass in quick inet6 from ff00::/8 to ff00::/8\n"; } if (Engine.Instance.Storage.GetBool("netlock.allow_ping")) { pf += "# Allow ICMP\n"; pf += "pass quick proto icmp\n"; // 2.9 // Old macOS throw "unknown protocol icmp6". We don't known from when, so use icmp6 if High Sierra and above. if (UtilsCore.CompareVersions(Platform.Instance.GetName(), "10.13") >= 0) { pf += "pass quick proto icmp6 all\n"; // 2.14.0 } } IpAddresses ipsWhiteListOutgoing = GetIpsWhiteListOutgoing(true); pf += "# Specific ranges\n"; foreach (IpAddress ip in ipsWhiteListOutgoing.IPs) { if (ip.IsV4) { pf += "pass out quick inet from any to " + ip.ToCIDR() + "\n"; } else if (ip.IsV6) { pf += "pass out quick inet6 from any to " + ip.ToCIDR() + "\n"; } } if (Platform.Instance.FileContentsWriteText(m_filePfConf.Path, pf)) { Engine.Instance.Logs.Log(LogType.Verbose, "macOS - PF rules updated, reloading"); SystemShell s = new SystemShell(); s.Path = m_pfctlPath; s.Arguments.Add("-v"); s.Arguments.Add("-f"); s.Arguments.Add(SystemShell.EscapePath(m_filePfConf.Path)); if (s.Run() == false) { throw new Exception(Messages.NetworkLockMacOSUnableToStart); } if (s.StdErr.Contains("rules not loaded")) { throw new Exception(Messages.NetworkLockMacOSUnableToStart); } } }
// This is the only method about exchange data between this software and AirVPN infrastructure. // We don't use SSL. Useless layer in our case, and we need to fetch hostname and direct IP that don't permit common-name match. // 'S' is the AES 256 bit one-time session key, crypted with a RSA 4096 public-key. // 'D' is the data from the client to our server, crypted with the AES. // The server answer is XML decrypted with the same AES session. public static XmlDocument FetchUrl(string authPublicKey, string url, Dictionary <string, string> parameters) { // AES using (RijndaelManaged rijAlg = new RijndaelManaged()) { rijAlg.KeySize = 256; rijAlg.GenerateKey(); rijAlg.GenerateIV(); // Generate S // Bug workaround: Xamarin 6.1.2 macOS throw an 'Default constructor not found for type System.Diagnostics.FilterElement' error. // in 'new System.Xml.Serialization.XmlSerializer', so i avoid that. /* * StringReader sr = new System.IO.StringReader(authPublicKey); * System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); * RSAParameters publicKey = (RSAParameters)xs.Deserialize(sr); */ RSAParameters publicKey = new RSAParameters(); XmlDocument docAuthPublicKey = new XmlDocument(); docAuthPublicKey.LoadXml(authPublicKey); publicKey.Modulus = Convert.FromBase64String(docAuthPublicKey.DocumentElement["Modulus"].InnerText); publicKey.Exponent = Convert.FromBase64String(docAuthPublicKey.DocumentElement["Exponent"].InnerText); Dictionary <string, byte[]> assocParamS = new Dictionary <string, byte[]>(); assocParamS["key"] = rijAlg.Key; assocParamS["iv"] = rijAlg.IV; byte[] bytesParamS = null; using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider()) { csp.ImportParameters(publicKey); bytesParamS = csp.Encrypt(UtilsCore.AssocToUtf8Bytes(assocParamS), false); } // Generate D byte[] aesDataIn = UtilsCore.AssocToUtf8Bytes(parameters); byte[] bytesParamD = null; { MemoryStream aesCryptStream = null; CryptoStream aesCryptStream2 = null; try { aesCryptStream = new MemoryStream(); using (ICryptoTransform aesEncryptor = rijAlg.CreateEncryptor()) { aesCryptStream2 = new CryptoStream(aesCryptStream, aesEncryptor, CryptoStreamMode.Write); aesCryptStream2.Write(aesDataIn, 0, aesDataIn.Length); aesCryptStream2.FlushFinalBlock(); bytesParamD = aesCryptStream.ToArray(); } } finally { if (aesCryptStream2 != null) { aesCryptStream2.Dispose(); } else if (aesCryptStream != null) { aesCryptStream.Dispose(); } } } // HTTP Fetch HttpRequest request = new HttpRequest(); request.Url = url; request.Parameters["s"] = UtilsString.Base64Encode(bytesParamS); request.Parameters["d"] = UtilsString.Base64Encode(bytesParamD); HttpResponse response = Engine.Instance.FetchUrl(request); try { byte[] fetchResponse = response.BufferData; byte[] fetchResponsePlain = null; MemoryStream aesDecryptStream = null; CryptoStream aesDecryptStream2 = null; // Decrypt answer try { aesDecryptStream = new MemoryStream(); using (ICryptoTransform aesDecryptor = rijAlg.CreateDecryptor()) { aesDecryptStream2 = new CryptoStream(aesDecryptStream, aesDecryptor, CryptoStreamMode.Write); aesDecryptStream2.Write(fetchResponse, 0, fetchResponse.Length); aesDecryptStream2.FlushFinalBlock(); fetchResponsePlain = aesDecryptStream.ToArray(); } } finally { if (aesDecryptStream2 != null) { aesDecryptStream2.Dispose(); } else if (aesDecryptStream != null) { aesDecryptStream.Dispose(); } } string finalData = System.Text.Encoding.UTF8.GetString(fetchResponsePlain); XmlDocument doc = new XmlDocument(); doc.LoadXml(finalData); return(doc); } catch (Exception ex) { string message = ""; if (response.GetHeader("location") != "") { message = MessagesFormatter.Format(Messages.ManifestFailedUnexpected302, response.GetHeader("location")); } else { message = ex.Message + " - " + response.GetLineReport(); } throw new Exception(message); } } }
public static XmlDocument FetchUrls(string title, string authPublicKey, List <string> urls, Dictionary <string, string> parameters) { parameters["login"] = Engine.Instance.Storage.Get("login"); parameters["password"] = Engine.Instance.Storage.Get("password"); parameters["system"] = Platform.Instance.GetSystemCode(); parameters["version"] = Constants.VersionInt.ToString(CultureInfo.InvariantCulture); string firstError = ""; int hostN = 0; foreach (string url in urls) { string host = UtilsCore.HostFromUrl(url); hostN++; if (IpAddress.IsIP(host) == false) { // If locked network are enabled, skip the hostname and try only by IP. // To avoid DNS issue (generally, to avoid losing time). if (Engine.Instance.NetworkLockManager.IsDnsResolutionAvailable(host) == false) { continue; } } try { RouteScope routeScope = new RouteScope(host); XmlDocument xmlDoc = FetchUrl(authPublicKey, url, parameters); routeScope.End(); if (xmlDoc == null) { throw new Exception("No answer."); } if (xmlDoc.DocumentElement.Attributes["error"] != null) { throw new Exception(xmlDoc.DocumentElement.Attributes["error"].Value); } return(xmlDoc); } catch (Exception e) { string info = e.Message; string proxyMode = Engine.Instance.Storage.Get("proxy.mode").ToLowerInvariant(); string proxyWhen = Engine.Instance.Storage.Get("proxy.when").ToLowerInvariant(); string proxyAuth = Engine.Instance.Storage.Get("proxy.auth").ToLowerInvariant(); if (proxyMode != "none") { info += " - with '" + proxyMode + "' (" + proxyWhen + ") proxy and '" + proxyAuth + "' auth"; } if (Engine.Instance.Storage.GetBool("advanced.expert")) { Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.ExchangeTryFailed, title, hostN.ToString(), info)); } if (firstError == "") { firstError = info; } } } throw new Exception(firstError); }