private void cmdCheckPorts_Click(object sender, EventArgs e) { DialogResult understood = MessageBox.Show("Before you proceed, you must keep in mind that in order to determine if" + " a port is truly open, you need to have a service listening to that port.\n\n" + "If no service is running behind the port, then the checker will report it as " + "closed no matter if it was forwarded correctly or not.\n\nClick \"Yes\" if you understand this to proceed.", "Information!", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (understood == DialogResult.No) { return; } foreach (ListViewItem item in listPorts.Items) { PortMapping mapping = (PortMapping)item.Tag; if (_portChecker.CheckPort(mapping.Protocol, _publicIp, mapping.Port)) { item.Text = mapping.ToString() + " - Open"; } else { item.Text = mapping.ToString() + " - Closed"; } } }
protected override async IAsyncEnumerable <ContainerArgs> AddContainersAsync() { var passivePorts = new PortRange(21100, 21110); var ftpVariables = new Dictionary <string, string> { ["FTP_USER"] = "******", ["FTP_PASS"] = "******", ["PASV_MIN_PORT"] = passivePorts.Start.ToString(), ["PASV_MAX_PORT"] = passivePorts.End.ToString() }; var ftpPorts = new List <PortMapping> { PortMapping.MapSinglePort(30020, 20), PortMapping.MapSinglePort(30021, 21), new PortMapping(passivePorts, passivePorts) }; var ftp = new ContainerArgs( "fauria/vsftpd", "ftp", ftpPorts, ftpVariables ); yield return(ftp); }
private void cmdAdd_Click(object sender, System.EventArgs e) { PortMapping mapping = FrmAddPort.GetPortMapping(this); if (mapping == null) { return; } foreach (ListViewItem existingItem in listPorts.Items) { PortMapping addedMapping = (PortMapping)existingItem.Tag; if (!addedMapping.Equals(mapping)) { continue; } MessageBox.Show($"Port number {mapping.Port} is already added to the list.", "Port exists!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } ListViewItem item = new ListViewItem(mapping.ToString()) { Tag = mapping }; listPorts.Items.Add(item); }
private void AddMapping() { Random r = new Random(); int desiredPort = r.Next(10000, 60000); myMapping = new PortMapping(9981, (ushort)desiredPort, PortMappingTransportProtocol.TCP); TCMPortMapper.PortMapper.SharedInstance.AddPortMapping(myMapping); }
public FargateStack(Construct scope, string id, FargateStackProps props = null) : base(scope, id, props) { var cluster = new Cluster(this, "WhatDayOfWeekCluster", new ClusterProps { Vpc = props.Vpc }); var logging = new AwsLogDriver(new AwsLogDriverProps() { StreamPrefix = "WhatDayOfWeek", LogRetention = Amazon.CDK.AWS.Logs.RetentionDays.ONE_DAY }); //container /* * var repo = Repository.FromRepositoryName(this, "myrepo","MyRepositoryName"); * * var containerOptions = new ContainerDefinitionOptions * { * Image = ContainerImage.FromEcrRepository(repo) * }; */ // to build the container image from the app in the local folder, replace lines 29-35 with //var rootDirectory = Directory.GetCurrentDirectory(); //var path = Path.GetFullPath(Path.Combine(rootDirectory, @"App/WhatDayOfWeek")); var containerOptions = new ContainerDefinitionOptions { Image = ContainerImage.FromAsset(@"App/WhatDayOfWeek"), Logging = logging }; var portMapping = new PortMapping() { ContainerPort = 80, HostPort = 80 }; var taskDef = new FargateTaskDefinition(this, "WhatDayOfWeekTaskDefinition"); taskDef.AddContainer("WhatDayOfWeekContainer", containerOptions).AddPortMappings(portMapping); var serviceProps = new ApplicationLoadBalancedFargateServiceProps() { ServiceName = "WhatDayOfWeekService", MemoryLimitMiB = 512, Cpu = 256, TaskDefinition = taskDef, Cluster = cluster }; ApplicationLoadBalancedFargateService service = new ApplicationLoadBalancedFargateService(this, "WhatDayOfWeekService", serviceProps); }
/// <summary> /// 向连接列表中的所有端点广播本客户端“退出分布网络”消息。 /// </summary> /// <param name="workerThread">返回发送用的 <see cref="System.Threading.Thread"/>。</param> /// <returns>一个 <see cref="System.Threading.WaitHandle"/>,通过此对象可以对发送操作进行等待。</returns> public WaitHandle ExitNetwork(out Thread workerThread) { Logger.Log("KClient::ExitNetwork()"); AutoResetEvent ev = new AutoResetEvent(false); Thread thread = new Thread(delegate() { try { if (PortMapping.AddedPortMapping) { PortMapping.DeletePortMapping(); } foreach (var item in ConnectionList) { if (item.State != ConnectionState.RemovePending) { TcpClient tcpClient = new TcpClient(); var remoteEndPoint = item.ClientLocation.GetEndPoint(); Logger.Log("尝试连接端点: " + remoteEndPoint.ToString()); var iar = tcpClient.BeginConnect(remoteEndPoint.Address, remoteEndPoint.Port, null, null); if (!iar.IsCompleted) { iar.AsyncWaitHandle.WaitOne(SendTimeout); } if (iar.IsCompleted) { // 未超时 tcpClient.EndConnect(iar); Logger.Log("连接成功。发送自己退出的消息。"); var bs = tcpClient.GetStream(); { bs.WriteMessage(MessageFactory.ClientExitNetwork(LocalKEndPoint)); } tcpClient.Close(); } else { Logger.Log("连接失败。无任何其他操作。"); } } } ev.Set(); ev.Dispose(); } catch (Exception ex) { Logger.Log(ex.Message + Environment.NewLine + ex.StackTrace); } }); thread.IsBackground = true; thread.Start(); workerThread = thread; return(ev); }
private void PortMapper_DidChangeMappingStatus(PortMapper sender, PortMapping pm) { DebugLog.WriteLine("Form1: PortMapper_DidChangeMappingStatus"); foreach (ListViewItem lvi in mappings) { PortMapping lvi_pm = (PortMapping)lvi.Tag; if (lvi_pm == pm) { mappingsListView.RedrawItems(lvi.Index, lvi.Index, false); } } }
public void PortItemSelected(PortMappingItem item) { _currentPortMapping = item.PortMapping; _currentDevice = _deviceProxy.GetDevice(_currentPortMapping.DeviceId, _currentPortMapping.SubDeviceId); CurrentDeviceName = _currentDevice != null ? _currentDevice.DeviceName : null; CurrentPlayerHeader = item.Label(Consts.KEY_NAME, "").Evaluate(); var wm = ServiceRegistration.Get <IWorkflowManager>(); wm.NavigatePushAsync(STATE_DEVICE_CONFIGURE, new NavigationContextConfig() { NavigationContextDisplayLabel = CurrentPlayerHeader }); }
protected void Reset() { EndMapping(); ResetMapper(); CurrentPlayerHeader = null; CurrentDeviceName = null; _currentDevice = null; _currentPortMapping = null; _portsList.Clear(); _portsList.FireChange(); _deviceList.Clear(); _deviceList.FireChange(); _inputList.Clear(); _inputList.FireChange(); }
/// <summary> /// This action deletes a previously instantiated port mapping. /// As each entry is deleted, the array is compacted, and the evented variable PortMappingNumberOfEntries is decremented. /// </summary> /// <param name="upnp"></param> /// <returns></returns> public bool DeletePortMapping(IUPnPUpdater upnp, PortMapping mapping) { UPnPFunction func = new UPnPFunction(); func.Name = "DeletePortMapping"; func.Service = this; func.Arguments.Add("NewRemoteHost", (mapping.RemoteHost != null ? mapping.RemoteHost : string.Empty)); func.Arguments.Add("NewExternalPort", mapping.ExternalPort.ToString()); func.Arguments.Add("NewProtocol", mapping.Protocol); FmdcEventArgs e = new FmdcEventArgs(Actions.UPnPFunctionCall, func); upnp.FireUpdateBase(e); return(e.Handled); }
public void StopBlocking() { // All public API methods are wrapped in a single thread lock. // This frees users to invoke the public API from multiple threads, but provides us a bit of sanity. lock (singleThreadLock) { refreshExternalIPThreadFlags = ThreadFlags.ShouldQuit; updatePortMappingsThreadFlags = ThreadFlags.ShouldQuit; Monitor.Enter(multiThreadLock); NATPMP.natpmp_t natpmp = new NATPMP.natpmp_t(); NATPMP.initnatpmp(ref natpmp); List <PortMapping> mappingsToRemove = PortMapper.SharedInstance.PortMappingsToRemove; lock (mappingsToRemove) { while (mappingsToRemove.Count > 0) { PortMapping pm = mappingsToRemove[0]; if (pm.MappingStatus == PortMappingStatus.Mapped) { RemovePortMapping(pm, ref natpmp); } mappingsToRemove.RemoveAt(0); } } List <PortMapping> mappingsToStop = PortMapper.SharedInstance.PortMappings; lock (mappingsToStop) { for (int i = 0; i < mappingsToStop.Count; i++) { PortMapping pm = mappingsToStop[i]; if (pm.MappingStatus == PortMappingStatus.Mapped) { RemovePortMapping(pm, ref natpmp); } } } Monitor.Exit(multiThreadLock); } }
private void okButton_Click(object sender, EventArgs e) { UInt16 localPort; UInt16.TryParse(localPortTextBox.Text, out localPort); UInt16 publicPort; UInt16.TryParse(publicPortTextBox.Text, out publicPort); PortMappingTransportProtocol protocol; if (tcpCheckBox.Checked) { if (udpCheckBox.Checked) { protocol = PortMappingTransportProtocol.Both; } else { protocol = PortMappingTransportProtocol.TCP; } } else { protocol = PortMappingTransportProtocol.UDP; } PortMapping pm = new PortMapping(localPort, publicPort, protocol); String description; if (descriptionTextBox.ForeColor == Color.Gray) { description = ""; } else { description = descriptionTextBox.Text; } WindowManager.GetMainForm().AddPortMapping(pm, description); ClearForm(); Close(); }
public ContainersStack(Construct parent, string id, IStackProps props) : base(parent, id, props) { var vpc = Vpc.FromLookup(this, id = "DefaultVpc", new VpcLookupOptions { IsDefault = true }); if (vpc == null) { throw new System.NullReferenceException($"Unable to determine default VPC in region {this.Region}"); } var cluster = new Cluster(this, "Cluster", new ClusterProps { Vpc = vpc }); var taskDef = new FargateTaskDefinition(this, "FargateTaskDefinition"); var currentDir = Directory.GetCurrentDirectory(); var path = Path.GetFullPath(Path.Combine(currentDir, @"dotnetapp/")); var containerOptions = new ContainerDefinitionOptions { Image = ContainerImage.FromAsset("dotnetapp") }; var portMapping = new PortMapping() { ContainerPort = 80, HostPort = 80 }; taskDef.AddContainer("Container", containerOptions).AddPortMappings(portMapping); var serviceProps = new ApplicationLoadBalancedFargateServiceProps() { MemoryLimitMiB = 512, Cpu = 256, TaskDefinition = taskDef }; ApplicationLoadBalancedFargateService service = new ApplicationLoadBalancedFargateService(this, "DotnetFargateApp", serviceProps); }
public async Task Create() { var result = await _docker.Client.Containers.CreateContainerAsync( new CreateContainerParameters { Name = Name, Image = _image.Name, HostConfig = new HostConfig { AutoRemove = IsAutoRemove, PortBindings = PortMapping.ToDictionary( pm => pm.ContainerPort, pm => pm.Binding ) } } ); }
private void removeButton_Click(object sender, EventArgs e) { if (mappingsListView.SelectedIndices.Count > 0) { int selectedIndex = mappingsListView.SelectedIndices[0]; ListViewItem selectedItem = mappings[selectedIndex]; PortMapping pm = (PortMapping)selectedItem.Tag; mappingsListView.BeginUpdate(); { mappings.Remove(selectedItem); mappingsListView.VirtualListSize = mappings.Count; } mappingsListView.EndUpdate(); PortMapper.SharedInstance.RemovePortMapping(pm); } }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region Interface Actions /////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void AddPortMapping(PortMapping pm, String description) { mappingsListView.BeginUpdate(); { ListViewItem lvi = new ListViewItem(description); lvi.SubItems.Add(pm.LocalPort.ToString()); lvi.SubItems.Add(pm.DesiredExternalPort.ToString()); lvi.SubItems.Add(""); lvi.SubItems.Add(pm.ExternalPort.ToString()); lvi.Tag = pm; mappings.Add(lvi); mappingsListView.VirtualListSize = mappings.Count; } mappingsListView.EndUpdate(); PortMapper.SharedInstance.AddPortMapping(pm); }
public override bool Equals(object obj) { if (obj == null) { return(false); } if (obj.GetHashCode() != GetHashCode()) { return(false); } if (obj.GetType() != typeof(PortMapping)) { return(false); } PortMapping other = obj as PortMapping; return(Equals(other)); }
public bool AddPortMapping(IUPnPUpdater upnp, PortMapping mapping) { UPnPFunction func = new UPnPFunction(); func.Name = "AddPortMapping"; func.Service = this; func.Arguments.Add("NewRemoteHost", (mapping.RemoteHost != null ? mapping.RemoteHost : string.Empty)); func.Arguments.Add("NewExternalPort", mapping.ExternalPort.ToString()); func.Arguments.Add("NewProtocol", mapping.Protocol); func.Arguments.Add("NewInternalPort", mapping.InternalPort.ToString()); func.Arguments.Add("NewInternalClient", mapping.InternalHost); func.Arguments.Add("NewEnabled", (mapping.Enable ? "1" : "0")); func.Arguments.Add("NewPortMappingDescription", mapping.Description); func.Arguments.Add("NewLeaseDuration", mapping.LeaseDuration.ToString()); FmdcEventArgs e = new FmdcEventArgs(Actions.UPnPFunctionCall, func); upnp.FireUpdateBase(e); return e.Handled; }
internal FargateStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { // Create VPC var vpc = new Vpc(this, "SampleVpc", new VpcProps { MaxAzs = 2 }); // Create ECS cluster var cluster = new Cluster(this, "SampleCluster", new ClusterProps { Vpc = vpc }); var taskDef = new FargateTaskDefinition(this, "FargateTaskDefinition"); // Build container image from local assets var containerOptions = new ContainerDefinitionOptions { Image = ContainerImage.FromAsset("webapp") }; var portMapping = new PortMapping() { ContainerPort = 80, HostPort = 80 }; taskDef .AddContainer("Container", containerOptions) .AddPortMappings(portMapping); // Create Fargate Service behind Application Load Balancer new ApplicationLoadBalancedFargateService(this, "DotnetFargateSampleApp", new ApplicationLoadBalancedFargateServiceProps() { Cluster = cluster, MemoryLimitMiB = 512, Cpu = 256, TaskDefinition = taskDef }); }
public bool AddPortMapping(IUPnPUpdater upnp, PortMapping mapping) { UPnPFunction func = new UPnPFunction(); func.Name = "AddPortMapping"; func.Service = this; func.Arguments.Add("NewRemoteHost", (mapping.RemoteHost != null ? mapping.RemoteHost : string.Empty)); func.Arguments.Add("NewExternalPort", mapping.ExternalPort.ToString()); func.Arguments.Add("NewProtocol", mapping.Protocol); func.Arguments.Add("NewInternalPort", mapping.InternalPort.ToString()); func.Arguments.Add("NewInternalClient", mapping.InternalHost); func.Arguments.Add("NewEnabled", (mapping.Enable ? "1" : "0")); func.Arguments.Add("NewPortMappingDescription", mapping.Description); func.Arguments.Add("NewLeaseDuration", mapping.LeaseDuration.ToString()); FmdcEventArgs e = new FmdcEventArgs(Actions.UPnPFunctionCall, func); upnp.FireUpdateBase(e); return(e.Handled); }
public async Task <PortMapping> GetGenericPortMappingEntry(int index) { var actionName = "GetGenericPortMappingEntry"; var args = new ServiceArgMap(); args .Add(new XmlSerializable("NewPortMappingIndex", index)) ; var content = GetContent(actionName, args); var response = await m_httpClient.PostAsync(m_uri, content); var responseContent = await response.Content.ReadAsByteArrayAsync(); var result = new PortMapping(); ParseResponse(responseContent, actionName, new ServiceArgMap().Add(result)); return(result); }
private void PortMappingChanged(PortMapper sender, PortMapping pm) { lock (lockObj) { if (pm != myMapping) { return; } if (pm.MappingStatus != PortMappingStatus.Mapped) { return; } externalPort = pm.ExternalPort; logger.Info("External port is registered: " + externalPort); if (IsReadyToNotifyCloud()) { TaskQueue.EnqueueMedium(this.NotifyCloudOfExternalPort); } } }
private void cmdForward_Click(object sender, System.EventArgs e) { if (listPorts.Items.Count == 0) { MessageBox.Show("You have selected no ports to forward!", "No ports selected!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } foreach (ListViewItem item in listPorts.Items) { PortMapping portMapping = (PortMapping)item.Tag; item.ForeColor = _portForwarder.ForwardPort(portMapping.Protocol, portMapping.Port) ? Color.Green : Color.Red; } MessageBox.Show( "The selected ports have been forwarded through UPnP.\n\nPorts that were forwarded successfully are marked with green color whereas, ports that weren't forwarded are marked red.", "Forward successful!", MessageBoxButtons.OK, MessageBoxIcon.Information); }
public ContainersStack(Construct parent, string id, IStackProps props) : base(parent, id, props) { // The code that defines your stack goes here var vpc = new Vpc(this, "VPC"); var cluster = new Cluster(this, "Cluster", new ClusterProps { Vpc = vpc }); var taskDef = new FargateTaskDefinition(this, "FargateTaskDefinition"); var rootDirectory = Directory.GetCurrentDirectory(); var path = Path.GetFullPath(Path.Combine(rootDirectory, @"dotnetapp/")); var containerOptions = new ContainerDefinitionOptions { Image = ContainerImage.FromAsset("dotnetapp") }; var portMapping = new PortMapping() { ContainerPort = 80, HostPort = 80 }; taskDef.AddContainer("Container", containerOptions).AddPortMappings(portMapping); var serviceProps = new ApplicationLoadBalancedFargateServiceProps() { MemoryLimitMiB = 512, Cpu = 256, TaskDefinition = taskDef }; ApplicationLoadBalancedFargateService service = new ApplicationLoadBalancedFargateService(this, "DotnetFargateApp", serviceProps); }
internal Example3Stack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { var vpcStack = new VpcStack(this, "someTestVpc"); var cluster = new Cluster(this, "WhatDayOfWeekCluster", new ClusterProps { Vpc = vpcStack.Vpc }); var taskDef = new FargateTaskDefinition(this, "WhatDayOfWeekTaskDefinition"); var rootDirectory = Directory.GetCurrentDirectory(); var path = Path.GetFullPath(Path.Combine(rootDirectory, @"App/WhatDayOfWeek")); var containerOptions = new ContainerDefinitionOptions { Image = ContainerImage.FromAsset("App/WhatDayOfWeek") }; var portMapping = new PortMapping() { ContainerPort = 80, HostPort = 80 }; taskDef.AddContainer("WhatDayOfWeekContainer", containerOptions).AddPortMappings(portMapping); var serviceProps = new ApplicationLoadBalancedFargateServiceProps() { MemoryLimitMiB = 512, Cpu = 256, TaskDefinition = taskDef }; ApplicationLoadBalancedFargateService service = new ApplicationLoadBalancedFargateService(this, "WhatDayOfWeekApp", serviceProps); }
public void CheckForExistingPortMapping(string remote_host, int external_port, string protocol) { PortMapping pm = new PortMapping(); pm.RemoteHost = remote_host; pm.ExternalPort = external_port; pm.Protocol = protocol; CheckForExistingPortMapping(pm); }
public void AddPortMapping(string remote_host, int external_port, int internal_port, string protocol, string internal_client, string description, long lease_duration, bool enabled) { PortMapping pm = new PortMapping(); pm.RemoteHost= remote_host; pm.ExternalPort = external_port; pm.InternalPort = internal_port; pm.Protocol= protocol; pm.InternalClient=internal_client; pm.Description=description; pm.LeaseDuration=lease_duration; pm.Enabled = enabled; AddPortMapping(pm); }
/// <summary> /// Gets the port at which the game server should listen on (differs between containers and processes). /// </summary> /// <param name="portMapping"></param> /// <returns></returns> protected abstract int GetLegacyServerListeningPort(PortMapping portMapping);
protected bool Equals(PortMapping other) { return(Port == other.Port && Protocol == other.Protocol); }
/// <summary> /// 保存配置信息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void save_Click(object sender, EventArgs e) { List<PortMapping> nodes = new List<PortMapping>(); if (DealXml.Remove("portMapping")) { foreach (DataGridViewRow row in dgvPortMapping.Rows) { PortMapping tempNode = new PortMapping(); tempNode.PortNo = row.Cells[0].Value == null ? "" : row.Cells[0].Value.ToString(); tempNode.MarkText = row.Cells[1].Value == null ? "" : row.Cells[1].Value.ToString(); tempNode.StepName = row.Cells[2].Value == null ? "" : row.Cells[2].Value.ToString(); nodes.Add(tempNode); } } if (DealXml.WritePortMappingNodesToXml(nodes)) { KryptonMessageBox.Show("保存成功!"); this.Close(); } }
public void CheckForExistingPortMapping(PortMapping pm) { if (pm.Protocol != "TCP" && pm.Protocol != "UDP") PortMappingCheckCompleted(this, pm,false, false); if (root_device != null) { //searching sub devices for a wan ip connections service SubDevice.Service wan_ip_connection = root_device.GetServiceByType("urn:schemas-upnp-org:service:WANIPConnection:1"); if (wan_ip_connection != null) { Console.WriteLine("Found the wan ip connection service."); Console.WriteLine("service control url: " + url_base + wan_ip_connection.ControlUrl); Console.WriteLine("service type: [" + wan_ip_connection.ServiceType + "]"); string soap_method = "GetSpecificPortMappingEntry"; string soap_body = "<?xml version=\"1.0\"?>\r\n"; soap_body += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n"; soap_body += "<s:Body>\r\n"; soap_body += "<m:" + soap_method + " xmlns:m=\"" + wan_ip_connection.ServiceType + "\">\r\n"; soap_body += "<NewRemoteHost>" + pm.RemoteHost + "</NewRemoteHost>"; soap_body += "<NewExternalPort>" + pm.ExternalPort + "</NewExternalPort>"; soap_body += "<NewProtocol>" + pm.Protocol + "</NewProtocol>"; soap_body += "</m:" + soap_method + ">\r\n"; soap_body += "</s:Body>\r\n"; soap_body += "</s:Envelope>\r\n"; string soap_action = wan_ip_connection.ServiceType + "#" + soap_method; SOAP soap = new SOAP(url_base + wan_ip_connection.ControlUrl, soap_body, soap_action); soap.RequestFinished += delegate(SOAP request_finished_soap, bool request_successful) { bool successful = false; bool exists = false; if (request_successful) { //Console.WriteLine("Soap Response: \n" + request_finished_soap.Response); string[] seps = { "\r\n" }; string[] lines = request_finished_soap.Response.Split(seps, StringSplitOptions.RemoveEmptyEntries); if (lines.Length > 0) { if (lines[0] == "HTTP/1.1 200 OK") { if (request_finished_soap.Response.IndexOf(soap_method + "Response") != -1) { int values_found = 0; string internal_port = "0"; int internal_port_start = request_finished_soap.Response.IndexOf("<NewInternalPort>"); if (internal_port_start != -1) { internal_port = request_finished_soap.Response.Substring(internal_port_start + "<NewInternalPort>".Length); int internal_port_end = internal_port.IndexOf("</NewInternalPort>"); if (internal_port_end != -1) { internal_port = internal_port.Substring(0, internal_port_end); values_found++; } } try { pm.InternalPort = int.Parse(internal_port); } catch (Exception ex) { Console.WriteLine("error parsing internal port: "+ex.Message); } int internal_client_start = request_finished_soap.Response.IndexOf("<NewInternalClient>"); if (internal_client_start != -1) { pm.InternalClient = request_finished_soap.Response.Substring(internal_client_start + "<NewInternalClient>".Length); int internal_client_end = pm.InternalClient.IndexOf("</NewInternalClient>"); if (internal_client_end != -1) { pm.InternalClient = pm.InternalClient.Substring(0, internal_client_end); values_found++; } } string enabled = "0"; int enabled_start = request_finished_soap.Response.IndexOf("<NewEnabled>"); if (enabled_start != -1) { enabled = request_finished_soap.Response.Substring(enabled_start + "<NewEnabled>".Length); int enabled_end = enabled.IndexOf("</NewEnabled>"); if (enabled_end != -1) { enabled = enabled.Substring(0, enabled_end); values_found++; } } if (enabled == "1") pm.Enabled = true; else pm.Enabled = false; int description_start = request_finished_soap.Response.IndexOf("<NewPortMappingDescription>"); if (description_start != -1) { pm.Description = request_finished_soap.Response.Substring(description_start + "<NewPortMappingDescription>".Length); int description_end = pm.Description.IndexOf("</NewPortMappingDescription>"); if (description_end != -1) { pm.Description = pm.Description.Substring(0, description_end); values_found++; } } string lease_duration = "0"; int lease_duration_start = request_finished_soap.Response.IndexOf("<NewLeaseDuration>"); if (lease_duration_start != -1) { lease_duration = request_finished_soap.Response.Substring(lease_duration_start + "<NewLeaseDuration>".Length); int lease_duration_end = lease_duration.IndexOf("</NewLeaseDuration>"); if (lease_duration_end != -1) { lease_duration = lease_duration.Substring(0, lease_duration_end); values_found++; } } try { pm.LeaseDuration = int.Parse(lease_duration); } catch (Exception ex) { Console.WriteLine("error parsing lease duration: " + ex.Message); } if (values_found == 5) exists = true; } } } successful = true; } else Console.WriteLine("Soap Request failed."); if (PortMappingCheckCompleted != null) PortMappingCheckCompleted(this, pm,exists, successful); }; soap.StartRequest(); } } }
public PortMappingItem(string name, PortMapping portMapping) : base(Consts.KEY_NAME, name) { _portMapping = portMapping; SetLabel(KEY_MAPPED_DEVICE, portMapping.DeviceName); }
private bool RemovePortMapping(PortMapping portMapping) { // Make sure the mapping still belongs to us IPAddress ourIP = PortMapper.SharedInstance.LocalIPAddress; String ourDescription = GetPortMappingDescription(); bool udpMappingStolen = false; bool tcpMappingStolen = false; if ((portMapping.TransportProtocol & PortMappingTransportProtocol.UDP) > 0) { ExistingUPnPPortMapping existingPM; if (existingUPnPPortMappingsUdpDict.TryGetValue(portMapping.ExternalPort, out existingPM)) { if (!existingPM.LocalAddress.Equals(ourIP) || !existingPM.Description.Equals(ourDescription)) { // The mapping was stolen by another machine or process // Do not remove it, but for our purposes we can consider it removed DebugLog.WriteLine("UPnP: RemovePortMapping: UDP mapping stolen"); udpMappingStolen = true; } } } if ((portMapping.TransportProtocol & PortMappingTransportProtocol.TCP) > 0) { ExistingUPnPPortMapping existingPM; if (existingUPnPPortMappingsTcpDict.TryGetValue(portMapping.ExternalPort, out existingPM)) { if (!existingPM.LocalAddress.Equals(ourIP) || !existingPM.Description.Equals(ourDescription)) { // The mapping was stolen by another machine or process // Do not remove it, but for our purposes we can consider it removed DebugLog.WriteLine("UPnP: RemovePortMapping: TCM mapping stolen"); tcpMappingStolen = true; } } } int result = MiniUPnP.UPNPCOMMAND_SUCCESS; bool udpResult = true; bool tcpResult = true; String extPortStr = portMapping.ExternalPort.ToString(); if ((portMapping.TransportProtocol & PortMappingTransportProtocol.UDP) > 0 && !udpMappingStolen) { try { result = MiniUPnP.UPNP_DeletePortMapping(urls.controlURL, igddata.ServiceType, extPortStr, "UDP"); } catch (AccessViolationException) { // I have no idea why the above method sometimes throws an AccessException. // The odd part about it is that it works perfect, except for the stupid exception. // So the exception can safely be ignored, it just bugs me because it feels like a hack. DebugLog.WriteLine("Ignoring exception from method MiniUPnP.UPNP_DeletePortMapping"); } DebugLog.WriteLine("UPnP: RemovePortMapping: UDP: result = {0}", result); udpResult = (result == MiniUPnP.UPNPCOMMAND_SUCCESS); } if ((portMapping.TransportProtocol & PortMappingTransportProtocol.TCP) > 0 && !tcpMappingStolen) { try { result = MiniUPnP.UPNP_DeletePortMapping(urls.controlURL, igddata.ServiceType, extPortStr, "TCP"); } catch (AccessViolationException) { // I have no idea why the above method sometimes throws an AccessException. // The odd part about it is that it works perfect, except for the stupid exception. // So the exception can safely be ignored, it just bugs me because it feels like a hack. DebugLog.WriteLine("Ignoring exception from method MiniUPnP.UPNP_DeletePortMapping"); } DebugLog.WriteLine("UPnP: RemovePortMapping: TCP: result = {0}", result); tcpResult = (result == MiniUPnP.UPNPCOMMAND_SUCCESS); } portMapping.SetMappingStatus(PortMappingStatus.Unmapped); return(udpResult && tcpResult); }
public void DeletePortMapping(PortMapping pm) { if (pm.Protocol != "TCP" && pm.Protocol != "UDP") DeletingPortMappingCompleted(this, pm, false); if (root_device != null) { //searching sub devices for a wan ip connections service SubDevice.Service wan_ip_connection = root_device.GetServiceByType("urn:schemas-upnp-org:service:WANIPConnection:1"); if (wan_ip_connection != null) { Console.WriteLine("Found the wan ip connection service."); Console.WriteLine("service control url: " + url_base + wan_ip_connection.ControlUrl); Console.WriteLine("service type: [" + wan_ip_connection.ServiceType + "]"); string soap_method = "DeletePortMapping"; string soap_body = "<?xml version=\"1.0\"?>\r\n"; soap_body += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n"; soap_body += "<s:Body>\r\n"; soap_body += "<m:" + soap_method + " xmlns:m=\"" + wan_ip_connection.ServiceType + "\">\r\n"; soap_body += "<NewRemoteHost>" + pm.RemoteHost + "</NewRemoteHost>"; soap_body += "<NewExternalPort>" + pm.ExternalPort + "</NewExternalPort>"; soap_body += "<NewProtocol>" + pm.Protocol + "</NewProtocol>"; soap_body += "</m:" + soap_method + ">\r\n"; soap_body += "</s:Body>\r\n"; soap_body += "</s:Envelope>\r\n"; string soap_action = wan_ip_connection.ServiceType + "#" + soap_method; SOAP soap = new SOAP(url_base + wan_ip_connection.ControlUrl, soap_body, soap_action); soap.RequestFinished += delegate(SOAP request_finished_soap, bool request_successful) { bool successful = false; if (request_successful) { //Console.WriteLine("Soap Response: \n" + request_finished_soap.Response); string[] seps = { "\r\n" }; string[] lines = request_finished_soap.Response.Split(seps, StringSplitOptions.RemoveEmptyEntries); if (lines.Length > 0) { if (lines[0] == "HTTP/1.1 200 OK") { if (request_finished_soap.Response.IndexOf(soap_method + "Response") != -1) { successful = true; } } } } else Console.WriteLine("Soap Request failed."); if (DeletingPortMappingCompleted != null) DeletingPortMappingCompleted(this, pm, successful); }; soap.StartRequest(); } } }
public void DeletePortMapping(string remote_host, int external_port, string protocol) { PortMapping pm = new PortMapping(); pm.RemoteHost = remote_host; pm.ExternalPort = external_port; pm.Protocol = protocol; DeletePortMapping(pm); }
private bool AddPortMapping(PortMapping portMapping) { portMapping.SetMappingStatus(PortMappingStatus.Trying); String intPortStr = portMapping.LocalPort.ToString(); String intClient = PortMapper.SharedInstance.LocalIPAddress.ToString(); String description = GetPortMappingDescription(); bool done = false; int attemptCount = 0; do { int udpErrCode = 0; int tcpErrCode = 0; bool udpResult = true; bool tcpResult = true; UInt16 extPort; if (portMapping.DesiredExternalPort < (65535 - 40)) { extPort = (UInt16)(portMapping.DesiredExternalPort + attemptCount); } else { extPort = (UInt16)(portMapping.DesiredExternalPort - attemptCount); } String extPortStr = extPort.ToString(); if ((portMapping.TransportProtocol & PortMappingTransportProtocol.UDP) > 0) { ExistingUPnPPortMapping existingPM; if (existingUPnPPortMappingsUdpDict.TryGetValue(extPort, out existingPM)) { udpErrCode = 718; DebugLog.WriteLine("UPnP: AddPortMapping: UDP: mapping already exists"); } else { udpErrCode = MiniUPnP.UPNP_AddPortMapping(urls.controlURL, igddata.ServiceType, extPortStr, intPortStr, intClient, description, "UDP"); DebugLog.WriteLine("UPnP: AddPortMapping: UDP: result = {0}", udpErrCode); } udpResult = (udpErrCode == MiniUPnP.UPNPCOMMAND_SUCCESS); } if ((portMapping.TransportProtocol & PortMappingTransportProtocol.TCP) > 0) { ExistingUPnPPortMapping existingPM; if (existingUPnPPortMappingsTcpDict.TryGetValue(extPort, out existingPM)) { tcpErrCode = 718; DebugLog.WriteLine("UPnP: AddPortMapping: TCP: mapping already exists"); } else { tcpErrCode = MiniUPnP.UPNP_AddPortMapping(urls.controlURL, igddata.ServiceType, extPortStr, intPortStr, intClient, description, "TCP"); DebugLog.WriteLine("UPnP: AddPortMapping: TCP: result = {0}", tcpErrCode); } tcpResult = (tcpErrCode == MiniUPnP.UPNPCOMMAND_SUCCESS); } if (udpResult && !tcpResult) { DebugLog.WriteLine("Deleting UDP mapping"); try { MiniUPnP.UPNP_DeletePortMapping(urls.controlURL, igddata.ServiceType, extPortStr, "UDP"); } catch (AccessViolationException) { // I have no idea why the above method sometimes throws an AccessException. // The odd part about it is that it works perfect, except for the stupid exception. // So the exception can safely be ignored, it just bugs me because it feels like a hack. DebugLog.WriteLine("Ignoring exception from method MiniUPnP.UPNP_DeletePortMapping"); } } if (tcpResult && !udpResult) { DebugLog.WriteLine("Deleting TCP mapping"); try { MiniUPnP.UPNP_DeletePortMapping(urls.controlURL, igddata.ServiceType, extPortStr, "TCP"); } catch (AccessViolationException) { // I have no idea why the above method sometimes throws an AccessException. // The odd part about it is that it works perfect, except for the stupid exception. // So the exception can safely be ignored, it just bugs me because it feels like a hack. DebugLog.WriteLine("Ignoring exception from method MiniUPnP.UPNP_DeletePortMapping"); } } if (udpResult && tcpResult) { // All attempted port mappings were successful portMapping.SetExternalPort(extPort); portMapping.SetMappingStatus(PortMappingStatus.Mapped); return(true); } attemptCount++; if (attemptCount >= 10) { // We've tried 10 different mappings and still no success done = true; } else if (!udpResult && udpErrCode != 718) { // We received non-conflict error done = true; } else if (!tcpResult && tcpErrCode != 718) { // We received non-conflict error done = true; } } while (!done); portMapping.SetMappingStatus(PortMappingStatus.Unmapped); return(false); }
/// <summary> /// This action deletes a previously instantiated port mapping. /// As each entry is deleted, the array is compacted, and the evented variable PortMappingNumberOfEntries is decremented. /// </summary> /// <param name="upnp"></param> /// <returns></returns> public bool DeletePortMapping(IUPnPUpdater upnp, PortMapping mapping) { UPnPFunction func = new UPnPFunction(); func.Name = "DeletePortMapping"; func.Service = this; func.Arguments.Add("NewRemoteHost", (mapping.RemoteHost != null ? mapping.RemoteHost : string.Empty)); func.Arguments.Add("NewExternalPort", mapping.ExternalPort.ToString()); func.Arguments.Add("NewProtocol", mapping.Protocol); FmdcEventArgs e = new FmdcEventArgs(Actions.UPnPFunctionCall, func); upnp.FireUpdateBase(e); return e.Handled; }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #region Update Port Mappings Thread /////////////////////////////////////////////////////////////////////////////////////////////////////////////// private void UpdatePortMappingsThread() { Monitor.Enter(multiThreadLock); OnDidBeginWorking(); // Remove existing mappings scheduled for removal. // These are mappings that weren't created by us, but have been explicity set for removal. List <ExistingUPnPPortMapping> existingMappingsToRemove; existingMappingsToRemove = PortMapper.SharedInstance.ExistingUPnPPortMappingsToRemove; lock (existingMappingsToRemove) { while ((existingMappingsToRemove.Count > 0) && (updatePortMappingsThreadFlags == ThreadFlags.None)) { ExistingUPnPPortMapping existingMappingToRemove = existingMappingsToRemove[0]; RemovePortMapping(existingMappingToRemove); existingMappingsToRemove.RemoveAt(0); } } // We need to safeguard mappings that others might have made. // UPnP is quite generous in giving us what we want, // even if other mappings are there, especially from the same local machine. DoUpdateExistingUPnPPortMappings(); // Remove mappings scheduled for removal List <PortMapping> mappingsToRemove = PortMapper.SharedInstance.PortMappingsToRemove; lock (mappingsToRemove) { while ((mappingsToRemove.Count > 0) && (updatePortMappingsThreadFlags == ThreadFlags.None)) { PortMapping mappingToRemove = mappingsToRemove[0]; if (mappingToRemove.MappingStatus == PortMappingStatus.Mapped) { RemovePortMapping(mappingToRemove); } mappingsToRemove.RemoveAt(0); } } // If the port mapper is running: // -Add new mappings // If the port mapper is stopped: // -Remove any existing mappings List <PortMapping> mappings = PortMapper.SharedInstance.PortMappings; lock (mappings) { for (int i = 0; i < mappings.Count && updatePortMappingsThreadFlags == ThreadFlags.None; i++) { PortMapping currentMapping = mappings[i]; bool isRunning = PortMapper.SharedInstance.IsRunning; if (currentMapping.MappingStatus == PortMappingStatus.Unmapped && isRunning) { AddPortMapping(currentMapping); } else if (currentMapping.MappingStatus == PortMappingStatus.Mapped && !isRunning) { RemovePortMapping(currentMapping); } } } Monitor.Exit(multiThreadLock); if (PortMapper.SharedInstance.IsRunning) { if ((updatePortMappingsThreadFlags & ThreadFlags.ShouldRestart) > 0) { UpdatePortMappings(); } else if ((updatePortMappingsThreadFlags & ThreadFlags.ShouldQuit) > 0) { Refresh(); } } OnDidEndWorking(); }
/// <summary> /// This action reports the Static Port Mapping specified by the unique tuple of RemoteHost, ExternalPort and PortMappingProtocol. /// </summary> /// <param name="mapping"></param> /// <returns></returns> public bool GetSpecificPortMappingEntry(IUPnPUpdater upnp, ref PortMapping mapping) { UPnPFunction func = new UPnPFunction(); func.Name = "GetSpecificPortMappingEntry"; func.Service = this; func.Arguments.Add("NewRemoteHost", (mapping.RemoteHost != null ? mapping.RemoteHost : string.Empty)); func.Arguments.Add("NewExternalPort", mapping.ExternalPort.ToString()); func.Arguments.Add("NewProtocol", mapping.Protocol); func.Arguments.Add("NewInternalPort", mapping.InternalPort.ToString()); func.Arguments.Add("NewInternalClient", string.Empty); func.Arguments.Add("NewEnabled", string.Empty); func.Arguments.Add("NewPortMappingDescription", string.Empty); func.Arguments.Add("NewLeaseDuration", string.Empty); FmdcEventArgs e = new FmdcEventArgs(Actions.UPnPFunctionCall, func); upnp.FireUpdateBase(e); if (e.Handled) { func = e.Data as UPnPFunction; if (func != null) { string str = func.Arguments["NewRemoteHost"]; if (!string.IsNullOrEmpty(str)) mapping.RemoteHost = str; str = func.Arguments["NewExternalPort"]; if (!string.IsNullOrEmpty(str)) { try { mapping.ExternalPort = int.Parse(str); } catch { } } str = func.Arguments["NewProtocol"]; if (!string.IsNullOrEmpty(str)) mapping.Protocol = str; str = func.Arguments["NewInternalPort"]; if (!string.IsNullOrEmpty(str)) { try { mapping.InternalPort = int.Parse(str); } catch { } } str = func.Arguments["NewInternalClient"]; if (!string.IsNullOrEmpty(str)) mapping.InternalHost = str; str = func.Arguments["NewEnabled"]; if (!string.IsNullOrEmpty(str)) { switch (str) { case "1": mapping.Enable = true; break; case "0": mapping.Enable = false; break; } } str = func.Arguments["NewPortMappingDescription"]; if (!string.IsNullOrEmpty(str)) mapping.Description = str; str = func.Arguments["NewLeaseDuration"]; if (!string.IsNullOrEmpty(str)) { try { mapping.LeaseDuration = int.Parse(str); } catch { } } } } return e.Handled; }