static private void watcher_Connected(object sender, RasConnectionEventArgs e) { // A connection has successfully connected. Log.ProcessDebug("Event " + VpnSelectorLibRes.A_connection_has_successfully_connected_ + e.Connection.EntryName); BaseProxyServer oldProxy = NetConnUtils.CurrentProxyServer; if (IsSynchMode == false) { NetConnUtils.CurrentProxyServer = BaseProxyServer.FindFromNames(NetConnUtils.GetActiveConnectionsNames()); } if (VpnConnectedEvent != null) { VpnConnectedEvent(null, new VpnConnectedEventArgs()); } if (IsSynchMode == false) { if ((oldProxy == null && NetConnUtils.CurrentProxyServer != null) || (oldProxy != null && oldProxy != NetConnUtils.CurrentProxyServer)) { //proxy changed NetConnUtils.ConfirmIpAddressAsync(); } } }
static public void CloseConnect(BaseProxyServer ps, bool async) { if (ps == null) { if (dialer != null) { RasConnection conn = RasConnection.GetActiveConnectionByName(dialer.EntryName, dialer.PhoneBookPath); if (conn != null) { conn.HangUp(); } } } else { RasConnection conn = RasConnection.GetActiveConnectionByName(ps.GetConnectionName(), RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User)); if (conn != null) { conn.HangUp(); } } if (!async) { NetConnUtils.CurrentProxyServer = null; } }
static private bool CreateAndConnectToProxyAsync(BaseProxyServer item) { bool statusChanged = false; if (!NetConnUtils.IsConnected(item)) { if (NetConnUtils.IsActiveConnectionPresent()) { NetConnUtils.CloseAllActiveConnections(false); } if (NetConnUtils.IsConnectionEntryExist(item) == false) { if (item.IsProtocolAvailable(ProxyProtocolTypeEnum.PPTP)) { NetConnUtils.CreateConnectionEntry(item, ProxyProtocolTypeEnum.PPTP); } else if (item.IsProtocolAvailable(ProxyProtocolTypeEnum.L2TP)) { NetConnUtils.CreateConnectionEntry(item, ProxyProtocolTypeEnum.L2TP); } else { throw new ArgumentException(VpnSelectorLibRes.Non_PPTP_no_L2TP_protocols_available_for_this_vpn_entry); } } NetConnUtils.OpenConnect(item); //DotRasUtils.CurrentProxyServer = item; statusChanged = true; } return(statusChanged); }
static public bool IsConnected(BaseProxyServer ps) { RasConnection conn = null; if (ps == null) { if (dialer != null) { conn = RasConnection.GetActiveConnectionByName(dialer.EntryName, dialer.PhoneBookPath); } } else { conn = RasConnection.GetActiveConnectionByName(ps.GetConnectionName(), RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User)); } if (conn != null) { RasConnectionStatus st = conn.GetConnectionStatus(); if (st.ConnectionState == RasConnectionState.Connected) { return(true); } else { return(false); } } else { return(false); } }
static private void watcher_Disconnected(object sender, RasConnectionEventArgs e) { // A connection has disconnected successfully. Log.ProcessDebug("Event " + VpnSelectorLibRes.A_connection_has_disconnected_successfully_ + e.Connection.EntryName); if (VpnDisconnectedEvent != null) { VpnDisconnectedEvent(null, new VpnDisconnectedEventArgs()); } if (IsSynchMode == false) { AppManager.Instance.ProcessNotification(VpnSelectorLibRes.VPN_disconnected); BaseProxyServer oldProxy = NetConnUtils.CurrentProxyServer; NetConnUtils.CurrentProxyServer = null; if (oldProxy != null) { //proxy changed NetConnUtils.ConfirmIpAddressAsync(); } //reconnect //https://stackoverflow.com/questions/23950702/reconnect-vpn-windows-service if (NetConnUtils.CurrentProxyServer != null && IsReconnect == true) { OpenConnectLocal(NetConnUtils.CurrentProxyServer, true); } } }
static public void MakeFavoriteContextMenu(List <ToolStripItem> items) { BaseProxyServer defaultItem = GetDefaulBaseProxyServer(); ToolStripMenuItem menuItem = new ToolStripMenuItem(); menuItem.Text = VpnSelectorLibRes.Favorit_connections; items.Add(menuItem); IList list = Dm.Instance.FindAll(BaseProxyServer.CurrentType); foreach (var o in list) { BaseProxyServer item = (BaseProxyServer)o; if (item.Favorite == true) { ToolStripMenuItem subMenuItem = new ToolStripMenuItem(); subMenuItem.Text = item.GetConnectionName(); if (item == defaultItem) { subMenuItem.Font = new Font(subMenuItem.Font, FontStyle.Bold); } menuItem.DropDownItems.Add(subMenuItem); List <ToolStripItem> subitems = new List <ToolStripItem>(); MakeContextMenuForBaseProxyServer(subitems, item); subMenuItem.DropDownItems.AddRange(subitems.ToArray()); } } }
private static void Dialer_DialCompleted(object sender, DialCompletedEventArgs e) { //Note: events are not generated when manipulating with a connection from outside if (e.Cancelled) { Log.ProcessDebug("Event Dialer Cancelled"); } else if (e.TimedOut) { Log.ProcessDebug("Event Dialer Timeout"); } else if (e.Connected) { Log.ProcessDebug("Event Dialer Connection successful"); } else if (e.Error != null) { Log.LogError("Event Dialer Error " + e.Error.ToString(), e.Error); try { if (dialer.EntryName != null) { BaseProxyServer currentProxyServer = BaseProxyServer.FindFromNames(new List <string>() { dialer.EntryName }); if (currentProxyServer != null) { currentProxyServer.ErrorCount = currentProxyServer.ErrorCount + 1; currentProxyServer.LastErrorDate = DateTimeOffset.Now; Dm.Instance.SaveObject(currentProxyServer); } } } catch (Exception ex) { Log.ProcessDebug("Event Error find BaseProxyServer " + ex); } if (IsSynchMode == false) { if (VpnDialerErrorEvent != null) { VpnDialerErrorEvent(null, new VpnDialerErrorEventArgs() { Exception = e.Error }); } } } if (!e.Connected) { Log.ProcessDebug("Dialer not connected"); } }
static public BaseProxyServer GetDefaulBaseProxyServer() { if (BaseProxyServerDefault == null) { JSetting setting = FrwConfig.Instance.GetProperty(DEFAULT_JPROXY_SERVER); if (setting != null) { BaseProxyServerDefault = setting.Value as BaseProxyServer; } } return(BaseProxyServerDefault); }
static public bool DisconnectWithConfirmation(BaseProxyServer item, string homeIP, bool createdNew, JobLog jobLog) { if (NetConnUtils.IsActiveConnectionPresent()) { NetConnUtils.CloseAllActiveConnections(false); Thread.Sleep(2 * 1000); } if (createdNew) { NetConnUtils.RemoveConnectionEntry(item); } return(true); }
static public bool IsConnectionEntryExist(BaseProxyServer ps) { string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); if (path != null && File.Exists(path)) { string name = ps.GetConnectionName(); return(RasEntry.Exists(name, path)); } else { return(false); } }
static public void MakeDefaultContextMenu(List <ToolStripItem> items) { BaseProxyServer item = GetDefaulBaseProxyServer(); if (item != null) { ToolStripMenuItem menuItem = new ToolStripMenuItem(); menuItem.Text = VpnSelectorLibRes.Deafault_connection; items.Add(menuItem); List <ToolStripItem> subitems = new List <ToolStripItem>(); MakeContextMenuForBaseProxyServer(subitems, item); menuItem.DropDownItems.AddRange(subitems.ToArray()); } }
static private void OpenConnectLocal(BaseProxyServer ps, bool async) { CreateDialerAndBeginWatch();//if not created yet //http://www.dotnetobject.com/Thread-Connecting-VPN-using-C dialer.EntryName = ps.GetConnectionName(); dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); try { try { RasConnection conn = RasConnection.GetActiveConnectionByName(ps.GetConnectionName(), dialer.PhoneBookPath); if (conn != null) { conn.HangUp(); } } catch (Exception) { //no connection present } if (!string.IsNullOrEmpty(ps.GetProxyProvider().VPNLogin)) { System.Net.NetworkCredential cred = new System.Net.NetworkCredential(ps.GetProxyProvider().VPNLogin, ps.GetProxyProvider().VPNPassword); dialer.Credentials = cred; } //dialer.Dial();//alt DialAsync() if (async) { handle = dialer.DialAsync(); } else { handle = dialer.Dial(); NetConnUtils.CurrentProxyServer = ps; } } catch (Exception ex) { throw ex; } }
static public bool ConnectWithConfirmation(BaseProxyServer item, string homeIP, JobLog jobLog) { IsSynchMode = true; string oldExternalIP = NetConnUtils.MyExternalIP; JIPAddressInfo oldExtIPAddressInfo = NetConnUtils.MyExtIPAddressInfo; bool createdNew = false; bool res = false; try { res = ConnectWithConfirmationLocal(item, homeIP, out createdNew, jobLog); } finally{ DisconnectWithConfirmation(item, homeIP, createdNew, jobLog); NetConnUtils.MyExternalIP = oldExternalIP; NetConnUtils.MyExtIPAddressInfo = oldExtIPAddressInfo; IsSynchMode = false; } return(res); }
static public void CreateConnectionEntry(BaseProxyServer ps, ProxyProtocolTypeEnum protocolType) { if (!ps.IsProtocolAvailable(protocolType)) { throw new ArgumentException("Protocol " + protocolType.ToString() + " not avilable"); } //http://stackoverflow.com/questions/36213393/get-connection-status-vpn-using-dotras // File.WriteAllText("your rasphone.pbk path","")//Add RasPhoneBook rasPhoneBook1 = new RasPhoneBook(); string rasPhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);//alt RasPhoneBookType.AllUsers rasPhoneBook1.Open(rasPhoneBookPath); string deviceTypeStr = "(" + protocolType.ToString() + ")"; RasVpnStrategy strategy = (protocolType == ProxyProtocolTypeEnum.L2TP) ? RasVpnStrategy.L2tpOnly : RasVpnStrategy.PptpOnly; //alt //RasVpnStrategy strategy = RasVpnStrategy.Default; RasEntry entry = RasEntry.CreateVpnEntry(ps.GetConnectionName(), ps.Url, strategy, RasDevice.GetDeviceByName(deviceTypeStr, RasDeviceType.Vpn, false)); entry.EncryptionType = ps.EncryptionType.ToEnum <RasEncryptionType>(); if (protocolType == ProxyProtocolTypeEnum.L2TP && !string.IsNullOrEmpty(ps.GetProxyProvider().UserPresharedKey)) { entry.Options.UsePreSharedKey = true; } rasPhoneBook1.Entries.Add(entry); if (protocolType == ProxyProtocolTypeEnum.L2TP && !string.IsNullOrEmpty(ps.GetProxyProvider().UserPresharedKey)) { entry.UpdateCredentials(RasPreSharedKey.Client, ps.GetProxyProvider().UserPresharedKey); } if (!string.IsNullOrEmpty(ps.GetProxyProvider().VPNLogin)) { //entry.UpdateCredentials(new System.Net.NetworkCredential(ps.JProxyProvider.VPNLogin, ps.JProxyProvider.VPNPassword), false); } }
static public void RemoveConnectionEntry(BaseProxyServer ps) { string name = ps.GetConnectionName(); RasPhoneBook rasPhoneBook1 = new RasPhoneBook(); string rasPhoneBookPath = null; rasPhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User); rasPhoneBook1.Open(rasPhoneBookPath); RasEntry entryFound = null; foreach (RasEntry entry1 in rasPhoneBook1.Entries) { if (entry1.Name.Equals(name)) { entryFound = entry1; break; } } if (entryFound != null) { entryFound.Remove(); } }
static public bool ConnectOrDisconnectDefautBaseProxyServerAsync() { bool statusChanged = false; if (NetConnUtils.IsActiveConnectionPresent()) { NetConnUtils.CloseAllActiveConnections(true); statusChanged = true; } else { BaseProxyServer item = GetDefaulBaseProxyServer(); if (item != null) { statusChanged = CreateAndConnectToProxyAsync(item); } else { MessageBox.Show(VpnSelectorLibRes.Double_click_on_this_icon_creates_VPN_connection_to_default_VPN_server_which_not_set__No_connection_created_, VpnSelectorLibRes.Warning_, MessageBoxButtons.OK, MessageBoxIcon.Information); } } return(statusChanged); }
private static void ScheduleJobChekVpnServer(BaseProxyServer item, string homeIP) { JRunningJob job = null; job = JobManager.Instance.CreateJob("ChekVpn", VpnSelectorLibRes.Test_for_VPN_server, item.Url, JobConcurrentTypeEnum.Wait); job.DoJob += (sd, ew) => { job.JobLog.Info("Plan VPN server test for " + item.Url); bool res = NetConnUtils.ConnectWithConfirmation(item, homeIP, job.JobLog); Thread.Sleep(5 * 1000); job.JobLog.Info("End VPN server test for " + item.Url); JobManager.Instance.ReportProgresJob(job, 100); if (res) { ew.StageResult = RunningJobResultEnum.ok; } else { ew.StageResult = RunningJobResultEnum.error; } }; item.JRunningJob = job; Dm.Instance.SaveObject(item); }
override protected void MakeContextMenu(List <ToolStripItem> menuItemList, object selectedListItem, object selectedObject, string aspectName) { base.MakeContextMenu(menuItemList, selectedListItem, selectedObject, aspectName); menuItemList.Add(new ToolStripSeparator()); BaseProxyServer item = (BaseProxyServer)selectedObject; List <ToolStripItem> subitems = new List <ToolStripItem>(); NetConnUtils.MakeContextMenuForBaseProxyServer(subitems, item); NetConnUtils.MakeContextMenuForAllBaseProxyServers(subitems); menuItemList.AddRange(subitems.ToArray()); ToolStripMenuItem groupItem = null; ToolStripMenuItem menuItem = null; menuItem = new ToolStripMenuItem(); menuItem.Text = VpnSelectorLibRes.Import_VPN_servers_from_vpngate_net; menuItem.Click += (s, em) => { try { VpngateImporter.DowloadAndParse(); } catch (Exception ex) { Log.ShowError(ex); } }; menuItemList.Add(menuItem); groupItem = new ToolStripMenuItem(); groupItem.Text = VpnSelectorLibRes.Run_test; menuItemList.Add(groupItem); if (item != null) { menuItem = new ToolStripMenuItem(); menuItem.Text = ((SelectedObjects.Count > 1) ? VpnSelectorLibRes.Run_test_for_selected_VPN_servers : VpnSelectorLibRes.Run_test_for_this_VPN_server); menuItem.Click += (s, em) => { try { ScheduleJobChekVpnAll(SelectedObjects, false, false); } catch (Exception ex) { Log.ShowError(ex); } }; groupItem.DropDownItems.Add(menuItem); if (item.JRunningJob != null && item.JRunningJob.JJobType != null)//JRunningJob.JJobType = null for manualy deleted job { List <ToolStripItem> subitems2 = new List <ToolStripItem>(); JobManager.MakeTitleContextMenuForRunningJob(item.JRunningJob, subitems2, this.ContentContainer); groupItem.DropDownItems.AddRange(subitems2.ToArray <ToolStripItem>()); } if (currQueueJobType != null) { List <ToolStripItem> subitems22 = new List <ToolStripItem>(); JobManager.MakeTitleContextMenuForRunningJobTypeQueue(currQueueJobType, subitems22, this.ContentContainer); groupItem.DropDownItems.AddRange(subitems22.ToArray <ToolStripItem>()); } } menuItem = new ToolStripMenuItem(); menuItem.Text = VpnSelectorLibRes.Run_test_for_favorite_VPN_servers; menuItem.Click += (s, em) => { try { ScheduleJobChekVpnAll(null, false, true); } catch (Exception ex) { Log.ShowError(ex); } }; groupItem.DropDownItems.Add(menuItem); menuItem = new ToolStripMenuItem(); menuItem.Text = VpnSelectorLibRes.Run_test_for_all_VPN_servers; menuItem.Click += (s, em) => { try { ScheduleJobChekVpnAll(null, true, false); } catch (Exception ex) { Log.ShowError(ex); } }; groupItem.DropDownItems.Add(menuItem); }
static public bool ConnectWithConfirmationLocal(BaseProxyServer item, string homeIP, out bool createdNew, JobLog jobLog) { bool result = false; jobLog.Debug("Start VpnServerConnectWithFullTestLocal for item " + item.JProxyServerId); createdNew = false; int closeAttemptCount = 0; while (NetConnUtils.IsActiveConnectionPresent()) { if (closeAttemptCount > 10) { throw new Exception("Unable to close previous active connection"); } jobLog.Debug("Found previous active connection. Going to close it"); NetConnUtils.CloseAllActiveConnections(false); Thread.Sleep(2 * 1000);//!!! closeAttemptCount++; } ///////test if (homeIP != null) { string externalIP = NetConnUtils.GetMyExternalIP(); if (externalIP == null) { throw new Exception("Ip of default connection is null"); } jobLog.Info("Default ExternalIP: " + externalIP); if (!homeIP.Equals(externalIP)) { throw new Exception("Ip address of default connection not equals home ip address."); } } ////////// if (NetConnUtils.IsConnectionEntryExist(item) == false) { if (item.IsProtocolAvailable(ProxyProtocolTypeEnum.PPTP)) { NetConnUtils.CreateConnectionEntry(item, ProxyProtocolTypeEnum.PPTP); createdNew = true; } else if (item.IsProtocolAvailable(ProxyProtocolTypeEnum.L2TP)) { NetConnUtils.CreateConnectionEntry(item, ProxyProtocolTypeEnum.L2TP); createdNew = true; } else { throw new ArgumentException(VpnSelectorLibRes.Non_PPTP_no_L2TP_protocols_available_for_this_vpn_entry); } } try { NetConnUtils.OpenConnectLocal(item, false); //sync Thread.Sleep(2 * 1000); //!!! //for (int i = 0; i < 60; i++)//~ 1 min //{ if (NetConnUtils.IsConnected(item)) { ConfirmIPAddress(item, homeIP, jobLog); result = true; item.SuccessCount = item.SuccessCount + 1; item.LastSuccessDate = DateTimeOffset.Now; Dm.Instance.SaveObject(item); } else { jobLog.Info("Not connected for item " + item.JProxyServerId); } //Thread.Sleep(1 * 1000); //} //todo error event } finally { //change label if (OnNetworkChekComplatedEvent != null) { NetworkChekComplatedEventArgs e = new NetworkChekComplatedEventArgs(); OnNetworkChekComplatedEvent(null, e); } } return(result); }
static public void ConfirmIPAddress(BaseProxyServer item, string homeIP, JobLog jobLog) { string externalIP = NetConnUtils.GetMyExternalIP(); if (externalIP == null) { throw new Exception("Ip of vpn connection is null"); } jobLog.Info("ExternalIP: " + externalIP); if (homeIP != null) { if (homeIP.Equals(externalIP)) { throw new Exception("Ip address of vpn connection not changed. It equals home ip address."); } } JIPAddressInfo extIPAddressInfo = NetConnUtils.GetIPAddressInfo(externalIP); if (extIPAddressInfo == null) { throw new Exception("IPAddressInfo of vpn connection is null"); } jobLog.Info("New IP address Info: " + Log.PropertyList(extIPAddressInfo)); if (item != null) { if (item.JCountry != null) { if (!string.IsNullOrEmpty(extIPAddressInfo.CountryCode)) { if (extIPAddressInfo.CountryCode.ToLower().Equals(item.JCountry.JCountryId) == false) { //throw new Exception jobLog.Warn("Country code of vpn connection ip address (" + extIPAddressInfo.CountryCode.ToLower() + ") not equals to contry code of VPN server (" + item.JCountry.JCountryId + ")"); JCountry newContry = Dm.Instance.Find <JCountry>(extIPAddressInfo.CountryCode.ToLower()); if (newContry != null) { if (item.JCountryDeclared == null) { item.JCountryDeclared = item.JCountry; } item.JCountry = newContry; Dm.Instance.SaveObject(item); } else { throw new Exception("Country code of vpn connection ip address (" + extIPAddressInfo.CountryCode.ToLower() + ") not a valid country code"); } } } else { throw new Exception("Country code of vpn connection is empty"); } if (!string.IsNullOrEmpty(extIPAddressInfo.City)) { if (item.Town != null) { if (extIPAddressInfo.City.ToLower().Equals(item.Town.ToLower()) == false) { jobLog.Warn("City vpn connection ip address (" + extIPAddressInfo.City + ") not equals to town of VPN server (" + item.Town + "). New City value was set"); if (item.TownDeclared == null) { item.TownDeclared = item.Town; } item.Town = extIPAddressInfo.City; Dm.Instance.SaveObject(item); } } else { item.Town = extIPAddressInfo.City; Dm.Instance.SaveObject(item); } } } else { //todo } jobLog.Info("Test OK for item " + item.JProxyServerId); } //ok //todo NetConnUtils.MyExternalIP = externalIP; NetConnUtils.MyExtIPAddressInfo = extIPAddressInfo; }
static public void OpenConnect(BaseProxyServer ps) { OpenConnectLocal(ps, true); }
private void ScheduleJobChekVpnAll(IList selectedItems, bool all, bool favoritOnly) { StartRefreshing(); // create background tasks, which nevertheless are executed sequentially // it would be possible to create one background thread and perform all the tasks sequentially, // but at the same time the opportunity to destroy the hanging task is lost and to let the others continue // todo worth thinking about limiting the number of waiting threads //prepare task list IList list = null; if (all) { list = Dm.Instance.FindAll(BaseProxyServer.CurrentType); } else if (favoritOnly) { IList list0 = Dm.Instance.FindAll(BaseProxyServer.CurrentType); list = new List <BaseProxyServer>(); foreach (var n in list0) { BaseProxyServer m = (BaseProxyServer)n; if (m.Favorite) { list.Add(m); } } } else { list = selectedItems; } if (list == null || list.Count == 0) { throw new Exception("No items to test found"); } //check for allready running tasks and stop it bool foundWorking = false; foreach (var n in list) { BaseProxyServer m = (BaseProxyServer)n; if (m.JRunningJob != null && m.JRunningJob.JJobType != null && m.JRunningJob.IsWorking()) { foundWorking = true; break; } } if (foundWorking) { DialogResult res = MessageBox.Show(VpnSelectorLibRes.Running_job_found__They_will_be_aborted_or_press__Cancel__to_exit, FrwConstants.WARNING, MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (res == DialogResult.Cancel) { return; } } foreach (var n in list) { BaseProxyServer m = (BaseProxyServer)n; if (favoritOnly == false || m.Favorite) { if (m.JRunningJob != null) { if (m.JRunningJob.JJobType != null) { if (m.JRunningJob.IsWorking()) { JobManager.Instance.AbortJob(m.JRunningJob); } else { //m.JRunningJob.Stage = RunningJobStageEnum.initial.ToString(); //Dm.Instance.SaveObject(m.JRunningJob); } } m.JRunningJob = null; Dm.Instance.SaveObject(m); } } } string homeIP = null; //close active vpns if (NetConnUtils.IsActiveConnectionPresent()) { NetConnUtils.CloseAllActiveConnections(false); homeIP = NetConnUtils.GetMyExternalIP(); } else { homeIP = NetConnUtils.MyExternalIP; } //Schedule tasks foreach (var n in list) { BaseProxyServer m = (BaseProxyServer)n; ScheduleJobChekVpnServer(m, homeIP); JobManager.ScheduleJobToQueue(m.JRunningJob); currQueueJobType = m.JRunningJob.JJobType; } if (currQueueJobType != null) { currQueueJobType.RemoveAllPostJobBatchEventHandlers(); currQueueJobType.PostJobBatch += currQueueJobType.StandartPostLJobBatchEventHandler; JobManager.StartProcessingJobBatch(currQueueJobType); } }
static public void MakeContextMenuForBaseProxyServer(List <ToolStripItem> items, BaseProxyServer item) { ToolStripMenuItem menuItem = new ToolStripMenuItem(); menuItem.Text = VpnSelectorLibRes.Create_VPN_entry_ + " PPTP " + item.GetConnectionName(); if (NetConnUtils.IsConnectionEntryExist(item) || item.IsProtocolAvailable(ProxyProtocolTypeEnum.PPTP) == false) { menuItem.Enabled = false; } menuItem.Click += (s, em) => { try { NetConnUtils.CreateConnectionEntry(item, ProxyProtocolTypeEnum.PPTP); } catch (Exception ex) { Log.ShowError(ex); } }; items.Add(menuItem); menuItem = new ToolStripMenuItem(); menuItem.Text = VpnSelectorLibRes.Create_VPN_entry_ + " L2TP " + item.GetConnectionName(); if (NetConnUtils.IsConnectionEntryExist(item) || item.IsProtocolAvailable(ProxyProtocolTypeEnum.L2TP) == false) { menuItem.Enabled = false; } menuItem.Click += (s, em) => { try { NetConnUtils.CreateConnectionEntry(item, ProxyProtocolTypeEnum.L2TP); } catch (Exception ex) { Log.ShowError(ex); } }; items.Add(menuItem); menuItem = new ToolStripMenuItem(); menuItem.Text = VpnSelectorLibRes.Connect_to_VPN_server; if (NetConnUtils.IsConnected(item)) { menuItem.Enabled = false; } if (NetConnUtils.IsConnectionEntryExist(item)) { menuItem.Text = menuItem.Text + VpnSelectorLibRes.__created_; } menuItem.Text = menuItem.Text + " " + item.GetConnectionName(); menuItem.Click += (s, em) => { try { DialogResult res = DialogResult.Cancel; if (NetConnUtils.IsActiveConnectionPresent()) { res = MessageBox.Show(VpnSelectorLibRes.Active_VPN_connection_found____ + NetConnUtils.ShowConnectionEntries() + VpnSelectorLibRes.__Press_OK_to_close_it_and_connect_to_selected_VPN_server_, VpnSelectorLibRes.Warning_, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (res == DialogResult.OK) { NetConnUtils.CloseAllActiveConnections(false); } } else { res = DialogResult.OK; } if (res == DialogResult.OK) { bool statusChanged = CreateAndConnectToProxyAsync(item); } } catch (Exception ex) { Log.ShowError(ex); } }; items.Add(menuItem); menuItem = new ToolStripMenuItem(); menuItem.Text = VpnSelectorLibRes.Disonnect_from_VPN_server_ + item.GetConnectionName(); if (!NetConnUtils.IsConnected(item)) { menuItem.Enabled = false; } menuItem.Click += (s, em) => { try { NetConnUtils.CloseConnect(item, true); } catch (Exception ex) { Log.ShowError(ex); } }; items.Add(menuItem); menuItem = new ToolStripMenuItem(); menuItem.Text = VpnSelectorLibRes.Set_as_default_VPN_connection_ + item.GetConnectionName(); if (NetConnUtils.GetDefaulBaseProxyServer() == item) { menuItem.Enabled = false; } menuItem.Click += (s, em) => { try { BaseProxyServerDefault = item; JSetting setting = FrwConfig.Instance.GetProperty(DEFAULT_JPROXY_SERVER); setting.Value = item; } catch (Exception ex) { Log.ShowError(ex); } }; items.Add(menuItem); }
protected void CreateVPNSupport() { NetConnUtils.InitSettings(); // // vpnButton // this.vpnButton = new System.Windows.Forms.ToolStripSplitButton(); this.vpnButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.vpnButton.Enabled = true; this.vpnButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.vpnButton.Name = "vpnButton"; this.vpnButton.Size = new System.Drawing.Size(19, 23); this.vpnButton.Text = "VPN"; this.vpnButton.ToolTipText = "VPN"; vpnButton.Image = VpnSelectorLibRes.network_off; //vpnButton.DoubleClick += VpnButton_DoubleClick; - do not working // // ipAddressLabel // this.ipAddressLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.ipAddressLabel.AutoToolTip = true; this.ipAddressLabel.Enabled = false; this.ipAddressLabel.Name = "ipAddressLabel"; this.ipAddressLabel.Size = new System.Drawing.Size(66, 20); this.ipAddressLabel.Text = "127.0.0.1"; this.ipAddressLabel.ToolTipText = "127.0.0.1"; this.statusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.eventWarrningButton, this.vpnButton, this.ipAddressLabel }); if (useMainTrayIconForVPN && BaseApplicationContext.NotifyIcon != null) { vpnNotifyIcon = BaseApplicationContext.NotifyIcon; } else { vpnNotifyIcon = new NotifyIcon(components) { ContextMenuStrip = new ContextMenuStrip(), Icon = vpnOffIcon, Text = "VPN", Visible = true }; } vpnButton.MouseDown += VpnButton_MouseDown; vpnNotifyIcon.ContextMenuStrip.Opening += VpnNotifyIconContextMenuStrip_Opening; vpnNotifyIcon.DoubleClick += VpnNotifyIcon_DoubleClick; NetConnUtils.OnNetworkChekComplatedEvent += JustNetworkUtils_OnNetworkChekComplatedEvent; NetConnUtils.VpnDisconnectedEvent += VpnSelector_OnVpnDisconnectedEvent; NetConnUtils.VpnConnectedEvent += VpnSelector_OnVpnConnectedEvent; NetConnUtils.VpnDialerErrorEvent += VpnSelector_OnVpnDialerErrorEvent; NetConnUtils.CreateDialerAndBeginWatch(); bool _isActiveConnectionPresent = NetConnUtils.IsActiveConnectionPresent(); if (_isActiveConnectionPresent) { NetConnUtils.CurrentProxyServer = BaseProxyServer.FindFromNames(NetConnUtils.GetActiveConnectionsNames()); ProcessVpnConnectedEvent(); //DotRasUtils.CurrentProxyServer = DotRasUtils.CurrentProxyServer; } else { NetConnUtils.ConfirmIpAddressAsync(); } }
//todo log //todo check vpn provider id //todo final message private static void ParseDirect(string s) { List <BaseProxyServer> tmpList = new List <BaseProxyServer>(); IList cl = Dm.Instance.FindAll(typeof(JCountry)); TextReader reader = new StringReader(s); HtmlDocument doc = new HtmlDocument(); doc.Load(reader); if (doc.DocumentNode != null) { HtmlNode span = doc.DocumentNode.SelectSingleNode("//span[@id='Label_Table']"); HtmlNode table = span.SelectSingleNode("table[@id='vg_hosts_table_id']"); HtmlNodeCollection trs = table.SelectNodes("tr"); if (trs != null) { //BaseProxyServer p = null; bool firstTr = true; foreach (HtmlNode tr in trs) { if (firstTr)//header { firstTr = false; continue; } if (tr.SelectNodes("td[@class='vg_table_header']") != null && tr.SelectNodes("td[@class='vg_table_header']").Count > 0) { continue; } HtmlNodeCollection tds = tr.SelectNodes("td"); if (tds != null) { bool valid = false; int tdnum = 0; foreach (HtmlNode td in tds) { if (tdnum == 5) { string l2tp = ClearTag(td.InnerText); if (string.IsNullOrEmpty(l2tp) == false && l2tp.Contains("L2TP")) { valid = true; break; } } tdnum++; } if (valid) { BaseProxyServer p = (BaseProxyServer)Activator.CreateInstance(BaseProxyServer.CurrentType); tdnum = 0; foreach (HtmlNode td in tds) { if (tdnum == 0)//country <img src='../images/flags/JP.png' width='32' height='32' /><br>Japan</td> { string p_JCountry = ClearTag(td.InnerText); if (p_JCountry != null) { foreach (JCountry c in cl) { if (c.Name.Equals(p_JCountry) || (c.Official_name_en != null && c.Official_name_en.Equals(p_JCountry)) || (c.Official_name_fr != null && c.Official_name_fr.Equals(p_JCountry)) ) { p.JCountry = c; break; } } } if (p.JCountry == null) { HtmlNode image = td.SelectSingleNode("img"); if (image != null) { string src = image.GetAttributeValue("src", null); if (src != null) { int indexDot = src.IndexOf(".png"); int indexSplash = src.LastIndexOf("/"); if (indexDot > -1 && indexSplash > -1 && indexDot > indexSplash) { string countryCode = src.Substring(indexSplash + 1, (indexDot - indexSplash) - 1); countryCode = countryCode.ToLower(); foreach (JCountry c in cl) { if (c.JCountryId.Equals(countryCode)) { p.JCountry = c; break; } } } } } } if (p.JCountry == null) { Console.WriteLine("=================================================="); Console.WriteLine("Country not found: " + td.InnerHtml); Console.WriteLine("=================================================="); } } if (tdnum == 1)//url <b><span style='font-size: 9pt;'>word-wind-vpn.opengw.net</span></b><br><span style='font-size: 10pt;'>218.229.183.122</span><br><span style='font-size: 7pt;'>(nttkyo1188122.tkyo.nt.ngn.ppp.infoweb.ne.jp)</span> { HtmlNode b = td.SelectSingleNode("b/span"); string urlsStr = ClearTag(b.InnerText); p.Url = urlsStr; } tdnum++; } tmpList.Add(p); } //valid } //tds } } } List <BaseProxyServer> newList = new List <BaseProxyServer>(); List <BaseProxyServer> sameList = new List <BaseProxyServer>(); List <BaseProxyServer> restoredList = new List <BaseProxyServer>(); List <BaseProxyServer> archivedList = new List <BaseProxyServer>(); BaseProxyProvider pp = (BaseProxyProvider)Dm.Instance.Find(BaseProxyProvider.CurrentType, "5"); foreach (var p0 in tmpList) { //Console.WriteLine(ModelHelper.ModelPropertyList(p0, "\n", null, null)); //Console.WriteLine("=================================================="); BaseProxyServer foundSame = null; IList oldList = Dm.Instance.FindAll(BaseProxyServer.CurrentType); foreach (var o in oldList) { BaseProxyServer oldP = (BaseProxyServer)o; if (oldP.GetProxyProvider() != null && oldP.GetProxyProvider().Equals(pp) && oldP.Url.Equals(p0.Url)) { foundSame = oldP; if (oldP.IsArchive == true) { oldP.IsArchive = false; restoredList.Add(oldP); Dm.Instance.SaveObject(oldP); } break; } } if (foundSame == null) { BaseProxyServer p = (BaseProxyServer)Dm.Instance.EmptyObject(BaseProxyServer.CurrentType, null); p.SetProxyProvider(pp); p.Url = p0.Url; p.JCountry = p0.JCountry; p.AvailableProtocols = new List <string>(); p.AvailableProtocols.Add(ProxyProtocolTypeEnum.L2TP.ToString()); p.EncryptionType = ProxyEncryptionTypeEnum.Require.ToString(); Dm.Instance.SaveObject(p); newList.Add(p); } else { sameList.Add(foundSame); } } //reverse search IList oldList2 = Dm.Instance.FindAll(BaseProxyServer.CurrentType); foreach (var o in oldList2) { BaseProxyServer oldP = (BaseProxyServer)o; if (oldP.GetProxyProvider() != null && oldP.GetProxyProvider().Equals(pp)) { bool found = false; foreach (var p0 in tmpList) { if (oldP.Url.Equals(p0.Url)) { found = true; } } if (!found && oldP.IsArchive == false) { oldP.IsArchive = true; archivedList.Add(oldP); } } } Log.ProcessDebug("================ same ================ " + sameList.Count); foreach (var v in sameList) { Log.ProcessDebug(v.Url); } Log.ProcessDebug("================ new ================ " + newList.Count); foreach (var v in newList) { Log.ProcessDebug(v.Url); } Log.ProcessDebug("================ restored ================ " + restoredList.Count); foreach (var v in restoredList) { Log.ProcessDebug(v.Url); } Log.ProcessDebug("================ archive ================ " + archivedList.Count); foreach (var v in archivedList) { Log.ProcessDebug(v.Url); } }