/// <summary> /// Creates a new port map. /// </summary> /// <param name="port">The port to map.</param> /// <param name="externalPort">The port which has been mapped, -1 if it failed.</param> /// <returns>True if successfull, else False.</returns> public static bool CreatePortMap(int port, out int externalPort) { if (!_discoveryComplete) { externalPort = -1; return false; } try { Mapping mapping = new Mapping(Protocol.Tcp, port, port); for (int i = 0; i < 3; i++) _device.CreatePortMap(mapping); if (_mappings.ContainsKey(mapping.PrivatePort)) _mappings[mapping.PrivatePort] = mapping; else _mappings.Add(mapping.PrivatePort, mapping); externalPort = mapping.PublicPort; return true; } catch (MappingException) { externalPort = -1; return false; } }
public static void ForwardPort() { try { var mapping = new Mapping(Protocol.Tcp, Game.Settings.Server.ExternalPort, Game.Settings.Server.ListenPort); NatDevice.CreatePortMap(mapping); Log.Write("server", "Create port mapping: protocol={0}, public={1}, private={2}", mapping.Protocol, mapping.PublicPort, mapping.PrivatePort); } catch (Exception e) { Log.Write("server", "Can not forward ports via UPnP: {0}", e); Game.Settings.Server.AllowPortForward = false; } }
private void DeviceFound (object sender, DeviceEventArgs args) { try { INatDevice device = args.Device; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine ("Device found"); Console.ResetColor(); Console.WriteLine ("Type: {0}", device.GetType().Name); Console.WriteLine ("IP: {0}", device.GetExternalIP ()); device.CreatePortMap(new Mapping(Protocol.Tcp, 1500, 1500)); Console.WriteLine ("---"); return; Mapping mapping = new Mapping(Protocol.Tcp, 6001, 6001); device.CreatePortMap(mapping); Console.WriteLine("Create Mapping: protocol={0}, public={1}, private={2}", mapping.Protocol, mapping.PublicPort, mapping.PrivatePort); try { Mapping m = device.GetSpecificMapping(Protocol.Tcp, 6001); Console.WriteLine("Specific Mapping: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort); } catch { Console.WriteLine("Couldnt get specific mapping"); } foreach (Mapping mp in device.GetAllMappings()) { Console.WriteLine("Existing Mapping: protocol={0}, public={1}, private={2}", mp.Protocol, mp.PublicPort, mp.PrivatePort); device.DeletePortMap(mp); } Console.WriteLine("External IP: {0}", device.GetExternalIP()); Console.WriteLine("Done..."); } catch (Exception ex) { Console.WriteLine (ex.Message); Console.WriteLine (ex.StackTrace); } }
private void AddMap(ref INatDevice device, Protocol ptype, int localport, int publicport, string description) { try { Mapping mapper = null; mapper = new Mapping(Protocol.Tcp, localport, publicport); mapper.Description = description; device.CreatePortMap(mapper); } catch (MappingException) { MessageBox.Show("Sorry, something went wrong.\n" + "Could not add the port due to an error.\n" + "This error may occur because the port is already taken\n" + "or the port lies within a not allowed range.\n\n" + "Try a different port, for example above 1024.", "Error..."); } catch (Exception e) { MessageBox.Show("An unknown error occurred. The content of the error is:\n\n" + e.ToString(), "Error..."); } }
public void DeviceFound(object sender, DeviceEventArgs args) { try { INatDevice device = args.Device; logger.Info("Trovato dispositivo con UPNP abilitato."); logger.Info("Tipo: {0}", device.GetType().Name); logger.Info("IP Esterno del dispositivo: {0}", device.GetExternalIP()); Mapping mapTcp = new Mapping(Protocol.Tcp, Convert.ToInt32(tcpport), Convert.ToInt32(tcpport)); logger.Info("Creazione del PortMapping sul dispositivo UPNP: Protocollo={0}, Porta Public={1}, private={2}", mapTcp.Protocol, mapTcp.PublicPort, mapTcp.PrivatePort); device.CreatePortMap(mapTcp); Mapping mapUdp = new Mapping(Protocol.Udp, Convert.ToInt32(udpport), Convert.ToInt32(udpport)); logger.Info("Creazione del PortMapping sul dispositivo UPNP: Protocollo={0}, Porta Public={1}, private={2}", mapUdp.Protocol, mapUdp.PublicPort, mapUdp.PrivatePort); device.CreatePortMap(mapUdp); Mapping mapTcp2 = device.GetSpecificMapping(Protocol.Tcp, Convert.ToInt32(tcpport)); PortMappingOkTcp = true; logger.Info("Verifica del PortMapping Protocollo={0}, Porta={1} passata con successo", mapTcp2.Protocol, mapTcp2.PublicPort); Mapping mapUdp2 = device.GetSpecificMapping(Protocol.Udp, Convert.ToInt32(udpport)); PortMappingOkUdp = true; logger.Info("Verifica del PortMapping Protocollo={0}, Porta={1} passata con successo", mapUdp2.Protocol, mapUdp2.PublicPort); // Se il portfoward funziona interrompiamo il discovery // NOTA: rileviamo solo il primo router della lista NatUtility.StopDiscovery(); } catch (Exception ex) { logger.Fatal("Procedura UPNP Fallita."); logger.Fatal(ex.Message); logger.Fatal(ex.StackTrace); } }
public static void ForwardPort(int lifetime) { try { var mapping = new Mapping(Protocol.Tcp, Game.Settings.Server.ExternalPort, Game.Settings.Server.ListenPort, lifetime); NatDevice.CreatePortMap(mapping); Log.Write("server", "Create port mapping: protocol = {0}, public = {1}, private = {2}, lifetime = {3} s", mapping.Protocol, mapping.PublicPort, mapping.PrivatePort, mapping.Lifetime); } catch (MappingException e) { if (e.ErrorCode == 725 && lifetime != 0) { Log.Write("server", "NAT device answered with OnlyPermanentLeasesSupported. Retrying..."); ForwardPort(0); } else { Log.Write("server", "Can not forward ports via UPnP: {0}", e); Game.Settings.Server.AllowPortForward = false; } } }
public ListenPortController() { settings = SettingsManager.EngineSettings; devices = new List<INatDevice> (); tcpMapping = new Mapping (Protocol.Tcp, settings.ListenPort, settings.ListenPort); tcpMapping.Description = Defines.ApplicationName; udpMapping = new Mapping (Protocol.Udp, settings.ListenPort, settings.ListenPort); udpMapping.Description = Defines.ApplicationName; IPAddress[] addresses = null; try { addresses = NatUtility.GetLocalAddresses (false); } catch (Exception) { logger.Warn ("Could not resolve hostname, port forwarding may not work"); addresses = new IPAddress[] { IPAddress.Loopback }; } NatUtility.DeviceFound += OnDeviceFound; }
public void Dispose() { timer.Stop(); NatUtility.StopDiscovery(); NatUtility.DeviceFound -= NatUtility_DeviceFound; NatUtility.DeviceLost -= NatUtility_DeviceLost; lock (ports) { lock (devices) { foreach (var port in ports) { foreach (var device in devices) { Mapping mapping_tcp = new Mapping(Protocol.Tcp, port, port, 7200); Mapping mapping_udp = new Mapping(Protocol.Udp, port, port, 7200); device.BeginDeletePortMap(mapping_tcp, OnPortMapDeleted, device); device.BeginDeletePortMap(mapping_udp, OnPortMapDeleted, device); } } devices.Clear(); } ports.Clear(); } }
static void NatUtility_OpenPort(NatDeviceState device, int port) { lock (syncLock) { Mapping mapping = new Mapping(Protocol.Udp, port, port); device.Nat.BeginCreatePortMap(mapping, ar => { lock (syncLock) { try { device.Nat.EndCreatePortMap(ar); // finish this NatUtility_OpenPort_Finish(device, port); } catch (MappingException exn) { if (exn.ErrorCode == 718) { NatUtility_OpenPort_Finish(device, port); } else { BoltLog.Exception(exn); } } catch (Exception exn) { BoltLog.Exception(exn); } } }, null); } }
public abstract Task DeletePortMapAsync (Mapping mapping);
public abstract Task CreatePortMapAsync (Mapping mapping);
public bool upnp_create_mapping(Protocol prot, int internalPort, int externalPort) { if (isUPnPavailable()) { Mapping port_mapping = new Mapping(prot, internalPort, externalPort); try { device.CreatePortMap(port_mapping); } catch (MappingException) { xbs_messages.addInfoMessage(" @ UPnP error: could not forward port", xbs_message_sender.UPNP, xbs_message_type.ERROR); return false; } lock (this) my_PortMappings.Add(port_mapping); xbs_messages.addInfoMessage(" @ UPnP port mapped from " + public_ip + ":" + port_mapping.PublicPort, xbs_message_sender.UPNP); return true; } return false; }
private void RenewPort(int port) { lock (devices) { foreach (var device in devices) { Mapping mapping_tcp = new Mapping(Protocol.Tcp, port, port, 7200); Mapping mapping_udp = new Mapping(Protocol.Udp, port, port, 7200); device.BeginCreatePortMap(mapping_tcp, OnPortMapDeleted, device); device.BeginCreatePortMap(mapping_udp, OnPortMapDeleted, device); } } }
private void RemovePort(int port) { lock (ports) { if (!ports.Remove(port)) return; } lock (devices) { foreach (var device in devices) { Mapping mapping_tcp = new Mapping(Protocol.Tcp, port, port, 7200); Mapping mapping_udp = new Mapping(Protocol.Udp, port, port, 7200); device.BeginDeletePortMap(mapping_tcp, OnPortMapDeleted, device); device.BeginDeletePortMap(mapping_udp, OnPortMapDeleted, device); } } }
private void NatUtility_DeviceFound(object sender, DeviceEventArgs e) { lock (devices) { if (!devices.Add(e.Device)) { return; } } lock (ports) { foreach (var port in ports) { Mapping mapping_tcp = new Mapping(Protocol.Tcp, port, port, 7200); Mapping mapping_udp = new Mapping(Protocol.Udp, port, port, 7200); e.Device.BeginCreatePortMap(mapping_tcp, OnPortMapCreated, e.Device); e.Device.BeginCreatePortMap(mapping_udp, OnPortMapCreated, e.Device); } } }
private void AddPort(int port) { lock (ports) { if (ports.Any(p => p==port)) return; ports.Add(port); } lock (devices) { Mapping mapping_tcp = new Mapping(Protocol.Tcp, port, port, 7200); Mapping mapping_udp = new Mapping(Protocol.Udp, port, port, 7200); foreach (var device in devices) { device.BeginCreatePortMap(mapping_tcp, OnPortMapCreated, device); device.BeginCreatePortMap(mapping_udp, OnPortMapCreated, device); } } }
public void ChangePort() { logger.Info("UPnP changing port map"); RemoveMap(); tcpMapping = new Mapping (Protocol.Tcp, settings.ListenPort, settings.ListenPort); udpMapping = new Mapping (Protocol.Udp, settings.ListenPort, settings.ListenPort); tcpMapping.Description = Defines.ApplicationName; udpMapping.Description = Defines.ApplicationName; MapPort(); }
static void NatUtility_ClosePort(NatDeviceState device, int port) { lock (syncLock) { Mapping mapping = new Mapping(Protocol.Udp, port, port); device.Nat.BeginDeletePortMap(mapping, ar => { lock (syncLock) { try { device.Nat.EndDeletePortMap(ar); ClosePortMapping(device, port); } catch (MappingException exn) { if (exn.ErrorCode == 714) { ClosePortMapping(device, port); } else { BoltLog.Exception(exn); } } catch (Exception exn) { BoltLog.Exception(exn); } } }, null); } }
public void Clear() { lock (ports) { lock (devices) { foreach (var port in ports) { foreach (var device in devices) { Mapping mapping_tcp = new Mapping(Protocol.Tcp, port, port, 7200); Mapping mapping_udp = new Mapping(Protocol.Udp, port, port, 7200); device.BeginDeletePortMap(mapping_tcp, OnPortMapDeleted, device); device.BeginDeletePortMap(mapping_udp, OnPortMapDeleted, device); } } } ports.Clear(); } }
internal bool DetectExternalEndpoint(CancellationToken cancellation = default(CancellationToken)) { using(Trace.Open()) { int externalPort = 0; try { var device = GetDevice(cancellation); if(device == null) return false; using(Trace.Open(false)) { try { var externalIp = device.GetExternalIP(); ExternalEndpoint = Utils.EnsureIPv6(new IPEndPoint(externalIp, externalPort)); NodeServerTrace.Information("External endpoint detected " + ExternalEndpoint); var mapping = device.GetAllMappings(); externalPort = BitcoinPorts.FirstOrDefault(p => mapping.All(m => m.PublicPort != p)); if(externalPort == 0) NodeServerTrace.Error("Bitcoin node ports already used " + string.Join(",", BitcoinPorts), null); Mapping = new Mapping(Mono.Nat.Protocol.Tcp, InternalPort, externalPort, (int)LeasePeriod.TotalSeconds) { Description = RuleName }; try { device.CreatePortMap(Mapping); } catch(MappingException ex) { if(ex.ErrorCode != 725) //Does not support lease throw; Mapping.Lifetime = 0; device.CreatePortMap(Mapping); } NodeServerTrace.Information("Port mapping added " + Mapping); Device = device; if(Mapping.Lifetime != 0) { LogNextLeaseRenew(); Timer = new Timer(o => { if(isDisposed) return; using(Trace.Open(false)) { try { device.CreatePortMap(Mapping); NodeServerTrace.Information("Port mapping renewed"); LogNextLeaseRenew(); } catch(Exception ex) { NodeServerTrace.Error("Error when refreshing the port mapping with UPnP", ex); } finally { Timer.Change((int)CalculateNextRefresh().TotalMilliseconds, Timeout.Infinite); } } }); Timer.Change((int)CalculateNextRefresh().TotalMilliseconds, Timeout.Infinite); } } catch(Exception ex) { NodeServerTrace.Error("Error during address port detection on the upnp device", ex); } } } catch(OperationCanceledException) { NodeServerTrace.Information("Discovery cancelled"); throw; } catch(Exception ex) { NodeServerTrace.Error("Error during upnp discovery", ex); } return true; } }
public static void RemovePortforward() { try { var mapping = new Mapping(Protocol.Tcp, Game.Settings.Server.ExternalPort, Game.Settings.Server.ListenPort); NatDevice.DeletePortMap(mapping); Log.Write("server", "Remove port mapping: protocol={0}, public={1}, private={2}", mapping.Protocol, mapping.PublicPort, mapping.PrivatePort); } catch (Exception e) { Log.Write("server", "Can not remove UPnP portforwarding rules: {0}", e); Game.Settings.Server.AllowPortForward = false; } }
public virtual void DeletePortMap(Mapping mapping) { IAsyncResult result = BeginDeletePortMap(mapping, null, mapping); EndDeletePortMap(result); }
public virtual void CreatePortMap(Mapping mapping) { IAsyncResult result = BeginCreatePortMap(mapping, null, null); EndCreatePortMap(result); }
public abstract IAsyncResult BeginDeletePortMap(Mapping mapping, AsyncCallback callback, object asyncState);
async Task DeletePortMapping(INatDevice device, Mapping mapping) { var map = new Mono.Nat.Mapping( mapping.Protocol == Protocol.Tcp ? Mono.Nat.Protocol.Tcp : Mono.Nat.Protocol.Udp, mapping.PrivatePort, mapping.PublicPort ); try { await device.DeletePortMapAsync(map); } catch { } }
async Task CreateOrFailMapping(INatDevice device, Mapping mapping) { var map = new Mono.Nat.Mapping( mapping.Protocol == Protocol.Tcp ? Mono.Nat.Protocol.Tcp : Mono.Nat.Protocol.Udp, mapping.PrivatePort, mapping.PublicPort ); try { await device.CreatePortMapAsync(map); Mappings = Mappings.WithCreated(mapping); } catch { Mappings = Mappings.WithFailed(mapping); } }
public static Mapping DeletePortMap(this INatDevice device, Mapping mapping) { return(device.DeletePortMapAsync(mapping).GetAwaiter().GetResult()); }
public abstract Task CreatePortMap(Mapping mapping);