public override bool OnIpV6Restore() { foreach (IpV6ModeEntry entry in m_listIpV6Mode) { if (entry.Mode == "Off") { SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6off", SystemShell.EscapeInsideQuote(entry.Interface) }); } else if (entry.Mode == "Automatic") { SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6automatic", SystemShell.EscapeInsideQuote(entry.Interface) }); } else if (entry.Mode == "LinkLocal") { SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6LinkLocal", SystemShell.EscapeInsideQuote(entry.Interface) }); } else if (entry.Mode == "Manual") { SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6manual", SystemShell.EscapeInsideQuote(entry.Interface), entry.Address, entry.PrefixLength, entry.Router }); } Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterIpV6Restored, entry.Interface)); } m_listIpV6Mode.Clear(); Recovery.Save(); base.OnIpV6Restore(); return(true); }
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 static bool RemoveItem(WfpItem item) { lock (Items) { if (Items.ContainsValue(item) == false) { throw new Exception("Windows WFP, unexpected: Rule '" + item.Code + "' not exists"); } foreach (UInt64 id in item.FirewallIds) { bool result = RemoveItemId(id); if (result == false) { throw new Exception(MessagesFormatter.Format(Messages.WfpRuleRemoveFail, NativeMethods.WfpGetLastError())); } } Items.Remove(item.Code); if (Items.Count == 0) { } } return(true); }
public override bool OnIpV6Restore() { foreach (IpV6ModeEntry entry in m_listIpV6Mode) { if (entry.Mode == "Off") { ShellCmd("networksetup -setv6off \"" + SystemShell.EscapeInsideQuote(entry.Interface) + "\""); } else if (entry.Mode == "Automatic") { ShellCmd("networksetup -setv6automatic \"" + SystemShell.EscapeInsideQuote(entry.Interface) + "\""); } else if (entry.Mode == "LinkLocal") { ShellCmd("networksetup -setv6LinkLocal \"" + SystemShell.EscapeInsideQuote(entry.Interface) + "\""); } else if (entry.Mode == "Manual") { ShellCmd("networksetup -setv6manual \"" + SystemShell.EscapeInsideQuote(entry.Interface) + "\" " + entry.Address + " " + entry.PrefixLength + " " + entry.Router); // IJTF2 // TOCHECK } Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterIpV6Restored, entry.Interface)); } m_listIpV6Mode.Clear(); Recovery.Save(); base.OnIpV6Restore(); return(true); }
public override bool OnDnsSwitchDo(IpAddresses dns) { string mode = Engine.Instance.Storage.GetLower("dns.mode"); if (mode == "auto") { string[] interfaces = GetInterfaces(); foreach (string i in interfaces) { string i2 = i.Trim(); string currentStr = SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-getdnsservers", SystemShell.EscapeInsideQuote(i2) }); // v2 IpAddresses current = new IpAddresses(); foreach (string line in currentStr.Split('\n')) { string ip = line.Trim(); if (IpAddress.IsIP(ip)) { current.Add(ip); } } if (dns.Equals(current) == false) { DnsSwitchEntry e = new DnsSwitchEntry(); e.Name = i2; e.Dns = current.Addresses; m_listDnsSwitch.Add(e); SystemShell s = new SystemShell(); s.Path = LocateExecutable("networksetup"); s.Arguments.Add("-setdnsservers"); s.Arguments.Add(SystemShell.EscapeInsideQuote(i2)); if (dns.IPs.Count == 0) { s.Arguments.Add("empty"); } else { foreach (IpAddress ip in dns.IPs) { s.Arguments.Add(ip.Address); } } s.Run(); Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterDnsDone, i2, ((current.Count == 0) ? "Automatic" : current.Addresses), dns.Addresses)); } } Recovery.Save(); } base.OnDnsSwitchDo(dns); return(true); }
public override string ToString() { if (Engine.Instance.IsConnected()) { return(MessagesFormatter.Format(Messages.PingerStatsPending, Utils.FormatTime(LatestCheckDate))); } else { return(MessagesFormatter.Format(Messages.PingerStatsNormal, Invalid.ToString(), Utils.FormatTime(OlderCheckDate), Utils.FormatTime(LatestCheckDate))); } }
public override void AwakeFromNib() { base.AwakeFromNib(); Window.Title = Constants.Name + " - " + Messages.WindowsAboutTitle; CmdHomePage.Title = UiClient.Instance.Data["links"]["help"]["website"].Value as string; CmdSoftware.Title = UiClient.Instance.Data["links"]["help"]["general"].Value as string; CmdSources.Title = UiClient.Instance.Data["links"]["github"].Value as string; TxtVersion.StringValue = Messages.WindowsAboutVersion + " " + Constants.VersionDesc; LblThanks.StringValue = MessagesFormatter.Format(Messages.WindowsAboutThanks, String.Join(", ", Constants.Thanks.Split(';'))); CmdHomePage.Activated += (object sender, EventArgs e) => { GuiUtils.OpenUrl(UiClient.Instance.Data["links"]["help"]["website"].Value as string); }; CmdSoftware.Activated += (object sender, EventArgs e) => { GuiUtils.OpenUrl(UiClient.Instance.Data["links"]["help"]["general"].Value as string); }; CmdSources.Activated += (object sender, EventArgs e) => { GuiUtils.OpenUrl(UiClient.Instance.Data["links"]["github"].Value as string); }; CmdAirVPN.Activated += (object sender, EventArgs e) => { GuiUtils.OpenUrl("https://airvpn.org"); }; CmdLicense.Activated += (object sender, EventArgs e) => { (Engine.Instance as UI.Cocoa.Osx.Engine).MainWindow.ShowText(Window, "License", UiClient.Instance.Data["about"]["license"].Value as string); }; CmdLibraries.Activated += (object sender, EventArgs e) => { (Engine.Instance as UI.Cocoa.Osx.Engine).MainWindow.ShowText(Window, "Libraries and Tools", UiClient.Instance.Data["about"]["libraries"].Value as string); }; CmdOk.Activated += (object sender, EventArgs e) => { this.Close(); NSApplication.SharedApplication.StopModal(); }; CmdSystemReport.Activated += (object sender, EventArgs e) => { UiClient.Instance.Command("system.report.start"); }; }
public override bool OnDnsSwitchDo(string dns) { string mode = Engine.Instance.Storage.GetLower("dns.mode"); if (mode == "auto") { string[] interfaces = GetInterfaces(); foreach (string i in interfaces) { string i2 = i.Trim(); string current = ShellCmd("networksetup -getdnsservers \"" + SystemShell.EscapeInsideQuote(i2) + "\""); // v2 List <string> ips = new List <string>(); foreach (string line in current.Split('\n')) { string ip = line.Trim(); if (IpAddress.IsIP(ip)) { ips.Add(ip); } } if (ips.Count != 0) { current = String.Join(",", ips.ToArray()); } else { current = ""; } if (current != dns) { // Switch Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterDnsDone, i2, ((current == "") ? "Automatic" : current), dns)); DnsSwitchEntry e = new DnsSwitchEntry(); e.Name = i2; e.Dns = current; m_listDnsSwitch.Add(e); string dns2 = dns.Replace(",", "\" \""); ShellCmd("networksetup -setdnsservers \"" + SystemShell.EscapeInsideQuote(i2) + "\" \"" + dns2 + "\""); // IJTF2 eh? } } Recovery.Save(); } base.OnDnsSwitchDo(dns); return(true); }
public override bool RouteRemove(Json jRoute) { IpAddress ip = jRoute["address"].Value as string; if (ip.Valid == false) { return(false); } IpAddress gateway = jRoute["gateway"].Value as string; if (gateway.Valid == false) { return(false); } SystemShell s = new SystemShell(); s.Path = LocateExecutable("route"); s.Arguments.Add("-n"); s.Arguments.Add("delete"); if (ip.IsV6) { s.Arguments.Add("-inet6"); } s.Arguments.Add(ip.ToCIDR()); s.Arguments.Add(gateway.Address); s.ExceptionIfFail = true; s.Run(); string result = s.StdErr.Trim(); if (result == "") { return(base.RouteRemove(jRoute)); } else { // Remember: Route deletion can occur in a second moment (for example a Recovery phase). // Still accepted: The device are not available anymore, so the route are already deleted. // Still accepted: Already deleted. if (result.ToLowerInvariant().Contains("not in table")) { return(base.RouteRemove(jRoute)); } // Unexpected/unknown error. Engine.Instance.Logs.LogWarning(MessagesFormatter.Format(Messages.RouteDelFailed, ip.ToCIDR(), gateway.ToCIDR(), result)); return(false); } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); CommonInit(Messages.WindowsAboutTitle); lnkWebsite.Text = Core.UI.App.Manifest["links"]["help"]["website"].Value as string; lnkManual.Text = Core.UI.App.Manifest["links"]["help"]["general"].Value as string; lnkSources.Text = Core.UI.App.Manifest["links"]["github"].Value as string; lblVersion.Text = Messages.WindowsAboutVersion + " " + Constants.VersionDesc; lblThanks.Text = MessagesFormatter.Format(Messages.WindowsAboutThanks, String.Join(", ", Constants.Thanks.Split(';'))); }
public override string OnRefresh() { base.OnRefresh(); string pathScan = Path; // Engine.Instance.Logs.LogVerbose(MessagesFormatter.Format(Messages.ProviderRefreshStart, Title)); List <ConnectionInfo> connections = new List <ConnectionInfo>(); // Scan directory if (pathScan != "") { if (Directory.Exists(pathScan)) { ScanDir(pathScan.Trim(), OptionRecursive, connections); } else { Engine.Instance.Logs.Log(LogType.Warning, MessagesFormatter.Format(Messages.ProvidersOpenVpnPathNotFound, pathScan, Title)); } } // Remove profiles for (;;) { bool changed = false; foreach (XmlElement nodeProfile in Profiles.ChildNodes) { if (nodeProfile.HasAttribute("checked") == false) { Profiles.RemoveChild(nodeProfile); changed = true; } } if (changed == false) { break; } } // Clean flags foreach (XmlElement nodeProfile in Profiles.ChildNodes) { nodeProfile.Attributes.RemoveNamedItem("checked"); } Engine.Instance.Logs.LogVerbose(MessagesFormatter.Format(Messages.ProviderRefreshDone, Title)); return(""); }
public static void Start() { NativeMethods.WfpInit(GetName()); XmlDocument xmlStart = new XmlDocument(); XmlElement xmlInfo = xmlStart.CreateElement("firewall"); xmlInfo.SetAttribute("description", Constants.Name); xmlInfo.SetAttribute("weight", "max"); xmlInfo.SetAttribute("dynamic", GetDynamicMode() ? "true" : "false"); if (NativeMethods.WfpStart(xmlInfo.OuterXml) == false) { throw new Exception(MessagesFormatter.Format(Messages.WfpStartFail, NativeMethods.WfpGetLastError())); } }
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 bool OnIpV6Do() { if (Engine.Instance.Storage.GetLower("ipv6.mode") == "disable") { string[] interfaces = GetInterfaces(); foreach (string i in interfaces) { string getInfo = SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-getinfo", SystemShell.EscapeInsideQuote(i) }); string mode = Utils.RegExMatchOne(getInfo, "^IPv6: (.*?)$"); string address = Utils.RegExMatchOne(getInfo, "^IPv6 IP address: (.*?)$"); if ((mode == "") && (address != "")) { mode = "LinkLocal"; } if (mode != "Off") { IpV6ModeEntry entry = new IpV6ModeEntry(); entry.Interface = i; entry.Mode = mode; entry.Address = address; if (mode == "Manual") { entry.Router = Utils.RegExMatchOne(getInfo, "^IPv6 IP Router: (.*?)$"); entry.PrefixLength = Utils.RegExMatchOne(getInfo, "^IPv6 Prefix Length: (.*?)$"); } m_listIpV6Mode.Add(entry); SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6off", SystemShell.EscapeInsideQuote(i) }); Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterIpV6Disabled, i)); } } Recovery.Save(); } base.OnIpV6Do(); return(true); }
public override bool OnDnsSwitchRestore() { foreach (DnsSwitchEntry e in m_listDnsSwitch) { /* * string v = e.Dns; * if (v == "") * v = "empty"; * v = v.Replace(",", "\" \""); * * SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setdnsservers", SystemShell.EscapeInsideQuote(e.Name), v }); */ IpAddresses dns = new IpAddresses(); dns.Add(e.Dns); SystemShell s = new SystemShell(); s.Path = LocateExecutable("networksetup"); s.Arguments.Add("-setdnsservers"); s.Arguments.Add(SystemShell.EscapeInsideQuote(e.Name)); if (dns.Count == 0) { s.Arguments.Add("empty"); } else { foreach (IpAddress ip in dns.IPs) { s.Arguments.Add(ip.Address); } } s.Run(); Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterDnsRestored, e.Name, ((e.Dns == "") ? "Automatic" : e.Dns))); } m_listDnsSwitch.Clear(); Recovery.Save(); base.OnDnsSwitchRestore(); return(true); }
public override void OnBuildOvpnAuth(OvpnBuilder ovpn) { base.OnBuildOvpnAuth(ovpn); string key = Engine.Instance.Storage.Get("key"); XmlNode nodeUser = User; if (nodeUser != null) { ovpn.AppendDirective("<ca>", nodeUser.Attributes["ca"].Value, ""); XmlElement xmlKey = nodeUser.SelectSingleNode("keys/key[@name='" + key + "']") as XmlElement; if (xmlKey == null) { throw new Exception(MessagesFormatter.Format(Messages.KeyNotFound, key)); } ovpn.AppendDirective("<cert>", xmlKey.Attributes["crt"].Value, ""); ovpn.AppendDirective("<key>", xmlKey.Attributes["key"].Value, ""); } }
public override void OnBuildConnectionActiveAuth(ConnectionActive connectionActive) { base.OnBuildConnectionActiveAuth(connectionActive); string key = Engine.Instance.Storage.Get("key"); XmlNode nodeUser = User; if (nodeUser != null) { connectionActive.OpenVpnProfileStartup.AppendDirective("<ca>", nodeUser.Attributes["ca"].Value, ""); XmlElement xmlKey = nodeUser.SelectSingleNode("keys/key[@name='" + key + "']") as XmlElement; if (xmlKey == null) { throw new Exception(MessagesFormatter.Format(Messages.KeyNotFound, key)); } connectionActive.OpenVpnProfileStartup.AppendDirective("<cert>", xmlKey.Attributes["crt"].Value, ""); connectionActive.OpenVpnProfileStartup.AppendDirective("<key>", xmlKey.Attributes["key"].Value, ""); } }
public override bool RouteAdd(Json jRoute) { IpAddress ip = jRoute["address"].Value as string; if (ip.Valid == false) { return(false); } IpAddress gateway = jRoute["gateway"].Value as string; if (gateway.Valid == false) { return(false); } SystemShell s = new SystemShell(); s.Path = LocateExecutable("route"); s.Arguments.Add("-n"); s.Arguments.Add("add"); if (ip.IsV6) { s.Arguments.Add("-inet6"); } s.Arguments.Add(ip.ToCIDR()); s.Arguments.Add(gateway.Address); s.ExceptionIfFail = true; s.Run(); string result = s.StdErr.Trim(); if (result == "") { return(base.RouteAdd(jRoute)); } else { Engine.Instance.Logs.LogWarning(MessagesFormatter.Format(Messages.RouteAddFailed, ip.ToCIDR(), gateway.ToCIDR(), result)); return(false); } }
public override void Deactivation() { base.Deactivation(); foreach (RouteEntry Entry in EntryAdded.Values) { Entry.Remove(); } foreach (RouteEntry Entry in EntryRemoved.Values) { Entry.Add(); Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkLockRouteRestored, Entry.ToString())); } DefaultGateway = ""; DefaultInterface = ""; EntryAdded.Clear(); EntryRemoved.Clear(); }
public override bool OnDnsSwitchRestore() { foreach (DnsSwitchEntry e in m_listDnsSwitch) { string v = e.Dns; if (v == "") { v = "empty"; } v = v.Replace(",", "\" \""); Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterDnsRestored, e.Name, ((e.Dns == "") ? "Automatic" : e.Dns))); ShellCmd("networksetup -setdnsservers \"" + e.Name + "\" \"" + v + "\""); // IJTF2 } m_listDnsSwitch.Clear(); Recovery.Save(); base.OnDnsSwitchRestore(); return(true); }
public static WfpItem AddItem(string code, XmlElement xml) { lock (Items) { if (Items.ContainsKey(code)) { throw new Exception("Windows WFP, unexpected: Rule '" + code + "' already exists"); } WfpItem item = new WfpItem(); item.Code = code; List <string> layers = new List <string>(); if (xml.GetAttribute("layer") == "all") { layers.Add("ale_auth_recv_accept_v4"); layers.Add("ale_auth_recv_accept_v6"); layers.Add("ale_auth_connect_v4"); layers.Add("ale_auth_connect_v6"); layers.Add("ale_flow_established_v4"); layers.Add("ale_flow_established_v6"); } else if (xml.GetAttribute("layer") == "all-in") { layers.Add("ale_auth_recv_accept_v4"); layers.Add("ale_auth_recv_accept_v6"); } else if (xml.GetAttribute("layer") == "all-out") { layers.Add("ale_auth_connect_v4"); layers.Add("ale_auth_connect_v6"); } else if (xml.GetAttribute("layer") == "ipv4") { layers.Add("ale_auth_recv_accept_v4"); layers.Add("ale_auth_connect_v4"); layers.Add("ale_flow_established_v4"); } else if (xml.GetAttribute("layer") == "ipv6") { layers.Add("ale_auth_recv_accept_v6"); layers.Add("ale_auth_connect_v6"); layers.Add("ale_flow_established_v6"); } else if (xml.GetAttribute("layer") == "ipv4-in") { layers.Add("ale_auth_recv_accept_v4"); } else if (xml.GetAttribute("layer") == "ipv6-in") { layers.Add("ale_auth_recv_accept_v6"); } else if (xml.GetAttribute("layer") == "ipv4-out") { layers.Add("ale_auth_connect_v4"); } else if (xml.GetAttribute("layer") == "ipv6-out") { layers.Add("ale_auth_connect_v6"); } else { layers.Add(xml.GetAttribute("layer")); } if (xml.HasAttribute("weight") == false) { xml.SetAttribute("weight", "1000"); } foreach (string layer in layers) { XmlElement xmlClone = xml.CloneNode(true) as XmlElement; xmlClone.SetAttribute("layer", layer); string xmlStr = xmlClone.OuterXml; UInt64 id1 = NativeMethods.WfpRuleAdd(xmlStr); if (id1 == 0) { throw new Exception(MessagesFormatter.Format(Messages.WfpRuleAddFail, NativeMethods.WfpGetLastError(), xmlStr)); } else { // Only used for debugging WFP issue with rules in some system // Engine.Instance.Logs.Log(LogType.Verbose, Messages.Format(Messages.WfpRuleAddSuccess, xmlStr)); item.FirewallIds.Add(id1); } } Items[item.Code] = item; return(item); } }
public void RefreshUi(Engine.RefreshUiMode mode) { try { if ((mode == Engine.RefreshUiMode.MainMessage) || (mode == Engine.RefreshUiMode.Full)) { if (Engine.CurrentServer != null) { ImgTopFlag.Image = NSImage.ImageNamed("flag_" + Engine.CurrentServer.CountryCode.ToLowerInvariant() + ".png"); } else { ImgTopFlag.Image = NSImage.ImageNamed("notconnected.png"); } LblWaiting1.StringValue = Engine.WaitMessage; if (Engine.IsWaiting()) { ImgProgress.StartAnimation(this); ImgTopPanel.Image = NSImage.ImageNamed("topbar_osx_yellow.png"); MnuTrayStatus.Image = NSImage.ImageNamed("status_yellow_16.png"); LblTopStatus.StringValue = Engine.WaitMessage; TabOverview.SelectAt(1); CmdCancel.Hidden = (Engine.IsWaitingCancelAllowed() == false); CmdCancel.Enabled = (Engine.IsWaitingCancelPending() == false); MnuTrayConnect.Enabled = CmdCancel.Enabled; } else if (Engine.IsConnected()) { ImgProgress.StopAnimation(this); ImgTopPanel.Image = NSImage.ImageNamed("topbar_osx_green.png"); MnuTrayStatus.Image = NSImage.ImageNamed("status_green_16.png"); LblTopStatus.StringValue = MessagesFormatter.Format(MessagesUi.TopBarConnected, Engine.CurrentServer.DisplayName); TabOverview.SelectAt(2); LblConnectedServerName.StringValue = Engine.CurrentServer.DisplayName; LblConnectedLocation.StringValue = Engine.CurrentServer.GetLocationForList(); TxtConnectedExitIp.StringValue = Engine.ConnectedExitIP.ToString(); ImgConnectedCountry.Image = NSImage.ImageNamed("flag_" + Engine.CurrentServer.CountryCode.ToLowerInvariant() + ".png"); } else { ImgProgress.StopAnimation(this); ImgTopPanel.Image = NSImage.ImageNamed("topbar_osx_red.png"); MnuTrayStatus.Image = NSImage.ImageNamed("status_red_16.png"); if (Engine.Instance.NetworkLockManager.IsActive()) { LblTopStatus.StringValue = MessagesUi.TopBarNotConnectedLocked; } else { LblTopStatus.StringValue = MessagesUi.TopBarNotConnectedExposed; } TabOverview.SelectAt(0); } // Icon update if (StatusItem != null) { //string colorMode = GuiUtils.InterfaceColorMode (); string colorMode = Engine.Storage.Get("gui.osx.style"); if (Engine.IsConnected()) { StatusItem.Image = NSImage.ImageNamed("menubar_" + colorMode.ToLowerInvariant() + "_green.png"); //NSApplication.SharedApplication.DockTile. = DateTime.Now.ToString (); NSApplication.SharedApplication.ApplicationIconImage = NSImage.ImageNamed("icon.png"); } else { StatusItem.Image = NSImage.ImageNamed("menubar_" + colorMode.ToLowerInvariant() + "_red.png"); //NSApplication.SharedApplication.DockTile.Description = DateTime.Now.ToString (); NSApplication.SharedApplication.ApplicationIconImage = NSImage.ImageNamed("icon_gray.png"); } } EnabledUI(); } if ((mode == Engine.RefreshUiMode.Log) || (mode == Engine.RefreshUiMode.Full)) { lock (Engine.LogsPending) { while (Engine.LogsPending.Count > 0) { LogEntry l = Engine.LogsPending[0]; Engine.LogsPending.RemoveAt(0); Log(l); } } LblWaiting2.StringValue = Engine.Logs.GetLogDetailTitle(); } if ((mode == Engine.RefreshUiMode.Stats) || (mode == Engine.RefreshUiMode.Full)) { if (Engine.IsConnected()) { TxtConnectedSince.StringValue = Engine.Stats.GetValue("VpnConnectionStart"); TxtConnectedDownload.StringValue = Core.Utils.FormatBytes(Engine.ConnectedLastDownloadStep, true, false); TxtConnectedUpload.StringValue = Core.Utils.FormatBytes(Engine.ConnectedLastUploadStep, true, false); string msg = Engine.Instance.GetConnectedTrayText(true, true); string tmsg = Constants.Name + " - " + msg; this.Window.Title = tmsg; MnuTrayStatus.Title = "> " + msg; StatusItem.ToolTip = msg; StatusItem.Title = Engine.Instance.GetConnectedTrayText(Engine.Instance.Storage.GetBool("gui.osx.sysbar.show_speed"), Engine.Instance.Storage.GetBool("gui.osx.sysbar.show_server")); } } if ((mode == Engine.RefreshUiMode.Full)) { if (TableServersController != null) { TableServersController.RefreshUI(); } if (TableAreasController != null) { TableAreasController.RefreshUI(); } } } catch (Exception) { // TOFIX: OS X sometime throw an useless exception in closing phase } }
public HttpResponse Fetch(HttpRequest request) { HttpResponse response = new HttpResponse(); ExceptionIfRequired(); ProgramScope programScope = new ProgramScope(this.GetPath(), "curl"); // Don't use proxy if connected to the VPN, or in special cases (checking) during connection. bool bypassProxy = request.BypassProxy; if (bypassProxy == false) { bypassProxy = Engine.Instance.IsConnected(); } string dataParameters = ""; if (request.Parameters.Count > 0) { foreach (string k in request.Parameters.Keys) { if (dataParameters != "") { dataParameters += "&"; } dataParameters += SystemShell.EscapeAlphaNumeric(k) + "=" + Uri.EscapeUriString(request.Parameters[k]); } } string args = ""; if (bypassProxy == false) { string proxyMode = Engine.Instance.Storage.GetLower("proxy.mode"); string proxyWhen = Engine.Instance.Storage.GetLower("proxy.when"); string proxyHost = Engine.Instance.Storage.Get("proxy.host"); int proxyPort = Engine.Instance.Storage.GetInt("proxy.port"); string proxyAuth = Engine.Instance.Storage.Get("proxy.auth").ToLowerInvariant(); string proxyLogin = Engine.Instance.Storage.Get("proxy.login"); string proxyPassword = Engine.Instance.Storage.Get("proxy.password"); if ((proxyWhen == "none") || (proxyWhen == "openvpn")) { proxyMode = "none"; } if (proxyMode == "detect") { throw new Exception(Messages.ProxyDetectDeprecated); } if (proxyMode == "tor") { proxyMode = "socks"; proxyAuth = "none"; proxyLogin = ""; proxyPassword = ""; } if (proxyMode == "http") { args += " --proxy http://" + SystemShell.EscapeHost(proxyHost) + ":" + proxyPort.ToString(); } else if (proxyMode == "socks") { // curl support different types of proxy. OpenVPN not, only socks5. So, it's useless to support other kind of proxy here. args += " --proxy socks5://" + SystemShell.EscapeHost(proxyHost) + ":" + proxyPort.ToString(); } if ((proxyMode != "none") && (proxyAuth != "none")) { if (proxyAuth == "basic") { args += " --proxy-basic"; } else if (proxyAuth == "ntlm") { args += " --proxy-ntlm"; } if (SystemShell.EscapeInsideQuoteAcceptable(proxyLogin) == false) { throw new Exception(MessagesFormatter.Format(Messages.UnacceptableCharacters, "Proxy Login")); } if (SystemShell.EscapeInsideQuoteAcceptable(proxyPassword) == false) { throw new Exception(MessagesFormatter.Format(Messages.UnacceptableCharacters, "Proxy Password")); } if ((proxyLogin != "") && (proxyPassword != "")) { args += " --proxy-user \"" + SystemShell.EscapeInsideQuote(proxyLogin) + "\":\"" + SystemShell.EscapeInsideQuote(proxyPassword) + "\""; } } } args += " \"" + SystemShell.EscapeUrl(request.Url) + "\""; args += " -sS"; // -s Silent mode, -S with errors args += " --max-time " + Engine.Instance.Storage.GetInt("tools.curl.max-time").ToString(); string pathCacert = Engine.Instance.LocateResource("cacert.pem"); if (pathCacert != "") { args += " --cacert \"" + SystemShell.EscapePath(pathCacert) + "\""; } if (request.ForceResolve != "") { args += " --resolve " + request.ForceResolve; } if (dataParameters != "") { args += " --data \"" + dataParameters + "\""; } if (request.IpLayer == "4") { args += " -4"; } if (request.IpLayer == "6") { args += " -6"; } args += " -i"; string error = ""; try { using (Process p = new Process()) { p.StartInfo.FileName = SystemShell.EscapePath(this.GetPath()); p.StartInfo.Arguments = args; p.StartInfo.WorkingDirectory = ""; p.StartInfo.CreateNoWindow = true; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.Start(); { using (System.IO.MemoryStream Stream = new System.IO.MemoryStream()) { using (System.IO.MemoryStream StreamHeader = new System.IO.MemoryStream()) { using (System.IO.MemoryStream StreamBody = new System.IO.MemoryStream()) { byte[] buffer = new byte[4096]; int read; while ((read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length)) > 0) { Stream.Write(buffer, 0, read); } if (Stream.Length >= 4) { byte[] buffer2 = Stream.ToArray(); int i = 0; for (; i < Stream.Length - 4; i++) { if ((buffer2[i] == 13) && (buffer2[i + 1] == 10) && (buffer2[i + 2] == 13) && (buffer2[i + 3] == 10)) { StreamHeader.Write(buffer2, 0, i); StreamBody.Write(buffer2, i + 4, (int)Stream.Length - i - 4); break; } } if (StreamHeader.Length == 0) { StreamHeader.Write(buffer2, 0, (int)Stream.Length); } } else { StreamHeader.Write(Stream.ToArray(), 0, (int)Stream.Length); } response.BufferHeader = StreamHeader.ToArray(); response.BufferData = StreamBody.ToArray(); } } string headers = System.Text.Encoding.ASCII.GetString(response.BufferHeader); string[] headersLines = headers.Split('\n'); for (int l = 0; l < headersLines.Length; l++) { string line = headersLines[l]; if (l == 0) { response.StatusLine = line; } int posSep = line.IndexOf(":"); if (posSep != -1) { string k = line.Substring(0, posSep); string v = line.Substring(posSep + 1); response.Headers.Add(new KeyValuePair <string, string>(k.ToLowerInvariant().Trim(), v.Trim())); } } } } error = p.StandardError.ReadToEnd(); p.WaitForExit(); response.ExitCode = p.ExitCode; } } catch (Exception e) { error = e.Message; } programScope.End(); if (error != "") { throw new Exception(error.Trim()); } return(response); }
public string GetRequiredVersionMessage() { return(MessagesFormatter.Format(Messages.ToolsCurlVersionNotSupported, Version, minVersionRequired)); }
public override void AwakeFromNib() { base.AwakeFromNib(); Window.Title = Constants.Name + " - " + Messages.WindowsSettingsTitle; TableTabsController = new TableTabsController(TableTabs, TabMain); ChkNetLock.Activated += (object sender, EventArgs e) => { if (GuiUtils.GetCheck(ChkNetLock)) { if ((Engine.Instance as UI.Cocoa.Osx.Engine).MainWindow.NetworkLockKnowledge() == false) { GuiUtils.SetCheck(ChkNetLock, false); } } }; TableRoutes.Delegate = new TableRoutingDelegate(this); LblDnsServers.StringValue = Messages.WindowsSettingsDnsServers; TableDnsServers.Delegate = new TableDnsServersDelegate(this); TableAdvancedEvents.Delegate = new TableAdvancedEventsDelegate(this); LblLoggingHelp.StringValue = Messages.WindowsSettingsLoggingHelp; TableRoutingController = new TableRoutingController(this.TableRoutes); TableDnsServersController = new TableDnsServersController(this.TableDnsServers); TableAdvancedEventsController = new TableAdvancedEventsController(this.TableAdvancedEvents); CmdSave.Activated += (object sender, EventArgs e) => { try { if (Check()) { SaveOptions(); Close(); } } catch (Exception ex) { Core.Engine.Instance.Logs.Log(LogType.Fatal, ex); } }; CmdCancel.Activated += (object sender, EventArgs e) => { Close(); }; // General CmdGeneralTos.Activated += (object sender, EventArgs e) => { WindowTosController tos = new WindowTosController(); tos.Window.ReleasedWhenClosed = true; NSApplication.SharedApplication.RunModalForWindow(tos.Window); tos.Window.Close(); }; CmdResetToDefault.Activated += (object sender, EventArgs e) => { if (Engine.Instance.OnAskYesNo(Messages.ResetSettingsConfirm)) { Engine.Instance.Storage.ResetAll(false); ReadOptions(); GuiUtils.MessageBoxInfo(Messages.ResetSettingsDone); } }; // UI CboUiUnit.RemoveAllItems(); CboUiUnit.AddItem(Messages.WindowsSettingsUiUnit0); CboUiUnit.AddItem(Messages.WindowsSettingsUiUnit1); CboUiUnit.AddItem(Messages.WindowsSettingsUiUnit2); // Protocols CmdProtocolsHelp1.Activated += (object sender, EventArgs e) => { Engine.Instance.Command("ui.show.docs.protocols"); }; CmdProtocolsHelp2.Activated += (object sender, EventArgs e) => { Engine.Instance.Command("ui.show.docs.udp_vs_tcp"); }; ChkProtocolsAutomatic.Activated += (object sender, EventArgs e) => { EnableIde(); }; TableProtocols.Delegate = new TableProtocolsDelegate(this); TableProtocolsController = new TableProtocolsController(this.TableProtocols); // Proxy CboProxyType.RemoveAllItems(); CboProxyType.AddItem("None"); CboProxyType.AddItem("Http"); CboProxyType.AddItem("Socks"); CboProxyType.AddItem("Tor"); CboProxyWhen.RemoveAllItems(); CboProxyWhen.AddItem(Messages.WindowsSettingsProxyWhenAlways); CboProxyWhen.AddItem(Messages.WindowsSettingsProxyWhenWeb); CboProxyWhen.AddItem(Messages.WindowsSettingsProxyWhenOpenVPN); CboProxyWhen.AddItem(Messages.WindowsSettingsProxyWhenNone); CmdProxyTorHelp.Activated += (object sender, EventArgs e) => { Engine.Instance.Command("ui.show.docs.tor"); }; CboProxyType.Activated += (object sender, EventArgs e) => { EnableIde(); if (GuiUtils.GetSelected(CboProxyType) == "Tor") { TxtProxyPort.StringValue = "9150"; } else { TxtProxyPort.StringValue = "8080"; } }; CboProxyAuthentication.Activated += (object sender, EventArgs e) => { EnableIde(); }; CmdProxyTorTest.Activated += (object sender, EventArgs e) => { string result = TorControl.Test(TxtProxyHost.StringValue, Conversions.ToInt32(TxtProxyTorControlPort.StringValue), TxtProxyTorControlPassword.StringValue); GuiUtils.MessageBoxInfo(result); }; // Routes CboRoutesOtherwise.RemoveAllItems(); CboRoutesOtherwise.AddItem(RouteDirectionToDescription("in")); CboRoutesOtherwise.AddItem(RouteDirectionToDescription("out")); CboRoutesOtherwise.Activated += (object sender, EventArgs e) => { EnableIde(); }; TableRoutes.DoubleClick += (object sender, EventArgs e) => { RouteEdit(); }; CmdRouteAdd.Activated += (object sender, EventArgs e) => { RouteAdd(); }; CmdRouteRemove.Activated += (object sender, EventArgs e) => { RouteRemove(); }; CmdRouteEdit.Activated += (object sender, EventArgs e) => { RouteEdit(); }; // Advanced - General CmdAdvancedHelp.Activated += (object sender, EventArgs e) => { Engine.Instance.Command("ui.show.docs.advanced"); }; CboIpV6.RemoveAllItems(); CboIpV6.AddItem("None"); CboIpV6.AddItem("Disable"); CboAdvancedManifestRefresh.RemoveAllItems(); CboAdvancedManifestRefresh.AddItem("Automatic"); CboAdvancedManifestRefresh.AddItem("Never"); CboAdvancedManifestRefresh.AddItem("Every minute"); CboAdvancedManifestRefresh.AddItem("Every ten minute"); CboAdvancedManifestRefresh.AddItem("Every one hour"); LblOpenVpnRcvBuf.StringValue = Messages.WindowsSettingsOpenVpnRcvBuf + ":"; LblOpenVpnSndBuf.StringValue = Messages.WindowsSettingsOpenVpnSndBuf + ":"; CboOpenVpnRcvBuf.RemoveAllItems(); CboOpenVpnRcvBuf.AddItem(Messages.Automatic); CboOpenVpnRcvBuf.AddItem(Messages.WindowsSettingsOpenVpnDefault); CboOpenVpnRcvBuf.AddItem("8 KB"); CboOpenVpnRcvBuf.AddItem("16 KB"); CboOpenVpnRcvBuf.AddItem("32 KB"); CboOpenVpnRcvBuf.AddItem("64 KB"); CboOpenVpnRcvBuf.AddItem("128 KB"); CboOpenVpnRcvBuf.AddItem("256 KB"); CboOpenVpnRcvBuf.AddItem("512 KB"); CboOpenVpnSndBuf.RemoveAllItems(); CboOpenVpnSndBuf.AddItem(Messages.Automatic); CboOpenVpnSndBuf.AddItem(Messages.WindowsSettingsOpenVpnDefault); CboOpenVpnSndBuf.AddItem("8 KB"); CboOpenVpnSndBuf.AddItem("16 KB"); CboOpenVpnSndBuf.AddItem("32 KB"); CboOpenVpnSndBuf.AddItem("64 KB"); CboOpenVpnSndBuf.AddItem("128 KB"); CboOpenVpnSndBuf.AddItem("256 KB"); CboOpenVpnSndBuf.AddItem("512 KB"); CmdAdvancedOpenVpnPath.Activated += (object sender, EventArgs e) => { GuiUtils.SelectFile(this.Window, TxtAdvancedOpenVpnPath); }; // Advanced - DNS TableDnsServers.DoubleClick += (object sender, EventArgs e) => { DnsServersEdit(); }; CmdDnsAdd.Activated += (object sender, EventArgs e) => { DnsServersAdd(); }; CmdDnsRemove.Activated += (object sender, EventArgs e) => { DnsServersRemove(); }; CmdDnsEdit.Activated += (object sender, EventArgs e) => { DnsServersEdit(); }; // Advanced - Net Lock CmdLockHelp.Activated += (object sender, EventArgs e) => { Engine.Instance.Command("ui.show.docs.lock"); }; CboLockMode.RemoveAllItems(); CboLockMode.AddItem("None"); CboLockMode.AddItem("Automatic"); foreach (NetworkLockPlugin lockPlugin in Engine.Instance.NetworkLockManager.Modes) { CboLockMode.AddItem(lockPlugin.GetName()); } LblRoutesNetworkLockWarning.StringValue = Messages.WindowsSettingsRouteLockHelp; LblLockRoutingOutWarning.StringValue = Messages.NetworkLockNotAvailableWithRouteOut; // Advanced - Logging TxtLoggingPath.Changed += (object sender, EventArgs e) => { RefreshLogPreview(); }; CmdLoggingOpen.Activated += (object sender, EventArgs e) => { List <string> paths = Engine.Instance.Logs.ParseLogFilePath(TxtLoggingPath.StringValue); foreach (string path in paths) { if (Core.Platform.Instance.OpenDirectoryInFileManager(path) == false) { GuiUtils.MessageBoxError(MessagesFormatter.Format(Messages.WindowsSettingsLogsCannotOpenDirectory, path)); } } }; // Directives CboOpenVpnDirectivesSkipDefault.RemoveAllItems(); CboOpenVpnDirectivesSkipDefault.AddItem(Messages.WindowsSettingsOpenVpnDirectivesDefaultSkip1); CboOpenVpnDirectivesSkipDefault.AddItem(Messages.WindowsSettingsOpenVpnDirectivesDefaultSkip2); CmdOpenVpnDirectivesHelp.Activated += (object sender, EventArgs e) => { Engine.Instance.Command("ui.show.docs.directives"); }; CmdOpenVpnDirectivesCustomPathBrowse.Activated += (object sender, EventArgs e) => { GuiUtils.SelectFile(this.Window, TxtOpenVpnDirectivesCustomPath); }; // Advanced - Events TableAdvancedEvents.DoubleClick += (object sender, EventArgs e) => { AdvancedEventEdit(); }; CmdAdvancedEventsEdit.Activated += (object sender, EventArgs e) => { AdvancedEventEdit(); }; CmdAdvancedEventsClear.Activated += (object sender, EventArgs e) => { AdvancedEventClear(); }; ReadOptions(); EnableIde(); RefreshLogPreview(); }
public void ScanDir(string path, bool recursive, List <ConnectionInfo> connections) { if (path == "") { return; } try { foreach (string filePath in Directory.GetFiles(path)) { FileInfo fileInfo = new FileInfo(filePath); string extension = fileInfo.Extension.ToLowerInvariant().Trim(); if ((extension != ".ovpn") && (extension != ".conf")) { continue; } // Already listed? XmlElement nodeProfile = null; foreach (XmlElement nodeFind in Profiles.ChildNodes) { string pathFind = UtilsXml.XmlGetAttributeString(nodeFind, "path", ""); if (pathFind == fileInfo.FullName) { nodeProfile = nodeFind; break; } } // Skip if is already checked if ((nodeProfile != null) && (UtilsXml.XmlGetAttributeString(nodeProfile, "checked", "") != "")) { continue; } if (Platform.Instance.FileExists(filePath) == false) { continue; } // Compute values FileInfo file = new FileInfo(filePath); string hosts = ""; try { string ovpnOriginal = Platform.Instance.FileContentsReadText(file.FullName); OvpnBuilder ovpnBuilder = new OvpnBuilder(); ovpnBuilder.AppendDirectives(ovpnOriginal, "Original"); //string ovpnNormalized = ovpnBuilder.Get(); foreach (OvpnBuilder.Directive remoteDirective in ovpnBuilder.GetDirectiveList("remote")) { string host = remoteDirective.Text; int posPort = host.IndexOf(" "); if (posPort != -1) { host = host.Substring(0, posPort).Trim(); } if (hosts != "") { hosts += ","; } hosts += host; } if (nodeProfile == null) { nodeProfile = Profiles.OwnerDocument.CreateElement("profile"); Profiles.AppendChild(nodeProfile); } UtilsXml.XmlSetAttributeString(nodeProfile, "remote", hosts); UtilsXml.XmlSetAttributeString(nodeProfile, "path", file.FullName); UtilsXml.XmlSetAttributeString(nodeProfile, "checked", "1"); } catch (System.Exception e) { string message = MessagesFormatter.Format(Messages.ProvidersOpenVpnErrorProfile, file.FullName, this.Title, e.Message); // TOTRANSLATE Engine.Instance.Logs.Log(LogType.Warning, message); } } if (recursive) { foreach (string dirPath in Directory.GetDirectories(path)) { ScanDir(dirPath, recursive, connections); } } } catch (System.Exception e) { Engine.Instance.Logs.Log(e); } }
public byte[] FetchUrlEx(string url, System.Collections.Specialized.NameValueCollection parameters, string title, bool forceBypassProxy, string resolve) { if (Available() == false) { throw new Exception(Messages.ToolsCurlRequired); } if (Utils.CompareVersions(Version, minVersionRequired) == -1) { throw new Exception(GetRequiredVersionMessage()); } ProgramScope programScope = new ProgramScope(this.GetPath(), "curl"); // Don't use proxy if connected to the VPN, or in special cases (checking) during connection. bool bypassProxy = forceBypassProxy; if (bypassProxy == false) { bypassProxy = Engine.Instance.IsConnected(); } string dataParameters = ""; if (parameters != null) { foreach (string k in parameters.Keys) { if (dataParameters != "") { dataParameters += "&"; } dataParameters += SystemShell.EscapeAlphaNumeric(k) + "=" + Uri.EscapeUriString(parameters[k]); } } string args = ""; if (bypassProxy == false) { string proxyMode = Engine.Instance.Storage.Get("proxy.mode").ToLowerInvariant(); string proxyHost = Engine.Instance.Storage.Get("proxy.host"); int proxyPort = Engine.Instance.Storage.GetInt("proxy.port"); string proxyAuth = Engine.Instance.Storage.Get("proxy.auth").ToLowerInvariant(); string proxyLogin = Engine.Instance.Storage.Get("proxy.login"); string proxyPassword = Engine.Instance.Storage.Get("proxy.password"); if (proxyMode == "detect") { throw new Exception(Messages.ProxyDetectDeprecated); } if (proxyMode == "tor") { proxyMode = "socks"; proxyAuth = "none"; proxyLogin = ""; proxyPassword = ""; } if (proxyMode == "http") { args += " --proxy http://" + SystemShell.EscapeHost(proxyHost) + ":" + proxyPort.ToString(); } else if (proxyMode == "socks") { // curl support different types of proxy. OpenVPN not, only socks5. So, it's useless to support other kind of proxy here. args += " --proxy socks5://" + SystemShell.EscapeHost(proxyHost) + ":" + proxyPort.ToString(); } if ((proxyMode != "none") && (proxyAuth != "none")) { if (proxyAuth == "basic") { args += " --proxy-basic"; } else if (proxyAuth == "ntlm") { args += " --proxy-ntlm"; } if (SystemShell.EscapeInsideQuoteAcceptable(proxyLogin) == false) { throw new Exception(MessagesFormatter.Format(Messages.UnacceptableCharacters, "Proxy Login")); } if (SystemShell.EscapeInsideQuoteAcceptable(proxyPassword) == false) { throw new Exception(MessagesFormatter.Format(Messages.UnacceptableCharacters, "Proxy Password")); } if ((proxyLogin != "") && (proxyPassword != "")) { args += " --proxy-user \"" + SystemShell.EscapeInsideQuote(proxyLogin) + "\":\"" + SystemShell.EscapeInsideQuote(proxyPassword) + "\""; } } } args += " \"" + SystemShell.EscapeUrl(url) + "\""; args += " -sS"; // -s Silent mode, -S with errors args += " --max-time " + Engine.Instance.Storage.GetInt("tools.curl.max-time").ToString(); Tool cacertTool = Software.GetTool("cacert.pem"); if (cacertTool.Available()) { args += " --cacert \"" + SystemShell.EscapePath(cacertTool.Path) + "\""; } if (resolve != "") { args += " --resolve " + resolve; } if (dataParameters != "") { args += " --data \"" + dataParameters + "\""; } string error = ""; byte[] output = default(byte[]); int exitcode = -1; try { /* * if ((Engine.Instance != null) && (Engine.Instance.Storage != null) && (Engine.Instance.Storage.GetBool("log.level.debug"))) * { * string message = "curl " + this.GetPath() + " " + args; * message = Utils.RegExReplace(message, "[a-zA-Z0-9+/]{30,}=", "{base64-omissis}"); * Engine.Instance.Logs.Log(LogType.Verbose, message); * } */ Process p = new Process(); p.StartInfo.FileName = SystemShell.EscapePath(this.GetPath()); p.StartInfo.Arguments = args; p.StartInfo.WorkingDirectory = ""; p.StartInfo.CreateNoWindow = true; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.Start(); using (var memoryStream = new System.IO.MemoryStream()) { //p.StandardOutput.BaseStream.CopyTo(memstream); // .Net 4 only Utils.CopyStream(p.StandardOutput.BaseStream, memoryStream); output = memoryStream.ToArray(); } error = p.StandardError.ReadToEnd(); p.WaitForExit(); exitcode = p.ExitCode; } catch (Exception e) { error = e.Message; output = default(byte[]); } programScope.End(); if (error != "") { throw new Exception(error.Trim()); } return(output); }
public void RefreshUi(Engine.RefreshUiMode mode) { try { if ((mode == Engine.RefreshUiMode.MainMessage) || (mode == Engine.RefreshUiMode.Full)) { if (Engine.CurrentServer != null) { ImgTopFlag.Image = NSImage.ImageNamed("flag_" + Engine.CurrentServer.CountryCode.ToLowerInvariant() + ".png"); } else { ImgTopFlag.Image = NSImage.ImageNamed("notconnected.png"); } LblWaiting1.StringValue = Engine.WaitMessage; if (Engine.IsWaiting()) { ImgProgress.StartAnimation(this); ImgTopPanel.Image = NSImage.ImageNamed("topbar_osx_yellow.png"); MnuTrayStatus.Image = NSImage.ImageNamed("status_yellow_16.png"); LblTopStatus.StringValue = Engine.WaitMessage; TabOverview.SelectAt(1); CmdCancel.Hidden = (Engine.IsWaitingCancelAllowed() == false); CmdCancel.Enabled = (Engine.IsWaitingCancelPending() == false); MnuTrayConnect.Enabled = CmdCancel.Enabled; } else if (Engine.IsConnected()) { ImgProgress.StopAnimation(this); ImgTopPanel.Image = NSImage.ImageNamed("topbar_osx_green.png"); MnuTrayStatus.Image = NSImage.ImageNamed("status_green_16.png"); LblTopStatus.StringValue = MessagesFormatter.Format(MessagesUi.TopBarConnected, Engine.CurrentServer.DisplayName); TabOverview.SelectAt(2); LblConnectedServerName.StringValue = Engine.CurrentServer.DisplayName; LblConnectedLocation.StringValue = Engine.CurrentServer.GetLocationForList(); TxtConnectedExitIp.StringValue = Engine.ConnectionActive.ExitIPs.ToString(); ImgConnectedCountry.Image = NSImage.ImageNamed("flag_" + Engine.CurrentServer.CountryCode.ToLowerInvariant() + ".png"); } else { ImgProgress.StopAnimation(this); ImgTopPanel.Image = NSImage.ImageNamed("topbar_osx_red.png"); MnuTrayStatus.Image = NSImage.ImageNamed("status_red_16.png"); if (Engine.Instance.NetworkLockManager.IsActive()) { LblTopStatus.StringValue = MessagesUi.TopBarNotConnectedLocked; } else { LblTopStatus.StringValue = MessagesUi.TopBarNotConnectedExposed; } TabOverview.SelectAt(0); } EnabledUI(); } if ((mode == Engine.RefreshUiMode.Log) || (mode == Engine.RefreshUiMode.Full)) { lock (Engine.LogsPending) { while (Engine.LogsPending.Count > 0) { LogEntry l = Engine.LogsPending[0]; Engine.LogsPending.RemoveAt(0); Log(l); } } LblWaiting2.StringValue = Engine.Logs.GetLogDetailTitle(); } if ((mode == Engine.RefreshUiMode.Stats) || (mode == Engine.RefreshUiMode.Full)) { if (Engine.IsConnected()) { TxtConnectedSince.StringValue = Engine.Stats.GetValue("VpnStart"); TxtConnectedDownload.StringValue = UtilsString.FormatBytes(Engine.ConnectionActive.BytesLastDownloadStep, true, false); TxtConnectedUpload.StringValue = UtilsString.FormatBytes(Engine.ConnectionActive.BytesLastUploadStep, true, false); } } if ((mode == Engine.RefreshUiMode.Full)) { if (TableServersController != null) { TableServersController.RefreshUI(); } if (TableAreasController != null) { TableAreasController.RefreshUI(); } } } catch (Exception) { // TOFIX: macOS sometime throw an useless exception in closing phase } }
// 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); }