Ejemplo n.º 1
0
        public static PortMapping GetPortMapping(Form parent)
        {
            FrmAddPort addPort = new FrmAddPort();

            if (addPort.ShowDialog(parent) == DialogResult.OK)
            {
                MappingProtocol protocol = MappingProtocol.Tcp;

                if (addPort.rbUdp.Checked)
                {
                    protocol = MappingProtocol.Udp;
                }
                else if (addPort.rbTcpUdp.Checked)
                {
                    protocol = MappingProtocol.Both;
                }

                return(new PortMapping()
                {
                    Port = Convert.ToInt32(addPort.numPort.Value),
                    Protocol = protocol
                });
            }

            return(null);
        }
Ejemplo n.º 2
0
        public async Task <MappedPort> MapAsync(MappingProtocol protocol, int port, TimeSpan lifetime, CancellationToken cancel_token)
        {
            var parameters = new Dictionary <string, string>()
            {
                { "NewRemoteHost", "" },
                { "NewExternalPort", port.ToString() },
                { "NewProtocol", protocol == MappingProtocol.TCP ? "TCP" : "UDP" },
                { "NewInternalPort", port.ToString() },
                { "NewInternalClient", (await GetInternalAddressAsync().ConfigureAwait(false)).ToString() },
                { "NewEnabled", "1" },
                { "NewPortMappingDescription", PortMappingDescription },
                { "NewLeaseDuration", "0" },
            };
            var result = await SendActionAsync("AddPortMapping", parameters, cancel_token).ConfigureAwait(false);

            if (result.IsSucceeded)
            {
                if (lifetime == Timeout.InfiniteTimeSpan)
                {
                    return(new MappedPort(this, protocol, port, port, DateTime.Now + TimeSpan.FromSeconds(604800)));
                }
                else
                {
                    return(new MappedPort(this, protocol, port, port, DateTime.Now + lifetime));
                }
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 3
0
        public bool ForwardPort(MappingProtocol protocol, int port)
        {
            List <Mapping> mappingsToForward = new List <Mapping>(2);

            if (protocol.HasFlag(MappingProtocol.Tcp))
            {
                mappingsToForward.Add(new Mapping(Protocol.Tcp, port, port));
            }

            if (protocol.HasFlag(MappingProtocol.Udp))
            {
                mappingsToForward.Add(new Mapping(Protocol.Udp, port, port));
            }

            try
            {
                foreach (Mapping mapping in mappingsToForward)
                {
                    _natDevice.CreatePortMap(mapping);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 4
0
 public async Task UnmapAsync(
     MappingProtocol protocol,
     int port,
     CancellationToken cancel_token)
 {
     try {
         await MapAsyncInternal(protocol, port, 0, cancel_token).ConfigureAwait(false);
     }
     catch (PortMappingException) {
     }
 }
Ejemplo n.º 5
0
        public async Task UnmapAsync(MappingProtocol protocol, int port, CancellationToken cancel_token)
        {
            var parameters = new Dictionary <string, string>()
            {
                { "NewRemoteHost", "" },
                { "NewExternalPort", port.ToString() },
                { "NewProtocol", protocol == MappingProtocol.TCP ? "TCP" : "UDP" },
            };

            await SendActionAsync("DeletePortMapping", parameters, cancel_token).ConfigureAwait(false);
        }
Ejemplo n.º 6
0
 public Task <MappedPort> MapAsync(
     MappingProtocol protocol,
     int port,
     TimeSpan lifetime,
     CancellationToken cancel_token)
 {
     return(MapAsyncInternal(
                protocol,
                port,
                lifetime.TotalSeconds <= 0 ? 7200 : (int)lifetime.TotalSeconds,
                cancel_token));
 }
Ejemplo n.º 7
0
 public MappedPort(
     INatDevice device,
     MappingProtocol protocol,
     int internal_port,
     int external_port,
     DateTime expiration)
 {
     this.Device       = device;
     this.Protocol     = protocol;
     this.InternalPort = internal_port;
     this.ExternalPort = external_port;
     this.Expiration   = expiration;
 }
Ejemplo n.º 8
0
 public MappedPort(
     INatDevice device,
     MappingProtocol protocol,
     int internal_port,
     int external_port,
     DateTime expiration)
 {
   this.Device       = device;
   this.Protocol     = protocol;
   this.InternalPort = internal_port;
   this.ExternalPort = external_port;
   this.Expiration   = expiration;
 }
Ejemplo n.º 9
0
        public bool CheckPort(MappingProtocol protocol, string ipAddress, int port)
        {
            bool tcpPortOpen = true;
            bool udpPortOpen = true;

            if (protocol.HasFlag(MappingProtocol.Tcp))
            {
                using (TcpClient client = new TcpClient())
                {
                    try
                    {
                        client.Connect(ipAddress, port);
                        tcpPortOpen = true;
                    }
                    catch
                    {
                        tcpPortOpen = false;
                    }
                }
            }

            if (protocol.HasFlag(MappingProtocol.Udp))
            {
                using (UdpClient client = new UdpClient())
                {
                    try
                    {
                        client.Connect(ipAddress, port);
                        udpPortOpen = true;
                    }
                    catch
                    {
                        udpPortOpen = false;
                    }
                }
            }

            return(udpPortOpen && tcpPortOpen);
        }
Ejemplo n.º 10
0
 public Task UnmapAsync(MappingProtocol protocol, int port, CancellationToken cancel_token)
 {
     return(Device.UnmapAsync(protocol, port, cancel_token));
 }
Ejemplo n.º 11
0
 public Task MapAsync(MappingProtocol protocol, int port, TimeSpan lifetime, CancellationToken cancel_token)
 {
     return(Device.MapAsync(protocol, port, lifetime, cancel_token));
 }
Ejemplo n.º 12
0
    private async Task<MappedPort> MapAsyncInternal(
        MappingProtocol protocol,
        int port,
        int lifetime,
        CancellationToken cancel_token)
    {
      int tries = 1;
    retry:
      cancel_token.ThrowIfCancellationRequested();
      using (var client = new UdpClient()) {
        var cancel_source = CancellationTokenSource.CreateLinkedTokenSource(
          new CancellationTokenSource(250*tries).Token,
          cancel_token);
        var cancel = cancel_source.Token;
        cancel.Register(() => client.Close(), false);
        try {
          var bytes = new byte[12];
          BinaryAccessor.PutByte(bytes, 0, PMPVersion);
          switch (protocol) {
          case MappingProtocol.TCP:
            BinaryAccessor.PutByte(bytes, 1, PMPOpMapTcp);
            break;
          case MappingProtocol.UDP:
            BinaryAccessor.PutByte(bytes, 1, PMPOpMapUdp);
            break;
          }
          BinaryAccessor.PutUInt16BE(bytes, 2, 0);
          BinaryAccessor.PutUInt16BE(bytes, 4, port);
          BinaryAccessor.PutUInt16BE(bytes, 6, port);
          BinaryAccessor.PutUInt32BE(bytes, 8, lifetime);

          await client.SendAsync(bytes, bytes.Length, new IPEndPoint(this.DeviceAddress, PMPPort));
          var msg = await client.ReceiveAsync();
          if (!msg.RemoteEndPoint.Address.Equals(this.DeviceAddress) || msg.Buffer.Length<16) {
            if (tries++<PMPTries) goto retry;
            throw new PortMappingException();
          }
          var ver    = BinaryAccessor.GetByte(msg.Buffer, 0);
          var opcode = BinaryAccessor.GetByte(msg.Buffer, 1);
          var err    = BinaryAccessor.GetUInt16BE(msg.Buffer, 2);
          var time   = BinaryAccessor.GetUInt32BE(msg.Buffer, 4);
          var internal_port = BinaryAccessor.GetUInt16BE(msg.Buffer, 8);
          var external_port = BinaryAccessor.GetUInt16BE(msg.Buffer, 10);
          var mapped_lifetime = BinaryAccessor.GetUInt32BE(msg.Buffer, 12);
          if (ver!=PMPVersion) {
            if (tries++<PMPTries) goto retry;
            throw new PortMappingException();
          }
          switch (protocol) {
          case MappingProtocol.TCP:
            if (opcode!=PMPOpResultMapTcp) {
              if (tries++<PMPTries) goto retry;
              throw new PortMappingException();
            }
            break;
          case MappingProtocol.UDP:
            if (opcode!=PMPOpResultMapUdp) {
              if (tries++<PMPTries) goto retry;
              throw new PortMappingException();
            }
            break;
          }
          if (err!=0) {
            if (tries++<PMPTries) goto retry;
            throw new PortMappingException();
          }
          this.LastTimestamp = time;
          return new MappedPort(
            this,
            protocol,
            internal_port,
            external_port,
            DateTime.Now.AddSeconds(mapped_lifetime));
        }
        catch (SocketException) { }
        catch (ObjectDisposedException) { }
        if (tries++<PMPTries) goto retry;
        throw new PortMappingException();
      }
    }
Ejemplo n.º 13
0
 public async Task UnmapAsync(MappingProtocol protocol, int port, CancellationToken cancel_token)
 {
   var parameters = new Dictionary<string,string>() {
     { "NewRemoteHost",   "" },
     { "NewExternalPort", port.ToString() },
     { "NewProtocol",     protocol==MappingProtocol.TCP ? "TCP" : "UDP" },
   };
   await SendActionAsync("DeletePortMapping", parameters, cancel_token);
 }
Ejemplo n.º 14
0
 public async Task<MappedPort> MapAsync(MappingProtocol protocol, int port, TimeSpan lifetime, CancellationToken cancel_token)
 {
   var parameters = new Dictionary<string,string>() {
     { "NewRemoteHost",     "" },
     { "NewExternalPort",   port.ToString() },
     { "NewProtocol",       protocol==MappingProtocol.TCP ? "TCP" : "UDP" },
     { "NewInternalPort",   port.ToString() },
     { "NewInternalClient", (await GetInternalAddressAsync()).ToString() },
     { "NewEnabled",        "1" },
     { "NewPortMappingDescription", PortMappingDescription },
     { "NewLeaseDuration",  "0" },
   };
   var result = await SendActionAsync("AddPortMapping", parameters, cancel_token);
   if (result.IsSucceeded) {
     if (lifetime==Timeout.InfiniteTimeSpan) {
       return new MappedPort(this, protocol, port, port, DateTime.Now+TimeSpan.FromSeconds(604800));
     }
     else {
       return new MappedPort(this, protocol, port, port, DateTime.Now+lifetime);
     }
   }
   else {
     return null;
   }
 }
Ejemplo n.º 15
0
 public Task<MappedPort> MapAsync(
     MappingProtocol protocol,
     int port,
     TimeSpan lifetime,
     CancellationToken cancel_token)
 {
   return MapAsyncInternal(
     protocol,
     port,
     lifetime.TotalSeconds<=0 ? 7200 : (int)lifetime.TotalSeconds,
     cancel_token);
 }
Ejemplo n.º 16
0
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void RefreshThread()
        {
            lock(multiThreadLock)
            {
                IncreaseWorkCount();

                mappingProtocol = MappingProtocol.None;
                externalIPAddress = null;

                lock (portMappings)
                {
                    for (int i = 0; i < portMappings.Count; i++)
                    {
                        PortMapping pm = (PortMapping)portMappings[i];
                        if (pm.MappingStatus == PortMappingStatus.Mapped)
                        {
                            pm.SetMappingStatus(PortMappingStatus.Unmapped);
                        }
                    }
                }

                OnWillStartSearchForRouter();

                DebugLog.WriteLine("RefreshThread");

                // Update all the following variables:
                // - routerIPAddress
                // - routerManufacturer
                // - localIPAddress
                // - localIPAddressOnSubnet
                //
                // Note: The order in which we call the following methods matters.
                // We must update the routerIPAddress before the others.
                UpdateRouterIPAddress();
                UpdateRouterManufacturer();
                UpdateLocalIPAddress();

                DebugLog.WriteLine("routerIPAddress       : {0}", routerIPAddress);
                DebugLog.WriteLine("routerManufacturer    : {0}", routerManufacturer);
                DebugLog.WriteLine("localIPAddress        : {0}", localIPAddress);
                DebugLog.WriteLine("localIPAddressOnSubnet: {0}", localIPOnRouterSubnet);

                if (routerIPAddress != null)
                {
                    if ((localIPAddress != null) && localIPOnRouterSubnet)
                    {
                        externalIPAddress = null;

                        if (IsIPv4AddressInPrivateSubnet(routerIPAddress))
                        {
                            natpmpStatus = MappingStatus.Trying;
                            upnpStatus = MappingStatus.Trying;

                            natpmpPortMapper.Refresh();
                            upnpPortMapper.Refresh();
                        }
                        else
                        {
                            natpmpStatus = MappingStatus.Failed;
                            upnpStatus = MappingStatus.Failed;
                            externalIPAddress = localIPAddress;
                            mappingProtocol = MappingProtocol.None;

                            // Set all mappings to be mapped with their local port number being the external one
                            lock (portMappings)
                            {
                                for (int i = 0; i < portMappings.Count; i++)
                                {
                                    PortMapping pm = (PortMapping)portMappings[i];
                                    pm.SetExternalPort(pm.LocalPort);
                                    pm.SetMappingStatus(PortMappingStatus.Mapped);
                                }
                            }

                            OnDidFinishSearchForRouter();
                        }
                    }
                    else
                    {
                        OnDidFinishSearchForRouter();
                    }
                }
                else
                {
                    OnDidFinishSearchForRouter();
                }

                // If we call DecreaseWorkCount right now, then it will likely result in a call to DidFinishWork.
                // This is because we the background threads that get called likely haven't started yet.
                // Therefore we delay this call, so as to allow the background threads to start first.
                new Timer(new TimerCallback(DecreaseWorkCount), null, (1 * 1000), Timeout.Infinite);
            }
        }
Ejemplo n.º 17
0
        private void natpmpPortMapper_DidGetExternalIPAddress(NATPMPPortMapper sender, System.Net.IPAddress ip)
        {
            bool shouldNotify = false;

            if (natpmpStatus == MappingStatus.Trying)
            {
                natpmpStatus = MappingStatus.Works;
                mappingProtocol = MappingProtocol.NATPMP;
                shouldNotify = true;
            }

            externalIPAddress = ip;
            OnExternalIPAddressDidChange();

            if (shouldNotify)
            {
                OnDidFinishSearchForRouter();
            }
        }
Ejemplo n.º 18
0
        private void upnpPortMapper_DidGetExternalIPAddress(UPnPPortMapper sender, IPAddress ip)
        {
            DebugLog.WriteLine("upnpPortMapper_DidGetExternalIPAddress: {0}", ip);

            bool shouldNotify = false;

            if (upnpStatus == MappingStatus.Trying)
            {
                upnpStatus = MappingStatus.Works;
                mappingProtocol = MappingProtocol.UPnP;
                shouldNotify = true;
            }

            externalIPAddress = ip;
            OnExternalIPAddressDidChange();

            if (shouldNotify)
            {
                OnDidFinishSearchForRouter();
            }
        }
 public Task UnmapAsync(MappingProtocol protocol, int port, CancellationToken cancel_token)
 {
   return Device.UnmapAsync(protocol, port, cancel_token);
 }
 public Task MapAsync(MappingProtocol protocol, int port, TimeSpan lifetime, CancellationToken cancel_token)
 {
   return Device.MapAsync(protocol, port, lifetime, cancel_token);
 }
Ejemplo n.º 21
0
        private async Task <MappedPort> MapAsyncInternal(
            MappingProtocol protocol,
            int port,
            int lifetime,
            CancellationToken cancel_token)
        {
            int tries = 1;

retry:
            cancel_token.ThrowIfCancellationRequested();
            using (var client = new UdpClient())
                using (var cancel_source = CancellationTokenSource.CreateLinkedTokenSource(cancel_token))
                    using (cancel_source.Token.Register(() => client.Close(), false)) {
                        cancel_source.CancelAfter(250 * tries);
                        try {
                            var bytes = new byte[12];
                            BinaryAccessor.PutByte(bytes, 0, PMPVersion);
                            switch (protocol)
                            {
                            case MappingProtocol.TCP:
                                BinaryAccessor.PutByte(bytes, 1, PMPOpMapTcp);
                                break;

                            case MappingProtocol.UDP:
                                BinaryAccessor.PutByte(bytes, 1, PMPOpMapUdp);
                                break;
                            }
                            BinaryAccessor.PutUInt16BE(bytes, 2, 0);
                            BinaryAccessor.PutUInt16BE(bytes, 4, port);
                            BinaryAccessor.PutUInt16BE(bytes, 6, port);
                            BinaryAccessor.PutUInt32BE(bytes, 8, lifetime);

                            await client.SendAsync(bytes, bytes.Length, new IPEndPoint(this.DeviceAddress, PMPPort)).ConfigureAwait(false);

                            var msg = await client.ReceiveAsync().ConfigureAwait(false);

                            if (!msg.RemoteEndPoint.Address.Equals(this.DeviceAddress) || msg.Buffer.Length < 16)
                            {
                                if (tries++ < PMPTries)
                                {
                                    goto retry;
                                }
                                throw new PortMappingException();
                            }
                            var ver             = BinaryAccessor.GetByte(msg.Buffer, 0);
                            var opcode          = BinaryAccessor.GetByte(msg.Buffer, 1);
                            var err             = BinaryAccessor.GetUInt16BE(msg.Buffer, 2);
                            var time            = BinaryAccessor.GetUInt32BE(msg.Buffer, 4);
                            var internal_port   = BinaryAccessor.GetUInt16BE(msg.Buffer, 8);
                            var external_port   = BinaryAccessor.GetUInt16BE(msg.Buffer, 10);
                            var mapped_lifetime = BinaryAccessor.GetUInt32BE(msg.Buffer, 12);
                            if (ver != PMPVersion)
                            {
                                if (tries++ < PMPTries)
                                {
                                    goto retry;
                                }
                                throw new PortMappingException();
                            }
                            switch (protocol)
                            {
                            case MappingProtocol.TCP:
                                if (opcode != PMPOpResultMapTcp)
                                {
                                    if (tries++ < PMPTries)
                                    {
                                        goto retry;
                                    }
                                    throw new PortMappingException();
                                }
                                break;

                            case MappingProtocol.UDP:
                                if (opcode != PMPOpResultMapUdp)
                                {
                                    if (tries++ < PMPTries)
                                    {
                                        goto retry;
                                    }
                                    throw new PortMappingException();
                                }
                                break;
                            }
                            if (err != 0)
                            {
                                if (tries++ < PMPTries)
                                {
                                    goto retry;
                                }
                                throw new PortMappingException();
                            }
                            this.LastTimestamp = time;
                            return(new MappedPort(
                                       this,
                                       protocol,
                                       internal_port,
                                       external_port,
                                       DateTime.Now.AddSeconds(mapped_lifetime)));
                        }
                        catch (SocketException) { }
                        catch (ObjectDisposedException) { }
                        if (tries++ < PMPTries)
                        {
                            goto retry;
                        }
                        throw new PortMappingException();
                    }
        }
Ejemplo n.º 22
0
 public async Task UnmapAsync(
     MappingProtocol protocol,
     int port,
     CancellationToken cancel_token)
 {
   try {
     await MapAsyncInternal(protocol, port, 0, cancel_token);
   }
   catch (PortMappingException) {
   }
 }