Exemplo n.º 1
0
 void initUPnP()
 {
     for (int i = 0; i < 5; i++)
     {
         try
         {
             NatUtility.Initialize();
             NatUtility.DeviceFound += deviceFound;
             NatUtility.StartDiscovery();
             upnpSem.WaitOne();
             NatUtility.StopDiscovery();
             break;
         }
         catch (Exception e)
         {
             System.Threading.Thread.Sleep(1000);
             if (i < 5)
             {
                 SystemLog.addEntry("Failed to boot up UPnP. Exception: " + e.Message + ". Trying again...");
             }
             else
             {
                 SystemLog.addEntry("Giving up on UPnP and running a STUN instead...");
                 UPnPActive = false;
                 return;
             }
         }
     }
 }
Exemplo n.º 2
0
        private void DisposeNat()
        {
            _logger.Debug("Stopping NAT discovery");

            if (_timer != null)
            {
                _timer.Dispose();
                _timer = null;
            }

            try
            {
                // This is not a significant improvement
                NatUtility.StopDiscovery();
                NatUtility.DeviceFound        -= NatUtility_DeviceFound;
                NatUtility.DeviceLost         -= NatUtility_DeviceLost;
                NatUtility.UnhandledException -= NatUtility_UnhandledException;
            }
            // Statements in try-block will no fail because StopDiscovery is a one-line
            // method that was no chances to fail.
            //		public static void StopDiscovery ()
            //      {
            //          searching.Reset();
            //      }
            // IMO you could remove the catch-block
            catch (Exception ex)
            {
                _logger.ErrorException("Error stopping NAT Discovery", ex);
            }
            finally
            {
                _isStarted = false;
            }
        }
Exemplo n.º 3
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            try
            {
                INatDevice device = args.Device;

                logger.Fatal("UPNP Enabled Device found");
                logger.Info("Type: {0}", device.GetType().Name);
                logger.Info("External IP: {0}", device.GetExternalIP());

                Mapping mapping = new Mapping(Protocol.Udp, Convert.ToInt32(uxServerPortUdp.Text), Convert.ToInt32(uxServerPortUdp.Text));
                device.CreatePortMap(mapping);
                logger.Info("Create Mapping: protocol={0}, public={1}, private={2}", mapping.Protocol, mapping.PublicPort, mapping.PrivatePort);
                try
                {
                    Mapping m = device.GetSpecificMapping(Protocol.Udp, Convert.ToInt32(uxServerPortUdp.Text));
                    logger.Info("Testing port Mapping passed: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort);
                    // Se il portfoward funziona interrompiamo il discovery
                    // NOTA: rileviamo solo il primo router della lista
                    NatUtility.StopDiscovery();
                }
                catch
                {
                    logger.Fatal("Could not get specific mapping");
                }
            }
            catch (Exception ex)
            {
                logger.Fatal(ex.Message);
                logger.Fatal(ex.StackTrace);
            }
        }
Exemplo n.º 4
0
        private void DisposeNat()
        {
            _logger.Debug("Stopping NAT discovery");

            if (_timer != null)
            {
                _timer.Dispose();
                _timer = null;
            }

            _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered;

            try
            {
                NatUtility.StopDiscovery();
                NatUtility.DeviceFound -= NatUtility_DeviceFound;
                NatUtility.DeviceLost  -= NatUtility_DeviceLost;
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error stopping NAT Discovery", ex);
            }
            finally
            {
                _isStarted = false;
            }
        }
Exemplo n.º 5
0
        public void StopDiscovery()
        {
            NatUtility.StopDiscovery();

            NatUtility.DeviceLost  -= NatUtilityOnDeviceLost;
            NatUtility.DeviceFound -= NatUtilityOnDeviceFound;
        }
Exemplo n.º 6
0
        public void Stop()
        {
            if (!running)
            {
                return;
            }

            running = false;
            logger.Info("UPnP shutting down");
            NatUtility.StopDiscovery();

            lock (devices)
                foreach (INatDevice device in devices)
                {
                    try
                    {
                        device.DeletePortMap(tcpMapping);
                        logger.Info("UPnP port map removal successful {0}", tcpMapping);
                        device.DeletePortMap(udpMapping);
                        logger.Info("UPnP port map removal successful {0}", udpMapping);
                    }
                    catch (MappingException e)
                    {
                        logger.Error("UPnP failed to remove map. Error: {0}", e);
                    }
                }

            logger.Info("UPnP shut down");
        }
Exemplo n.º 7
0
    void OnApplicationQuit()
    {
        if (natDevice != null)
        {
            try
            {
                if (udpMapping != null)
                {
                    natDevice.DeletePortMap(udpMapping);
                }
                if (tcpMapping != null)
                {
                    natDevice.DeletePortMap(tcpMapping);
                }
                tcpMapping = udpMapping = null;
                Debug.Log("Deleted port mapping");
            }
            catch (Exception ex)
            {
                Debug.Log("Failed to delete port mapping");
            }
        }
        NatUtility.StopDiscovery();

        CloseServer();

        natDevice = null;
    }
Exemplo n.º 8
0
 public void Dispose()
 {
     NatUtility.StopDiscovery();
     NatUtility.DeviceFound -= DeviceFound;
     NatUtility.DeviceLost  -= DeviceLost;
     ShouldMapNatDevices     = false;
 }
Exemplo n.º 9
0
        public async Task StopAsync(bool removeExisting, CancellationToken token)
        {
            using (await Locker.EnterAsync()) {
                NatUtility.StopDiscovery();

                var created = Mappings.Created;
                Mappings = Mappings.WithAllPending();
                try {
                    if (removeExisting)
                    {
                        foreach (var mapping in created)
                        {
                            foreach (var device in Devices)
                            {
                                token.ThrowIfCancellationRequested();
                                await DeletePortMapping(device, mapping);
                            }
                        }
                    }
                } finally {
                    Devices = new List <INatDevice> ();
                    RaiseMappingsChangedAsync();
                }
            }
        }
Exemplo n.º 10
0
 public void StopScan()
 {
     if (running)
     {
         NatUtility.StopDiscovery();
         running = false;
     }
 }
Exemplo n.º 11
0
 void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
 {
     try
     {
         e.Device.CreatePortMap(new Mapping(Protocol.Tcp, SettingsManager.IncomingPort, SettingsManager.IncomingPort));
         NatUtility.StopDiscovery();
     }
     catch { }
 }
        private void Stop()
        {
            _logger.LogInformation("Stopping NAT discovery");

            NatUtility.StopDiscovery();
            NatUtility.DeviceFound -= OnNatUtilityDeviceFound;

            _timer?.Dispose();
        }
Exemplo n.º 13
0
 public void upnp_stopDiscovery()
 {
     if (upnp_discovery_started)
     {
         xbs_messages.addDebugMessage(" @ UPnP device discovery stopped", xbs_message_sender.UPNP);
         NatUtility.StopDiscovery();
         upnp_discovery_started = false;
     }
 }
Exemplo n.º 14
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            _device = args.Device;
            NatUtility.StopDiscovery();

            if (_port > 0)
            {
                CreatePortMap(_port);
            }
        }
Exemplo n.º 15
0
 public void Search()
 {
     NatUtility.DeviceFound += DeviceFound;
     NatUtility.StartDiscovery();
     while (true)
     {
         Thread.Sleep(500000);
         NatUtility.StopDiscovery();
         NatUtility.StartDiscovery();
     }
 }
Exemplo n.º 16
0
 public void StopScan()
 {
     if (_stopTimer != null)
     {
         _stopTimer.Enabled  = false;
         _stopTimer.Elapsed -= StopTimerOnElapsed;
         _stopTimer.Dispose();
     }
     NatUtility.StopDiscovery();
     NatUtility.UnknownDeviceFound -= UnknownDeviceFound;
 }
Exemplo n.º 17
0
        private void Stop()
        {
            _logger.LogDebug("Stopping NAT discovery");

            NatUtility.StopDiscovery();
            NatUtility.DeviceFound -= OnNatUtilityDeviceFound;

            _timer?.Dispose();

            _deviceDiscovery.DeviceDiscovered -= OnDeviceDiscoveryDeviceDiscovered;
        }
Exemplo n.º 18
0
        // Nat device

        private async Task ScanNatDevices(int scanDuration)
        {
            // Enable nat device discovery for a while.
            scanButton.Enabled = false;
            scanButton.Text    = "Scanning...";
            NatUtility.StartDiscovery();
            await Task.Delay(scanDuration);

            NatUtility.StopDiscovery();
            scanButton.Text    = "Scan";
            scanButton.Enabled = true;
        }
Exemplo n.º 19
0
 public static void RemovePort()
 {
     foreach (var device in Devices)
     {
         if (device.GetSpecificMapping(Protocol.Tcp, Port).PublicPort > 0) // if port map exists
         {
             device.DeletePortMap(new Mapping(Protocol.Tcp, Port, Port));
         }
     }
     IsPortForwarded = false;
     NatUtility.StopDiscovery();
 }
Exemplo n.º 20
0
 public static void InitializePortMappingEnvironment(TimeSpan timeout)
 {
     if (!_delegatesAdded)
     {
         NatUtility.DeviceFound += DeviceFoundHandler;
         NatUtility.DeviceLost  += DeviceLostHandler;
         _delegatesAdded         = true;
     }
     NatUtility.StartDiscovery();
     Thread.Sleep(timeout);
     NatUtility.StopDiscovery();
 }
Exemplo n.º 21
0
        public static void StoppingNatDiscovery()
        {
            Log.Write("server", "Stopping NAT discovery.");
            NatUtility.StopDiscovery();

            if (NatDevice == null || NatDevice.GetType() != typeof(Mono.Nat.Upnp.UpnpNatDevice))
            {
                Log.Write("server", "No NAT devices with UPnP enabled found within {0} ms deadline. Disabling automatic port forwarding.".F(Game.Settings.Server.NatDiscoveryTimeout));
                Game.Settings.Server.NatDeviceAvailable = false;
                Game.Settings.Server.AllowPortForward   = false;
            }
        }
        public void CreatePortMapping()
        {
            NatUtility.DeviceFound += DeviceFound;

            fLogger.WriteInfo("NAT Discovery started");
            NatUtility.StartDiscovery();

            fUPnPSem.WaitOne();

            fLogger.WriteInfo("NAT Discovery stopped");
            NatUtility.StopDiscovery();
        }
Exemplo n.º 23
0
        /// <summary>
        ///     Sets up the port forwarding in the background.
        /// </summary>
        private void SetupPortForwardingAsync()
        {
            NatUtility.DeviceFound += (sender, router) =>
            {
                NatUtility.StopDiscovery();
                _uPnpRouter = router.Device;
                Logger.InfoFormat("{0} is creating UPnP external port {1} forwarding on the discovered router.",
                                  DeviceDisplayNameInternal, _portNumber);
                _uPnpRouter.CreatePortMap(new Mapping(Protocol.Tcp, _portNumber, _portNumber));
            };

            NatUtility.StartDiscovery();
        }
Exemplo n.º 24
0
 public void Stop()
 {
     if (server != null)
     {
         if (AutoMapPort)
         {
             NatUtility.StopDiscovery();
             NatUtility.DeviceFound -= HandleNatUtilityDeviceFound;
             // NatUtility.UnhandledException -= HandleNatUtilityUnhandledException;
             // NatUtility.DeviceLost -= HandleDeviceLost;
         }
         server.Shutdown("Server shutdown by host");
     }
 }
Exemplo n.º 25
0
        private static void DeviceFound(object sender, DeviceEventArgs args)
        {
            _device = args.Device;

            NatUtility.StopDiscovery();

            _discoveryComplete = true;

            if (_port > 0)
            {
                int outPort;
                CreatePortMap(_port, out outPort);
            }
        }
Exemplo n.º 26
0
        public NatTest()
        {
            NatUtility.DeviceFound += DeviceFound;
            NatUtility.DeviceLost  += DeviceLost;

            NatUtility.StartDiscovery();

            Console.WriteLine("Discovery started");

            while (true)
            {
                Thread.Sleep(500000);
                NatUtility.StopDiscovery();
                NatUtility.StartDiscovery();
            }
        }
 //ellenőrzés
 public async void upnp_ell(Vezerlofo vzf)
 {
     write_file("MCSC: Portok létrehozásának eredményének ellenőrzése", vzf);
     try
     {
         device.DeletePortMap(new Mapping(Protocol.Udp, 2, 2));
         write_file("MCSC: Portok sikeresen létrehozva", vzf);
     }
     catch
     {
         write_file("MCSC-ERROR: PORTOK LÉTREHOZÁSA LEHETETLEN", vzf);
         MessageBox.Show("Sajnos neked nem elérhető az automatikus port létrehozás");
         NatUtility.StopDiscovery();
         err = true;
     }
 }
Exemplo n.º 28
0
        public override async Task MapAsync()
        {
            NatUtility.DeviceFound += DeviceFound;

            try
            {
                await Task.Run(() => NatUtility.StartDiscovery(),
                               new CancellationTokenSource(TimeSpan.FromSeconds(5)).Token
                               );
            }
            catch (TaskCanceledException)
            {
            }
            finally
            {
                NatUtility.StopDiscovery();
            }
        }
Exemplo n.º 29
0
        public NatTest()
        {
            // Raised whenever a device is discovered.
            NatUtility.DeviceFound += DeviceFound;

            // If you know the gateway address, you can directly search for a device at that IP
            //NatUtility.Search (System.Net.IPAddress.Parse ("192.168.0.1"), NatProtocol.Pmp);
            //NatUtility.Search (System.Net.IPAddress.Parse ("192.168.0.1"), NatProtocol.Upnp);
            NatUtility.StartDiscovery();

            Console.WriteLine("Discovery started");

            while (true)
            {
                Thread.Sleep(500000);
                NatUtility.StopDiscovery();
                NatUtility.StartDiscovery();
            }
        }
Exemplo n.º 30
0
        private void DisposeNat()
        {
            _logger.Debug("Stopping NAT discovery");

            try
            {
                NatUtility.DeviceFound        -= NatUtility_DeviceFound;
                NatUtility.DeviceLost         -= NatUtility_DeviceLost;
                NatUtility.UnhandledException -= NatUtility_UnhandledException;
                NatUtility.StopDiscovery();
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error stopping NAT Discovery", ex);
            }
            finally
            {
                _isStarted = false;
            }
        }