/// <summary>
    /// Handles users request to join the game world.
    /// It picks a random (*first) game server
    /// </summary>
    /// <param name="message"></param>
    public virtual void HandleEnterWorldRequest(IIncommingMessage message)
    {
        var user = message.Peer.GetExtension <IUserExtension>();

        if (user == null)
        {
            // Invalid player session
            message.Respond("Not logged in", ResponseStatus.Unauthorized);
            return;
        }

        // Get world servers. We can filter world zones by checking
        // if a game server has a zone name key
        var worldServers = RoomsModule.GetAllRooms()
                           .Where(s => s.Options.Properties.ContainsKey(ZoneNameKey));

        // Find which zone we should be getting into.

        // You'd probably want to load the name of the zone
        // the user was in before quitting the game, but to keep this
        // example simple, we'll just take the first zone from the list
        var gameServer = worldServers.FirstOrDefault();

        if (gameServer == null)
        {
            message.Respond("Zone not found", ResponseStatus.Failed);
            return;
        }

        // Request an access
        gameServer.GetAccess(user.Peer, (access, error) =>
        {
            if (access == null)
            {
                // We didn't get the access
                message.Respond("Failed to get access to the zone: " + error, ResponseStatus.Failed);
                return;
            }

            // We have the access to new zone, let's store it
            // so player can request it when he's on the loading screen
            message.Peer.SetProperty(WorldDemoPropCodes.ZoneAccess, access);

            // Notify client that he's ready to enter the zone
            message.Respond(access, ResponseStatus.Success);
        });
    }
Esempio n. 2
0
        private void HandleClientsSpawnRequest(IIncommingMessage message)
        {
            var data = message.Deserialize <ClientsSpawnRequestPacket>();
            var peer = message.Peer;

            if (!CanClientSpawn(peer, data))
            {
                // Client can't spawn
                message.Respond("Unauthorized", ResponseStatus.Unauthorized);
                return;
            }

            if (peer.GetProperty((int)PeerPropertyKeys.ClientSpawnRequest) is SpawnTask prevRequest &&
                !prevRequest.IsDoneStartingProcess)
            {
                // Client has unfinished request
                message.Respond("You already have an active request", ResponseStatus.Failed);
                return;
            }

            // Get the spawn task
            var task = Spawn(data.Options, data.Region);

            if (task == null)
            {
                message.Respond("All the servers are busy. Try again later".ToBytes(), ResponseStatus.Failed);
                return;
            }

            task.Requester = message.Peer;

            // Save the task
            peer.SetProperty((int)PeerPropertyKeys.ClientSpawnRequest, task);

            // Listen to status changes
            task.StatusChanged += status =>
            {
                // Send status update
                message.Peer.SendMessage((ushort)OpCodes.SpawnRequestStatusChange, new SpawnStatusUpdatePacket
                {
                    SpawnId = task.SpawnId,
                    Status  = status
                });
            };

            message.Respond(task.SpawnId, ResponseStatus.Success);
        }
Esempio n. 3
0
        public bool peerJoined(IIncommingMessage rawMsg, PlayerInfo info, ref PreGameRoomMsg returnMsg)
        {
            if (getAmountCurrentPlayers() >= specs.maxPlayers)
            {
                rawMsg.Respond("Game is already full", ResponseStatus.Failed);
                return(false);
            }
            if (state != PreGameState.Lobby)
            {
                rawMsg.Respond("Game has already started", ResponseStatus.Failed);
                return(false);
            }

            addPeerToGame(rawMsg.Peer, info);
            returnMsg = newUpdate();
            return(true);
        }
Esempio n. 4
0
        private void HandleLobbyMemberReadyStatusChangeMsg(IIncommingMessage message)
        {
            var data = message.Deserialize(new StringPairPacket());

            LobbyMemberData member;

            Members.TryGetValue(data.A, out member);

            if (member == null)
            {
                return;
            }

            member.IsReady = bool.Parse(data.B);

            Listener?.OnMemberReadyStatusChanged(member, member.IsReady);
        }
Esempio n. 5
0
        protected void C2L_JoinRoom(IIncommingMessage reader)
        {
            var msg = reader.Parse <Msg_C2L_JoinRoom>();

            Debug.Log("C2L_JoinRoom" + msg);
            var roomId = msg.RoomId;

            if (_roomId2Room.TryGetValue(roomId, out var room))
            {
                if (room.IsFull)
                {
                    reader.Respond((int)ERoomOperatorResult.Full, EResponseStatus.Failed);
                    return;
                }
                else
                {
                    var user = reader.Peer.GetExtension <User>();
                    if (user.Room == null)
                    {
                        user.Room = room;
                        room.AddUser(user);
                        reader.Respond((short)EMsgSC.L2C_JoinRoomResult, new Msg_L2C_JoinRoomResult()
                        {
                            PlayerInfos = room.RoomPlayerInfos
                        });
                        room.BorderMessage((short)EMsgSC.L2C_JoinRoom, new Msg_L2C_JoinRoom()
                        {
                            PlayerInfo = new RoomPlayerInfo()
                            {
                                UserId = user.UserId,
                                Name   = user.Name,
                                Status = user.IsReady
                            }
                        });
                    }
                    else
                    {
                        reader.Respond((int)ERoomOperatorResult.AlreadyExist, EResponseStatus.Failed);
                    }
                }
            }
            else
            {
                reader.Respond((int)ERoomOperatorResult.NotExist, EResponseStatus.Failed);
            }
        }
Esempio n. 6
0
        protected virtual void HandlerRegisterSpawner(IIncommingMessage message)
        {
            if (!HasCreationPermissions(message.Peer))
            {
                message.Respond("Insufficient permissions", ResponseStatus.Unauthorized);
                return;
            }

            var options = message.Deserialize(new SpawnerOptions());

            var spawner = CreateSpawner(message.Peer, options);

            _logger.Info($"New Spawner registered. ID: {spawner.SpawnerId}");

            // Respond with spawner id
            message.Respond(spawner.SpawnerId, ResponseStatus.Success);
        }
Esempio n. 7
0
        private void HandleLeftLobbyMsg(IIncommingMessage message)
        {
            var id = message.AsString();

            // Check the id in case there's something wrong with message order
            if (Id != id)
            {
                return;
            }

            HasLeft = true;

            if (_listener != null)
            {
                _listener.OnLobbyLeft();
            }
        }
    private bool validateDecryptMsg(IIncommingMessage msg, out Dictionary <string, string> data)
    {
        var encryptedData = msg.AsBytes();
        var securityExt   = msg.Peer.GetExtension <PeerSecurityExtension>();
        var aesKey        = securityExt.AesKey;

        data = new Dictionary <string, string> ();
        if (aesKey == null)
        {
            return(false);
        }

        var decrypted = Msf.Security.DecryptAES(encryptedData, aesKey);

        data = new Dictionary <string, string>().FromBytes(decrypted);
        return(true);
    }
Esempio n. 9
0
        /// <summary>
        /// Handles a request from user to leave a lobby
        /// </summary>
        /// <param name="message"></param>
        protected virtual void HandleLeaveLobby(IIncommingMessage message)
        {
            var lobbyId = message.AsInt();

            ILobby lobby;

            lobbies.TryGetValue(lobbyId, out lobby);

            var lobbiesExt = GetOrCreateLobbiesExtension(message.Peer);

            if (lobby != null)
            {
                lobby.RemovePlayer(lobbiesExt);
            }

            message.Respond(ResponseStatus.Success);
        }
        private void handleTournamentCreated(ResponseStatus status, IIncommingMessage rawMsg)
        {
            string msg = rawMsg.AsString();

            print("Tournament Created: " + status + "  :" + msg);
            if (waitingForResponse == false)
            {
                return;
            }

            waitingForResponse = false;
            if (status == ResponseStatus.Success)
            {
                currentTournamentID = msg;
                state = TournamentState.Lobby;
            }
        }
Esempio n. 11
0
        private static void HandleKillSpawnedProcessRequest(IIncommingMessage message)
        {
            var data = message.Deserialize(new KillSpawnedProcessPacket());

            var controller = Msf.Server.Spawners.GetController(data.SpawnerId);

            if (controller == null)
            {
                if (message.IsExpectingResponse)
                {
                    message.Respond("Couldn't find a spawn controller", ResponseStatus.NotHandled);
                }
                return;
            }

            controller.HandleKillSpawnedProcessRequest(data.SpawnId);
        }
Esempio n. 12
0
        protected void X2Y_ReqOtherServerInfo(IIncommingMessage reader)
        {
            var msg = reader.Parse <Msg_ReqOtherServerInfo>();

            if (_type2MasterPeer.TryGetValue((EServerType)msg.ServerType, out var peer))
            {
                peer.SendMessage((short)EMsgYM.Y2M_ReqOtherServerInfo, msg,
                                 (status, respond) => {
                    var rMsg = respond.Parse <Msg_RepOtherServerInfo>();
                    reader.Respond(rMsg);
                });
            }
            else
            {
                reader.Respond(0, EResponseStatus.Failed);
            }
        }
Esempio n. 13
0
        protected void S2X_ReqOtherServerInfo(IIncommingMessage reader)
        {
            var msg = reader.Parse <Msg_ReqOtherServerInfo>();

            _netClientYX.SendMessage(EMsgYX.X2Y_ReqOtherServerInfo, msg,
                                     (status, respond) => {
                if (status == EResponseStatus.Failed)
                {
                    reader.Respond(0, EResponseStatus.Failed);
                }
                else
                {
                    var rMsg = respond.Parse <Msg_RepOtherServerInfo>();
                    reader.Respond(rMsg);
                }
            });
        }
Esempio n. 14
0
        protected virtual void OnMessageReceived(IIncommingMessage message)
        {
            try
            {
                IPacketHandler handler;
                Handlers.TryGetValue(message.OpCode, out handler);

                if (handler == null)
                {
                    Logger.Warn(string.Format("Handler for OpCode {0} does not exist", message.OpCode));

                    if (message.IsExpectingResponse)
                    {
                        message.Respond(InternalServerErrorMessage, ResponseStatus.NotHandled);
                        return;
                    }
                    return;
                }

                handler.Handle(message);
            }
            catch (Exception e)
            {
                if (Msf.Runtime.IsEditor)
                {
                    throw;
                }

                Logger.Error("Error while handling a message from Client. OpCode: " + message.OpCode);
                Logger.Error(e);

                if (!message.IsExpectingResponse)
                {
                    return;
                }

                try
                {
                    message.Respond(InternalServerErrorMessage, ResponseStatus.Error);
                }
                catch (Exception exception)
                {
                    Logs.Error(exception);
                }
            }
        }
Esempio n. 15
0
 void ReqUserInfo(Msg_C2I_UserLogin cInfo, IIncommingMessage reader){
     var account = cInfo.Account;
     var password = cInfo.Password;
     _netClientDS?.SendMessage(EMsgDS.S2D_ReqUserInfo, new Msg_ReqAccountData() {
         account = account,
         password = password
     }, (status, response) => {
         var msg = response.Parse<Msg_RepAccountData>();
         if (msg.accountData == null) {
             CreateUser(cInfo, reader);
         }
         else {
             //密码不正确
             NotifyLobbyUserLoginResult(msg.accountData.Password, msg.accountData.UserId, cInfo, reader);
         }
     });
 }
Esempio n. 16
0
        protected void TriggerAck(int ackId, ResponseStatus statusCode, IIncommingMessage message)
        {
            ResponseCallback ackCallback;

            lock (_acks)
            {
                _acks.TryGetValue(ackId, out ackCallback);

                if (ackCallback == null)
                {
                    return;
                }

                _acks.Remove(ackId);
            }
            ackCallback(statusCode, message);
        }
Esempio n. 17
0
        private void HandleValidateRoomAccess(IIncommingMessage message)
        {
            var data = message.Deserialize(new RoomAccessValidatePacket());

            RegisteredRoom room;

            Rooms.TryGetValue(data.RoomId, out room);

            if (room == null)
            {
                message.Respond("Room does not exist", ResponseStatus.Failed);
                return;
            }

            if (message.Peer != room.Peer)
            {
                // Wrong peer unregistering the room
                message.Respond("You're not the creator of the room", ResponseStatus.Unauthorized);
                return;
            }

            IPeer playerPeer;

            if (!room.ValidateAccess(data.Token, out playerPeer))
            {
                message.Respond("Failed to confirm the access", ResponseStatus.Unauthorized);
                return;
            }

            var packet = new UsernameAndPeerIdPacket()
            {
                PeerId = playerPeer.Id
            };

            // Add username if available
            var userExt = playerPeer.GetExtension <IUserExtension>();

            if (userExt != null)
            {
                packet.Username = userExt.Username ?? "";
            }

            // Respond with success and player's peer id
            message.Respond(packet, ResponseStatus.Success);
        }
Esempio n. 18
0
        /// <summary>
        /// Handles a message from game server, which includes player profiles updates
        /// </summary>
        /// <param name="message"></param>
        protected virtual void ProfileUpdateHandler(IIncommingMessage message)
        {
            if (!HasPermissionToEditProfiles(message.Peer))
            {
                Logs.Error("Master server received an update for a profile, but peer who tried to " +
                           "update it did not have sufficient permissions");
                return;
            }

            var data = message.AsBytes();

            using (var ms = new MemoryStream(data))
            {
                using (var reader = new EndianBinaryReader(EndianBitConverter.Big, ms))
                {
                    // Read profiles count
                    var count = reader.ReadInt32();

                    for (var i = 0; i < count; i++)
                    {
                        // Read username
                        var username = reader.ReadString();

                        // Read updates length
                        var updatesLength = reader.ReadInt32();

                        // Read updates
                        var updates = reader.ReadBytes(updatesLength);

                        try
                        {
                            if (ProfilesList.TryGetValue(username, out ObservableServerProfile profile))
                            {
                                profile.ApplyUpdates(updates);
                            }
                        }
                        catch (Exception e)
                        {
                            Logs.Error("Error while trying to handle profile updates from master server");
                            Logs.Error(e);
                        }
                    }
                }
            }
        }
Esempio n. 19
0
        protected virtual void HandleSendChatMessage(IIncommingMessage message)
        {
            var chatUser = message.Peer.GetExtension <ChatUserExtension>();

            if (chatUser == null)
            {
                message.Respond("Chat cannot identify you", ResponseStatus.Unauthorized);
                return;
            }

            var packet = message.Deserialize(new ChatMessagePacket());

            if (!OnChatMessageReceived(packet, chatUser, message))
            {
                // If message was not handled
                message.Respond("Invalid message", ResponseStatus.NotHandled);
            }
        }
Esempio n. 20
0
        protected void X2Y_ReqMasterInfo(IIncommingMessage reader)
        {
            var serverInfo = reader.Parse <Msg_ReqMasterInfo>().ServerInfo;
            var type       = (EServerType)serverInfo.ServerType;

            if (serverInfo.IsMaster)
            {
                _netServerYX.BorderMessage(EMsgYX.Y2X_BorderMasterInfo,
                                           new Msg_BorderMasterInfo()
                {
                    ServerInfo = serverInfo
                });
            }
            reader.Respond(EMsgYX.Y2X_RepMasterInfo, new Msg_RepMasterInfo()
            {
                ServerInfo = _type2MasterInfo.GetRefVal(type)
            });
        }
Esempio n. 21
0
        /// <summary>
        /// Handles spawn request for all controllers filtered by ID
        /// </summary>
        /// <param name="message"></param>
        private static void SpawnProcessRequestHandler(IIncommingMessage message)
        {
            var data       = message.Deserialize(new SpawnRequestPacket());
            var controller = Mst.Server.Spawners.GetController(data.SpawnerId) as SpawnerController;

            if (controller == null)
            {
                if (message.IsExpectingResponse)
                {
                    message.Respond("Couldn't find a spawn controller", ResponseStatus.NotHandled);
                }

                return;
            }

            controller.Logger.Debug($"Spawn process requested for spawn controller [{controller.SpawnerId}]");
            controller.SpawnRequestHandler(data, message);
        }
        protected virtual void RegisterSpawnerRequestHandler(IIncommingMessage message)
        {
            logger.Debug($"Client [{message.Peer.Id}] requested to be registered as spawner");

            if (!HasCreationPermissions(message.Peer))
            {
                message.Respond("Insufficient permissions", ResponseStatus.Unauthorized);
                return;
            }

            var options = message.Deserialize(new SpawnerOptions());
            var spawner = CreateSpawner(message.Peer, options);

            logger.Debug($"Client [{message.Peer.Id}] was successfully registered as spawner [{spawner.SpawnerId}] with options: {options}");

            // Respond with spawner id
            message.Respond(spawner.SpawnerId, ResponseStatus.Success);
        }
Esempio n. 23
0
        private static void HandleStatusUpdate(IIncommingMessage message)
        {
            var data = message.Deserialize(new SpawnStatusUpdatePacket());

            var controller = Msf.Client.Spawners.GetRequestController(data.SpawnId);

            if (controller == null)
            {
                return;
            }

            controller.Status = data.Status;

            if (controller.StatusChanged != null)
            {
                controller.StatusChanged.Invoke(data.Status);
            }
        }
Esempio n. 24
0
        protected void L2G_UserReconnect(IIncommingMessage reader)
        {
            var msg = reader.Parse <Msg_L2G_UserReconnect>();

            Log("L2G_UserReconnect " + msg);
            if (_uid2Players.TryGetValue(msg.PlayerInfo.UserId, out var player))
            {
                var game = player.Game;
                if (game != null)
                {
                    game.OnPlayerReconnect(msg.PlayerInfo);
                    reader.Respond(1, EResponseStatus.Success);
                    return;
                }
            }

            reader.Respond(0, EResponseStatus.Failed);
        }
Esempio n. 25
0
        private void HandleSpawnRequest(IIncommingMessage message)
        {
            var data = message.Deserialize(new SpawnRequestPacket());

            var controller = _spawners.GetController(data.SpawnerId);

            if (controller == null)
            {
                if (message.IsExpectingResponse)
                {
                    message.Respond("Couldn't find a spawn controller", ResponseStatus.NotHandled);
                }
                return;
            }

            // Pass the request to handler
            controller.HandleSpawnRequest(data, message);
        }
Esempio n. 26
0
        private void HandleLobbyMemberLeftMsg(IIncommingMessage message)
        {
            var username = message.AsString();

            LobbyMemberData member;

            Members.TryGetValue(username, out member);

            if (member == null)
            {
                return;
            }

            if (_listener != null)
            {
                _listener.OnMemberLeft(member);
            }
        }
Esempio n. 27
0
        /// <summary>
        ///     Handles e-mail confirmation request
        /// </summary>
        /// <param name="message"></param>
        private void HandleEmailConfirmation(IIncommingMessage message)
        {
            var code = message.AsString();

            var extension = message.Peer.GetExtension <UserExtension>();

            if (extension?.AccountData == null)
            {
                message.Respond("Invalid session", ResponseStatus.Unauthorized);
                return;
            }

            if (extension.AccountData.IsGuest)
            {
                message.Respond("Guests cannot confirm e-mails", ResponseStatus.Unauthorized);
                return;
            }

            if (extension.AccountData.IsEmailConfirmed)
            {
                // We still need to respond with "success" in case
                // response is handled somehow on the client
                message.Respond("Your email is already confirmed",
                                ResponseStatus.Success);
                return;
            }

            var requiredCode = _database.GetEmailConfirmationCode(extension.AccountData.Email);

            if (requiredCode != code)
            {
                message.Respond("Invalid activation code", ResponseStatus.Error);
                return;
            }

            // Confirm e-mail
            extension.AccountData.IsEmailConfirmed = true;

            // Update account
            _database.UpdateAccount(extension.AccountData);

            // Respond with success
            message.Respond(ResponseStatus.Success);
        }
        private void HandleMessage(IIncommingMessage message)
        {
            try
            {
                IPacketHandler handler;
                _handlers.TryGetValue(message.OpCode, out handler);

                if (handler != null)
                {
                    handler.Handle(message);
                }
                else if (message.IsExpectingResponse)
                {
                    Debug.LogError("Connection is missing a handler. OpCode: " + message.OpCode);
                    message.Respond(EResponseStatus.Error);
                }
            }
            catch (Exception e)
            {
#if UNITY_EDITOR
                if (RethrowExceptionsInEditor)
                {
                    throw;
                }
#endif

                Debug.LogError("Failed to handle a message. OpCode: " + message.OpCode);
                Debug.LogError(e);

                if (!message.IsExpectingResponse)
                {
                    return;
                }

                try
                {
                    message.Respond(EResponseStatus.Error);
                }
                catch (Exception exception)
                {
                    Debug.LogError(exception);
                }
            }
        }
    /// <summary>
    /// Handles a request from game server to teleport
    /// user to another game server / zone.
    /// </summary>
    /// <param name="message"></param>
    public virtual void HandleTeleportRequest(IIncommingMessage message)
    {
        var request = message.Deserialize(new TeleportRequestPacket());

        var user = AuthModule.GetLoggedInUser(request.Username);
        var peer = user.Peer;

        // Find the room which represents the zone we need
        var room = RoomsModule.GetAllRooms()
                   .Where(s => s.Options.Properties.ContainsKey(ZoneNameKey))
                   .FirstOrDefault(s => s.Options.Properties[ZoneNameKey] == request.ZoneName);

        if (room == null)
        {
            // If no room with that zone name was found
            message.Respond("Zone was not found", ResponseStatus.Failed);
            return;
        }

        var accessRequestProperties = new Dictionary <string, string>()
        {
            // Add the new position to the request
            // So that new server knows where exactly to position the player
            { ZonePosition, request.Position }
        };

        // Request an access to room
        room.GetAccess(peer, accessRequestProperties, (access, error) =>
        {
            if (access == null)
            {
                // We didn't get the access
                message.Respond("Failed to get access to the zone: " + error, ResponseStatus.Failed);
                return;
            }

            // We have the access to new zone, let's store it
            // so player can request it when he's on the loading screen
            peer.SetProperty(WorldDemoPropCodes.ZoneAccess, access);

            // Notify game server that access was received
            message.Respond(ResponseStatus.Success);
        });
    }
Esempio n. 30
0
        protected virtual void HandlePickUsername(IIncommingMessage message)
        {
            if (!AllowUsernamePicking)
            {
                message.Respond("Username picking is disabled", ResponseStatus.Failed);
                return;
            }

            var username = message.AsString();

            if (username.Replace(" ", "") != username)
            {
                message.Respond("Username cannot contain whitespaces", ResponseStatus.Failed);
                return;
            }

            var chatUser = message.Peer.GetExtension <ChatUserExtension>();

            if (chatUser != null)
            {
                message.Respond("You're already identified as: " + chatUser);
                return;
            }

            if (ChatUsers.ContainsKey(username.ToLower()))
            {
                message.Respond("There's already a user who has the same username", ResponseStatus.Failed);
                return;
            }

            chatUser = new ChatUserExtension(message.Peer, username);

            if (!AddChatUser(chatUser))
            {
                message.Respond("Failed to add user to chat", ResponseStatus.Failed);
                return;
            }

            // Add the extension
            message.Peer.AddExtension(chatUser);

            message.Respond(ResponseStatus.Success);
        }