public ConnectionEventInfo(ConnectionBase sourceConn, HostProtocolSupport protocolSupport)
        {
            this.Source = sourceConn;
            this.Event  = ConnectionEvents.ProtocolSupport;

            this.State = HTTPConnectionStates.Initial;

            this.ProtocolSupport = protocolSupport;
        }
        public ConnectionEventInfo(ConnectionBase sourceConn, ConnectionEvents @event)
        {
            this.Source = sourceConn;
            this.Event  = @event;

            this.State = HTTPConnectionStates.Initial;

            this.ProtocolSupport = HostProtocolSupport.Unknown;
        }
예제 #3
0
 //
 // This is the callback delegate that will be invoked when a connection
 // changes state from connected to disconnected (and vice versa)
 //
 static void NotifyConnectionState(Object src, ConnectionEvents cev)
 {
     Console.WriteLine("Connection Status: " + cev.GetState.ToString() +
                       " (Souce:" + cev.GetSource +
                       " Destination:" + cev.GetDestination +
                       " Relay1:" + cev.GetRelay1 +
                       " Relay2:" + cev.GetRelay2 +
                       " ID:" + cev.GetConnectionID +
                       ")");
 }
        public ConnectionEventInfo(ConnectionBase sourceConn, HTTPConnectionStates newState)
        {
            this.Source = sourceConn;

            this.Event = ConnectionEvents.StateChange;

            this.State = newState;

            this.ProtocolSupport = HostProtocolSupport.Unknown;
        }
예제 #5
0
        public ConnectionEventInfo(ConnectionBase sourceConn, HTTPRequest request)
        {
            this.Source = sourceConn;

            this.Event = ConnectionEvents.StateChange;

            this.State = HTTPConnectionStates.ClosedResendRequest;

            this.ProtocolSupport = HostProtocolSupport.Unknown;

            this.Request = request;
        }
예제 #6
0
        private void HandleClientConnectionApproval(Client client, NetIncomingMessage msg)
        {
            var type    = msg.ReadInt32();
            var length  = msg.ReadInt32();
            var connReq = Util.DeserializeBinary <ConnectionRequest>(msg.ReadBytes(length));

            if (connReq == null)
            {
                DenyConnect(client, "Connection is null, this is most likely a bug in the client.", true, msg);
                return;
            }

            var pluginResponse = ConnectionEvents.ConnectionRequest(client, connReq);

            if (!pluginResponse.ContinueServerProc)
            {
                return;
            }
            connReq = pluginResponse.Data;

            client.DisplayName         = connReq.DisplayName;
            client.Name                = connReq.Name;
            client.GameVersion         = connReq.GameVersion;
            client.RemoteScriptVersion = (ScriptVersion)connReq.ScriptVersion;


            // If nicknames are disabled on the server, set the nickname to the player's social club name.
            if (!AllowNicknames)
            {
                SendNotificationToPlayer(client,
                                         $"Nicknames are disabled on this server. Your nickname has been set to {connReq.Name}");
                client.DisplayName = client.Name;
            }


            logger.LogInformation(
                $"New connection request: {client.DisplayName}@{msg.SenderEndPoint.Address.ToString()} | Game version: {client.GameVersion.ToString()} | Script version: {client.RemoteScriptVersion.ToString()}");

            var latestScriptVersion = Enum.GetValues(typeof(ScriptVersion)).Cast <ScriptVersion>().Last();

            if (!AllowOutdatedClients &&
                (ScriptVersion)connReq.ScriptVersion != latestScriptVersion)
            {
                var latestReadableScriptVersion = latestScriptVersion.ToString();
                latestReadableScriptVersion = Regex.Replace(latestReadableScriptVersion, "VERSION_", "",
                                                            RegexOptions.IgnoreCase);
                latestReadableScriptVersion = Regex.Replace(latestReadableScriptVersion, "_", ".",
                                                            RegexOptions.IgnoreCase);

                logger.LogInformation($"Client {client.DisplayName} tried to connect with an outdated script version {client.RemoteScriptVersion.ToString()} but the server requires {latestScriptVersion.ToString()}");
                DenyConnect(client, $"Please update to version ${latestReadableScriptVersion} from http://bit.ly/gtacoop", true, msg);
                return;
            }
            else if (client.RemoteScriptVersion != latestScriptVersion)
            {
                SendNotificationToPlayer(client, "You are currently on an outdated client. Please go to http://bit.ly/gtacoop and update.");
            }
            else if (client.RemoteScriptVersion == ScriptVersion.VERSION_UNKNOWN)
            {
                logger.LogInformation($"Client {client.DisplayName} tried to connect with an unknown script version (client too old?)");
                DenyConnect(client, $"Unknown version. Please re-download GTACoop from http://bit.ly/gtacoop", true, msg);
                return;
            }
            var numClients = 0;

            lock (Clients) numClients = Clients.Count;
            if (numClients >= MaxPlayers)
            {
                logger.LogInformation($"Player tried to join while server is full: {client.DisplayName}");
                DenyConnect(client, "No available player slots.", true, msg);
            }

            if (PasswordProtected && connReq.Password != Password)
            {
                logger.LogInformation($"Client {client.DisplayName} tried to connect with the wrong password.");
                DenyConnect(client, "Wrong password.", true, msg);
            }

            lock (Clients)
                if (Clients.Any(c => c.DisplayName == client.DisplayName))
                {
                    DenyConnect(client, "A player already exists with the current display name.");
                }
                else
                {
                    Clients.Add(client);
                }



            var channelHail = Server.CreateMessage();

            channelHail.Write(GetChannelForClient(client));
            client.NetConnection.Approve(channelHail);
        }
예제 #7
0
 private void Awake()
 {
     Instance = this;
 }
예제 #8
0
        private static ServerHandshakePacket BeginConnection(ConnectionEvents events, string ip, int port)
        {
            events.OnStatusUpdate?.Invoke("Connecting To Master Server...");
            TcpClient c = null;

            try
            {
                c = new TcpClient(ip, port);
                events.OnStatusUpdate?.Invoke("Connected to Server...");
            }
            catch (Exception connEX)
            {
                events.OnError?.Invoke(MatchMakingErrorCode.SocketException, connEX);
                events.OnStatusUpdate?.Invoke("Connection Failed... Exception: \n" + connEX.Message);
                return(new ServerHandshakePacket()
                {
                    ErrorCode = MatchMakingErrorCode.SocketException, ErrorException = connEX
                });
            }

            object obj = null;

            try
            {
                events.OnStatusUpdate?.Invoke("Waiting for Handshake...");
                if (!SerializerSingleton.Serializer.TryReadPacket(c.GetStream(), out obj))
                {
                    throw new Exception();
                }
            }
            catch (Exception e)
            {
                events.OnStatusUpdate?.Invoke("Handshake Failed... Exception: \n" + e.Message);
                events.OnError?.Invoke(MatchMakingErrorCode.PacketDeserializationException, e);
                return(new ServerHandshakePacket()
                {
                    ErrorCode = MatchMakingErrorCode.PacketDeserializationException, ErrorException = e
                });
            }

            if (obj == null)
            {
                events.OnStatusUpdate?.Invoke("Handshake Failed... Deserialized object was null");
                events.OnError?.Invoke(MatchMakingErrorCode.PacketDeserializationException, null);
                return(new ServerHandshakePacket()
                {
                    ErrorCode = MatchMakingErrorCode.PacketDeserializationException
                });
            }


            if (obj is ClientHandshakePacket)
            {
                events.OnStatusUpdate?.Invoke("Handshake Received..");
                ClientHandshakePacket packet = (ClientHandshakePacket)obj;
                ServerHandshakePacket sp     = new ServerHandshakePacket
                {
                    Client           = c,
                    HeartBeat        = packet.HeartBeat,
                    CurrentInstances = packet.CurrentInstances,
                    MaxInstances     = packet.MaxInstances,
                    WaitingQueue     = packet.WaitingQueue
                };
                return(sp);
            }
            events.OnStatusUpdate?.Invoke("Handshake Failed... Wrong Packet Received");
            events.OnError?.Invoke(MatchMakingErrorCode.WrongPacketReceived, null);
            return(new ServerHandshakePacket()
            {
                ErrorCode = MatchMakingErrorCode.WrongPacketReceived
            });
            //throw new Exception("Expected Packet of Type ClientHandshakePacket. Got: " + obj.GetType());
        }
예제 #9
0
        public static ServerInstanceResultPacket Queue(ConnectionEvents events, string ip, int port, CancellationToken token)
        {
            ServerHandshakePacket conn = BeginConnection(events, ip, port);

            return(FindMatch(events, conn, token));
        }
예제 #10
0
 public static Task <ServerInstanceResultPacket> QueueAsync(ConnectionEvents events, string ip, int port, CancellationToken token)
 {
     Logger.DefaultLogger(events.ToString());
     return(new Task <ServerInstanceResultPacket>(() => Queue(events, ip, port, token)));
 }
예제 #11
0
        //public static ServerInstanceResultPacket FindMatch(ConnectionEvents events, ServerHandshakePacket packet)
        //{
        //    return FindMatch(events, packet, new CancellationToken());
        //}


        private static ServerInstanceResultPacket FindMatch(ConnectionEvents events, ServerHandshakePacket packet, CancellationToken token)
        {
            if (packet.ErrorCode != MatchMakingErrorCode.None)
            {
                return(new ServerInstanceResultPacket()
                {
                    ErrorCode = packet.ErrorCode, ErrorException = packet.ErrorException
                });
            }


            //try
            //{
            TcpClient c = packet.Client;

            int waitTime = packet.HeartBeat;

            events.OnStatusUpdate?.Invoke("In Queue..");
            Logger.DefaultLogger(packet.ToString());
            while (c.Connected && c.Available == 0)
            {
                if (token.IsCancellationRequested)
                {
                    Logger.DefaultLogger("Aborting Queue");
                    events.OnStatusUpdate?.Invoke("Aborting Queue...");
                    events.OnError?.Invoke(MatchMakingErrorCode.ClientQueueAborted, null);

                    return(new ServerInstanceResultPacket()
                    {
                        ErrorCode = MatchMakingErrorCode.ClientQueueAborted
                    });
                }

                try
                {
                    if (!SerializerSingleton.Serializer.TryWritePacket(c.GetStream(), new ClientHeartBeatPacket()))
                    {
                        throw new Exception("Serializer Write Error");
                    }
                }
                catch (Exception e)
                {
                    events.OnStatusUpdate?.Invoke("Packet Could not be Deserialized. Exception: " + e.Message);

                    break; //We could still have some data in the stream that could be our instance ready packet

                    //events.OnError?.Invoke(MatchMakingErrorCode.PacketSerializationException, e);
                    //return new ServerInstanceResultPacket() { ErrorCode = MatchMakingErrorCode.PacketSerializationException, ErrorException = e };
                }
                Thread.Sleep(waitTime);
                Logger.DefaultLogger("Heartbeat...");
            }



            if (c.Available == 0)
            {
                events.OnStatusUpdate?.Invoke("Client or Server has Disconnected during Queue.");
                events.OnError?.Invoke(MatchMakingErrorCode.ClientDisconnectDuringReady, null);
                return(new ServerInstanceResultPacket()
                {
                    ErrorCode = MatchMakingErrorCode.ClientDisconnectDuringReady
                });
            }
            ClientInstanceReadyPacket irp;


            events.OnStatusUpdate?.Invoke("Creating Match...");

            try
            {
                if (!SerializerSingleton.Serializer.TryReadPacket(c.GetStream(), out irp))
                {
                    throw new Exception();
                }

                events.OnStatusUpdate?.Invoke("Received Packet Data..");
            }
            catch (Exception e)
            {
                events.OnStatusUpdate?.Invoke("Packet Could not be Deserialized. Exception: " + e.Message);
                events.OnError?.Invoke(MatchMakingErrorCode.PacketSerializationException, e);
                return(new ServerInstanceResultPacket()
                {
                    ErrorCode = MatchMakingErrorCode.PacketSerializationException, ErrorException = e
                });
            }


            events.OnStatusUpdate?.Invoke("Match Starting on Port: " + irp.Port);

            Logger.DefaultLogger($"Client: Current Instances: {packet.CurrentInstances}/{packet.MaxInstances}");
            Logger.DefaultLogger($"Client: Clients in Queue: {packet.WaitingQueue}");
            Logger.DefaultLogger($"Client: Instance Ready: {irp.Port}");

            if (c.Connected)
            {
                c.Close();
            }


            ServerInstanceResultPacket ret = new ServerInstanceResultPacket {
                Port = irp.Port, ErrorCode = MatchMakingErrorCode.None
            };

            events.OnSuccess?.Invoke(ret);
            return(ret);
            //}
            //catch (Exception unhandled)
            //{
            //    events.OnStatusUpdate?.Invoke("Packet Could not be Deserialized. Exception: " + unhandled.Message);
            //    events.OnError?.Invoke(MatchMakingErrorCode.PacketSerializationException, unhandled);
            //    return new ServerInstanceResultPacket() { Port = -1, ErrorCode = MatchMakingErrorCode.UnhandledError, ErrorException = unhandled };
            //}
        }