Ejemplo n.º 1
0
#pragma warning restore 4014

        private static async Task ForwardPortInternalAsync(ushort port, int milisecondsDelay, NetworkProtocolType networkProtocolType = NetworkProtocolType.Udp)
        {
            try
            {
                if (LastForwardedPort == port || UpnpFailed)
                {
                    return;
                }
                if (LastForwardedPort != 0)
                {
                    NatDiscoverer.ReleaseAll();
                }
                NatDiscoverer discoverer = new NatDiscoverer();
                NatDevice     device;
                using (CancellationTokenSource cts = new CancellationTokenSource(milisecondsDelay))
                {
                    device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp | PortMapper.Pmp, cts).ConfigureAwait(false);
                }

                ExternalIp = await device.GetExternalIPAsync();

                await device.CreatePortMapAsync(new Mapping(networkProtocolType, IPAddress.None, port, port, 0, ApplicationName)).ConfigureAwait(false);

                LastForwardedPort = port;
                Debug.Log($"Port {port.ToString()} forwarded successfully!");
            }
            catch (Exception ex)
            {
                //Debug.LogWarning($"UPnP failed!\n{ex.Message}\n{ex.StackTrace}");
                UpnpFailed = true;
            }
        }
#pragma warning restore 4014

        private static async Task ForwardPortInternalAsync(ushort port, int milisecondsDelay, NetworkProtocolType networkProtocolType = NetworkProtocolType.Udp)
        {
            try
            {
                if (LastForwardedPort == port || UpnpFailed)
                {
                    return;
                }
                if (LastForwardedPort != 0)
                {
                    NatDiscoverer.ReleaseAll();
                }
                NatDiscoverer discoverer = new NatDiscoverer();
                NatDevice     device;
                using (CancellationTokenSource cts = new CancellationTokenSource(milisecondsDelay))
                {
                    device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp | PortMapper.Pmp, cts).ConfigureAwait(false);
                }

                await device.CreatePortMapAsync(new Mapping(networkProtocolType, port, port, "LiteNetLib4Mirror UPnP")).ConfigureAwait(false);

                LastForwardedPort = port;
                Debug.Log("Port forwarded successfully!");
            }
            catch
            {
                Debug.LogWarning("UPnP failed!");
                UpnpFailed = true;
            }
        }
Ejemplo n.º 3
0
    private void Disconnect()
    {
        if (isHost)
        {
            server?.Stop();
        }
        else if (client != null && client.Connected)
        {
            // Write disconnect to socket
            try {
                SendMessage(new Message(MessageType.Disconnect));
            } catch (Exception e) {
                Debug.LogWarning($"Failed to write to socket with error:\n{e}");
            }
        }

        stream?.Close();
        client?.Close();

        NatDiscoverer.ReleaseAll();

        lobby?.DisconnectRecieved();

        Debug.Log($"Disconnected.");
    }
        private bool ExecuteCommand(string message)
        {
            var command = message.Remove(0, 1).ToLower();

            message = message.Remove(0, 1);

            if (command.StartsWith("stop"))
            {
                Program.LastRunTime = DateTime.UtcNow;
                Stop();
                NatDiscoverer.ReleaseAll();

                Console.WriteLine();
                Console.WriteLine("Stopped the server. Press any key to continue...");
                Console.ReadKey();
            }

            else if (command.StartsWith("clear"))
            {
                Console.Clear();
            }

            else
            {
                return(Server.Services.GetService <CommandManagerService>()?.ExecuteServerCommand(message) == true);
            }

            return(true);
        }
 private void OnDestroy()
 {
     LiteNetLib4MirrorCore.StopTransport();
     if (LiteNetLib4MirrorUtils.LastForwardedPort != 0)
     {
         NatDiscoverer.ReleaseAll();
         LiteNetLib4MirrorUtils.LastForwardedPort = 0;
     }
 }
Ejemplo n.º 6
0
        private void Stop()
        {
            UpdateToken?.Cancel();
            Server?.Stop();

            if (NATForwardingEnabled)
            {
                NatDiscoverer.ReleaseAll();
            }
        }
Ejemplo n.º 7
0
 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     try
     {
         Program.WebSocketApi?.Disconnect();
         NatDiscoverer.ReleaseAll();
     }
     catch
     {
         //
     }
 }
Ejemplo n.º 8
0
        private async Task ForwardPortTask(Protocol protocol = Protocol.Udp)
        {
            // delete previous port mappings
            NatDiscoverer.ReleaseAll();

            startTime = Time.time;
            for (int i = 0; i < 10 && !Found; i++)
            {
                await ForwardPort(this.internalPort, this.externalPort, 150, protocol);

                await Task.Delay(60);
            }
        }
Ejemplo n.º 9
0
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var pname = Process.GetProcessesByName("spartan");

            if (pname.Length > 0 && !_forceClose)
            {
                SkinHelper.ShowMessage(@"You need to close the game first!");
                e.Cancel = true;
                return;
            }
            _timer.Stop();
            Program.WebSocketClient.AgentWebSocket.Close();
            NatDiscoverer.ReleaseAll();
        }
Ejemplo n.º 10
0
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var pname = Process.GetProcessesByName("spartan");

            if (pname.Length > 0 && !_forceClose)
            {
                SkinHelper.ShowMessage(MultiLanguage.GetString("strCloseGameFirst"));
                e.Cancel = true;
                return;
            }
            _timer.Stop();
            Program.WebSocketClient.AgentWebSocket.Close();
            NatDiscoverer.ReleaseAll();
        }
Ejemplo n.º 11
0
    private void Disconnect()
    {
        if (isHost)
        {
            server?.Stop();
        }
        else if (client != null && client.Connected)
        {
            SendMessage(new Message(MessageType.Disconnect));
        }

        stream?.Close();
        client?.Close();

        NatDiscoverer.ReleaseAll();

        lobby?.DisconnectRecieved();

        Debug.Log($"Disconnected.");
    }
Ejemplo n.º 12
0
 private void OnApplicationQuit()
 {
     NatDiscoverer.ReleaseAll();
 }
Ejemplo n.º 13
0
        public static async Task <int> MapPortTask(int privatePort, int publicPort)
        {
            var logFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OpenNat.log");

            try
            {
                if (!NatDiscoverer.TraceSource.Listeners.Contains(TextWriterTraceListener))
                {
                    NatDiscoverer.TraceSource.Listeners.Remove(TextWriterTraceListener);
                }

                TextWriterTraceListener.Close();

                if (File.Exists(logFile))
                {
                    File.Delete(logFile);
                }
            }
            catch
            {
                // ignored
            }
            NatDiscoverer.ReleaseAll();

            NatDiscoverer.TraceSource.Switch.Level = SourceLevels.All;

            if (TextWriterTraceListener == null)
            {
                TextWriterTraceListener = new TextWriterTraceListener(logFile, "OpenNatTxtLog");
            }

            if (!NatDiscoverer.TraceSource.Listeners.Contains(TextWriterTraceListener))
            {
                NatDiscoverer.TraceSource.Listeners.Add(TextWriterTraceListener);
            }

            var nat = new NatDiscoverer();

            var cts    = new CancellationTokenSource(30 * 1000); //30 Sec
            var device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts);

            var externalIp = await device.GetExternalIPAsync();

            var allMappings = await device.GetAllMappingsAsync();

            var localIp = Dns.GetHostEntry(Dns.GetHostName()).AddressList
                          .FirstOrDefault(key => key.AddressFamily == AddressFamily.InterNetwork);

            var enumerable = allMappings as Mapping[] ?? allMappings.ToArray();

            if (enumerable.Any(key => //Equals(key.PrivateIP, localIp) && key.Description == "AOEO Project Celeste"
                               key.PublicPort == 1000))
            {
                var r = enumerable.FirstOrDefault(
                    key => //Equals(key.PrivateIP, localIp) && key.Description == "AOEO Project Celeste"
                    key.PublicPort == 1000);

                if (r != null)
                {
                    await device.DeletePortMapAsync(r);
                }
            }

            //var rnd = new Random(DateTime.UtcNow.Millisecond);
            var newPublicPort = publicPort;
            //while (enumerable.Any(key => key.PublicPort == newPublicPort))
            //    newPublicPort = rnd.Next(1000, ushort.MaxValue);

            await device.CreatePortMapAsync(new Mapping(Protocol.Udp, privatePort, newPublicPort, int.MaxValue,
                                                        "AOEO Project Celeste"));

            allMappings = await device.GetAllMappingsAsync();

            enumerable = allMappings as Mapping[] ?? allMappings.ToArray();

            var sb = new StringBuilder();

            sb.AppendFormat(
                "\n+------+-------------------------------+--------------------------------+------------------------------------+-------------------------+");
            sb.AppendFormat(
                "\n| PROT | PUBLIC (Reacheable)		   | PRIVATE (Your computer)		| Description						|						 |");
            sb.AppendFormat(
                "\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            sb.AppendFormat("\n|	  | IP Address		   | Port   | IP Address			| Port   |									| Expires				 |");
            sb.AppendFormat(
                "\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            foreach (var mapping in enumerable)
            {
                sb.AppendFormat("\n|  {5} | {0,-20} | {1,6} | {2,-21} | {3,6} | {4,-35}|{6,25}|",
                                externalIp, mapping.PublicPort, mapping.PrivateIP, mapping.PrivatePort, mapping.Description,
                                mapping.Protocol == Protocol.Tcp ? "TCP" : "UDP", mapping.Expiration.ToLocalTime());
            }
            sb.AppendFormat(
                "\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");

            NatDiscoverer.TraceSource.TraceInformation(sb.ToString());

            if (enumerable.Any(key => Equals(key.PrivateIP, localIp) &&
                               key.PublicPort == newPublicPort &&
                               key.PrivatePort == privatePort && key.Description == "AOEO Project Celeste"))
            {
                return(newPublicPort);
            }

            throw new Exception("Port mapping fail!");
        }