Esempio n. 1
0
 private void OnPlayerDone(ServerUser user, PacketGameMessage msg)
 {
     try
     {
         PlayerDone(user.CurrentCharacter);
     }
     catch
     {
     }
 }
Esempio n. 2
0
 protected override bool OnBeforeHandleGamePacket(ServerUser user, PacketGameMessage msg)
 {
     try
     {
         return(IsPlayerPartOfGame(user.CurrentCharacter.ID));
     }
     catch
     {
         return(false);
     }
 }
Esempio n. 3
0
        /// <summary>
        /// Gets called when a game sub-server sends us a reply to our request to have a player play on that server.  This method forwards that reply to the player.
        /// </summary>
        private void OnPlayerHandoffResult(INetworkConnection sender, Packet msg)
        {
            PacketPlayerAuthorizedForTransfer p = msg as PacketPlayerAuthorizedForTransfer;
            ServerUser playerCon = ConnectionManager.GetAuthorizedUser(p.AccountName, Server, PacketLoginRequest.ConnectionType.AssistedTransfer);

            if (playerCon != null)
            {
                Log1.Logger("Server.Outbound.Network").Info("Account [" + playerCon.AccountName + "] transfer request to " + Name + " reply: [" + p.ReplyCode.ToString() + "]. Forwarding result to player.");
            }
            OnPlayerHandoffResponseReceived(p, playerCon);
        }
Esempio n. 4
0
        public static INetworkConnection GetUserConnection(Guid user)
        {
            INetworkConnection con = null;
            ServerUser         su  = null;

            if (AuthorizedAccounts.TryGetValue(user, out su))
            {
                con = su.MyConnection;
            }
            return(con);
        }
Esempio n. 5
0
        protected void SendGameMessageReply(ServerUser client, ReplyType rp, string msg, Packet inResponseToPacket, PropertyBag parms, bool compress, bool encrypt)
        {
            PacketReply rmsg = client.MyConnection.CreateStandardReply(inResponseToPacket, rp, msg);

            if (parms != null)
            {
                rmsg.Parms = parms;
            }
            rmsg.IsCompressed = compress;
            rmsg.IsEncrypted  = encrypt;
            inResponseToPacket.ReplyPacket = rmsg;
        }
        public override Guid OnPlayerConnectionRequest(ServerUser player, ref string msg)
        {
            // only allow players on the game server if we have a character selection
            if (player.CurrentCharacter == null)
            {
                return(Guid.Empty);
            }

            Guid ticket = base.OnPlayerConnectionRequest(player, ref msg);

            return(ticket);
        }
Esempio n. 7
0
        /// <summary>
        /// Saves/updates the character to the DB
        /// </summary>
        /// <param name="owner">owning account</param>
        /// <param name="id">the id for the character to get</param>
        /// <param name="enforceUniqueName">You can change a toon's name in the DB. To ensure unique names, set to true. IMPORTANT!!!: If you are saving
        /// , i.e. updating an EXISTING toon without changing his name, set enforceUniqueName to FALSE - otherwise the update will fail since that
        /// toon's name already exists in the DB, the update will fail.</param>
        /// <returns></returns>
        public bool SaveCharacter(ServerUser owner, ServerCharacterInfo toon, bool enforceUniqueName, ref string rsultMsg)
        {
            SqlConnection  con  = null;
            SqlTransaction tran = null;

            try
            {
                Guid cown = Guid.Empty;
                if (DB.Instance.Character_Save(owner.ID, toon, (int)PropertyID.Name, toon.CharacterName, enforceUniqueName, out rsultMsg, out tran, out con))
                {
                    if (!OnCharacterSaving(con, tran, toon, ref rsultMsg))
                    {
                        tran.Rollback();
                    }
                    else
                    {
                        tran.Commit();
                    }
                }
                else
                {
                    if (con.State != System.Data.ConnectionState.Closed && con.State != System.Data.ConnectionState.Connecting)
                    {
                        if (tran != null)
                        {
                            tran.Rollback();
                        }
                    }
                    rsultMsg = "Can't save character. " + rsultMsg;
                    return(false);
                }
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                    con.Dispose();
                    con = null;
                }
                if (tran != null)
                {
                    tran.Dispose();
                    tran = null;
                }
            }
            return(true);
        }
Esempio n. 8
0
        /// <summary>
        /// Each server in the cluster can have one parent.  Whenever the parent connects, we call this method.
        /// </summary>
        public static void AddParentConnection(InboundConnection client, ServerUser su)
        {
            InboundConnection con = null;

            if (ParentConnections.TryGetValue(client.ServerUser.AccountName.ToLower(), out con))
            {
                con.KillConnection("Parent server logging in again from different connection.");
                con.Disconnected -= new InboundConnection.DisconnectedDelegate(ParentConnection_Disconnected);
                ParentConnections.Remove(con.ServerUser.AccountName.ToLower());
            }

            ParentConnections.Add(client.ServerUser.AccountName.ToLower(), client);
            client.Disconnected += new InboundConnection.DisconnectedDelegate(ParentConnection_Disconnected);
        }
Esempio n. 9
0
        /// <summary>
        /// Transfers this connection to an available lobby server or, if there is no lobby server available, disconnects the player.
        /// </summary>
        public void TransferToLobbyOrDisconnect()
        {
            string address  = "";
            int    port     = 0;
            string serverId = "";

            if (!GetCentralHandoffAddress(ref address, ref port, ref serverId))
            {
                KillConnection("Unable to host player on this server.  No lobby server found to hand off too.");
                return;
            }

            ServerUser.TransferToServerUnassisted(address, port, Guid.Empty, "Lobby Server", serverId);
        }
Esempio n. 10
0
        /// <summary>
        /// Gets called when the parent server wishes to handoff a player off
        /// </summary>
        /// <param name="msg">request details</param>
        private void OnPlayerHandoffRequest(INetworkConnection con, Packet pck)
        {
            PacketRelayPlayerHandoffRequest msg = pck as PacketRelayPlayerHandoffRequest;

            // Create an auth ticket for the player, if we want to allow them to connect.

            ServerUser su = new ServerUser();

            su.OwningServer = msg.OwningServer;
            su.AuthTicket   = Guid.Empty;
            su.ID           = msg.Player;
            su.AccountName  = msg.AccountName;
            su.Profile      = msg.Profile;

            if (msg.Character != null)
            {
                msg.Character.OwningAccount        = su;
                su.CurrentCharacter                = msg.Character;
                su.CurrentCharacter.TargetResource = msg.TargetResource;
            }

            string rmsg = "";

            su.AuthTicket = OnPlayerConnectionRequest(su, ref rmsg);

            bool allowed = su.AuthTicket != Guid.Empty;

            if (allowed)
            {
                ConnectionManager.AuthorizeUser(su, false);
                if (msg.Character != null)
                {
                    CharacterCache.CacheCharacter(su.CurrentCharacter, ServerUser.AccountName);
                }
            }

            PacketPlayerAuthorizedForTransfer p = (PacketPlayerAuthorizedForTransfer)CreatePacket((int)ServerPacketType.PacketPlayerAuthorizedForTransfer, 0, true, true);

            p.ReplyCode      = allowed ? ReplyType.OK : ReplyType.Failure;
            p.Profile        = msg.Profile;
            p.AccountName    = msg.AccountName;
            p.AuthTicket     = su.AuthTicket;
            p.ReplyMessage   = allowed ? "Welcome to " + MyServer.ServerName + ", " + msg.AccountName : "Server is currently not accepting logins.  Try again a little later. " + rmsg;
            p.Player         = msg.Player;
            p.TargetResource = msg.TargetResource;

            msg.ReplyPacket = p; // reply will be sent by NetworkConnection.OnAfterPacketProcessed
        }
Esempio n. 11
0
        public InboundConnection(Socket s, ServerBase server, bool isBlocking) : base(isBlocking)
        {
            MyServer = server;
            NUM_CONNECTIONS_IN_MEMORY++;
            try
            {
                MyTCPSocket = s;
                MyTCPSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, DisableTCPDelay);

                m_TimeoutTimer = new Timer();

                int timeout = ConfigHelper.GetIntConfig("PlayerConnectionTimeout");
                if (timeout < 1)
                {
                    timeout = 10;
                }

                m_TimeoutTimer.Interval = timeout * 1000;
                m_TimeoutTimer.Elapsed += new ElapsedEventHandler(TimeoutTimer_Elapsed);
                m_TimeoutTimer.Start();

                ServerUser = new Shared.ServerUser();
                ServerUser.MyConnection = this;

                // Track the network socket associated with this connection object.
                string msg = "";
                if (!ConnectionManager.TrackUserSocket(this, ref msg))
                {
                    KillConnection(msg);
                    return;
                }

                if (!Transit.ListenForDataOnSocket())
                {
                    KillConnection("Remote end closed socket.");
                    return;
                }

                Log1.Logger("Server").Info("Now have [" + ConnectionManager.ConnectionCount.ToString() + " connections] attached.");
            }
            catch (Exception e)
            {
                KillConnection("Error instantiating Inbound connection object " + GetType().ToString() + " : " + e.Message);
                Log1.Logger("Server.Network").Error("Error instantiating Inbound connection object " + GetType().ToString() + " : " + e.Message, e);
                return;
            }
            SendRijndaelExchangeRequest();
        }
Esempio n. 12
0
        protected virtual void OnPlayerClientLevelLoaded(ServerUser fromPlayer, PacketGameMessage msg)
        {
            float pLoaded = msg.Parms.GetSinglelProperty("PercentLoaded").GetValueOrDefault(0);

            Log1.Logger("Server").Debug(fromPlayer.CurrentCharacter.CharacterName + " loaded " + pLoaded + "%");
            Properties.SetProperty(fromPlayer.CurrentCharacter.ID.ToString() + "_clientloadpercent", pLoaded);
            bool stillWaiting = !m_Game.AllPlayerClientsLoaded();

            Log1.Logger("Server").Debug("Still waiting for clients to load: " + stillWaiting.ToString());
            if (!stillWaiting)
            {
                Log1.Logger("Server").Debug("Firing ALL CLIENTS LOADED");
                AllPlayerClientsLoaded();
            }
            m_Game.WaitingOnClientsToLoad = stillWaiting;
        }
Esempio n. 13
0
        /// <summary>
        /// Gets the character from the DB
        /// </summary>
        /// <param name="owner">owning account</param>
        /// <param name="id">the id for the character to get</param>
        /// <returns></returns>
        public ServerCharacterInfo LoadCharacter(ServerUser owner, int id, ref string rsultMsg)
        {
            SqlConnection       con  = null;
            SqlTransaction      tran = null;
            ServerCharacterInfo ci   = OnCharacterObjectCreate(CreateNewCharacterShell(), owner);

            try
            {
                Guid cown = Guid.Empty;
                if (DB.Instance.Character_Load(owner.ID, ci, id, ref cown, out tran, out con))
                {
                    if (!OnCharacterLoading(con, tran, ci, ref rsultMsg))
                    {
                        tran.Rollback();
                    }
                    else
                    {
                        tran.Commit();
                    }
                }
                else
                {
                    rsultMsg = "Character doesn't exist.";
                    return(null);
                }
            }
            catch (Exception e)
            {
                return(null);
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                    con.Dispose();
                    con = null;
                }
                if (tran != null)
                {
                    tran.Dispose();
                    tran = null;
                }
            }
            return(ci);
        }
Esempio n. 14
0
        /// <summary>
        /// creates a character object, but does not persist it.
        /// </summary>
        /// <param name="properties">character properties to add</param>
        /// <param name="owner">the owning user</param>
        /// <returns></returns>
        public ServerCharacterInfo CreateNewCharacter(PropertyBag properties, ServerUser owner)
        {
            CharacterInfo shell = CreateNewCharacterShell();

            if (properties != null)
            {
                shell.Properties.UpdateWithValues(properties);
            }

            ServerCharacterInfo ci = new ServerCharacterInfo(shell);

            ci.ID            = NextCharId;
            ci.Properties    = shell.Properties;
            ci.Stats         = shell.Stats;
            ci.OwningAccount = owner;

            return(ci);
        }
        private void OnPlayerJoinGame(INetworkConnection con, Packet gmsg)
        {
            PacketGenericMessage genMsg = gmsg as PacketGenericMessage;

            if (!ValidateHasCurrentCharacter())
            {
                return;
            }

            Guid gameId            = genMsg.Parms.GetGuidProperty((int)PropertyID.GameId);
            ServerCharacterInfo ci = ServerUser.CurrentCharacter;

            string address = "";
            int    port    = 0;
            string name    = "";

            Log1.Logger(MyServer.ServerUserID).Info(string.Format("Player {0} requesting join content '{1}'...", ServerUser.AccountName, gameId.ToString()));

            if (DB.Instance.Lobby_GetGameServer(gameId, out address, out port, out name) && address.Length > 0 && port > 0)
            {
                Log.LogMsg(string.Format("Transferring Player {0} to join content '{1}' on server @ {2} ...", ServerUser.AccountName, gameId.ToString(), address));

                PacketMatchNotification note = (PacketMatchNotification)CreatePacket((int)LobbyPacketType.MatchNotification, 0, false, false);
                note.Kind         = MatchNotificationType.PlayerAdded;
                note.TargetPlayer = ci.CharacterInfo;
                note.Parms        = genMsg.Parms;
                note.ReplyCode    = ReplyType.OK;
                Send(note);

                ServerUser.TransferToServerUnassisted(address, port, gameId, name, name);
            }
            else
            {
                Log.LogMsg(string.Format("Player {0} failed to join content '{1}' : {2} ...", ServerUser.AccountName, gameId.ToString(), "Couldn't find game. Join canceled."));
                PacketMatchNotification note = (PacketMatchNotification)CreatePacket((int)LobbyPacketType.MatchNotification, 0, false, false);
                note.ReplyMessage  = "Game couldn't be found. Strange...";
                note.Kind          = MatchNotificationType.PlayerAdded;
                note.TargetPlayer  = ci.CharacterInfo;
                note.Parms         = genMsg.Parms;
                note.ReplyCode     = ReplyType.Failure;
                genMsg.ReplyPacket = note;
                return;
            }
        }
        private void OnCreateNewGame(INetworkConnection con, Packet gmsg)
        {
            PacketGenericMessage    genMsg = gmsg as PacketGenericMessage;
            PacketMatchNotification note   = (PacketMatchNotification)CreatePacket((int)LobbyPacketType.MatchNotification, 0, false, false);

            note.Kind       = MatchNotificationType.MatchCreated;
            note.NeedsReply = false;

            if (!ValidateHasCurrentCharacter())
            {
                genMsg.ReplyPacket = note;
                note.ReplyMessage  = "You must select a character before you can create a new game.";
                note.ReplyCode     = ReplyType.Failure;
                return;
            }

            //
            // <h2 style="text-align: center"><span style="color: #993300;"><a href="http://www.survivalnotes.org/content/category/fire"><span style="color: #993300;">Latest Entries</span></a>           <a href="http://www.survivalnotes.org/content/category/fire?r_sortby=highest_rated&amp;r_orderby=desc"><span style="color: #993300;">Highest Rated Entries</span></a></span></h2>
            // <h2 style="text-align: center"><span style="color: #993300;"><a href="http://www.survivalnotes.org/content/category/fire"><span style="color: #993300;">Latest Entries</span></a>           &nbsp;&nbsp;&nbsp;&nbsp;             <a href="http://www.survivalnotes.org/content/category/fire?r_sortby=highest_rated&amp;r_orderby=desc"><span style="color: #993300;">Highest Rated Entries</span></a></span></h2>
            //

            Log1.Logger(MyServer.ServerUserID).Info(string.Format("Player {0} requesting create new game '{1}' ...", ServerUser.AccountName, genMsg.Parms.GetStringProperty((int)PropertyID.Name)));
            string msg = "";

            GameServerInfo <OutboundServerConnection> gsi = RequestCreateNewGameServer(out msg);

            genMsg.ReplyPacket = note;
            note.ReplyMessage  = msg;
            if (gsi == null)
            {
                // Failed. Either no servers online, or they are full.
                note.ReplyCode = ReplyType.Failure;
                return;
            }
            else
            {
                // Contact that server and request a game be created.

                note.ReplyCode = ReplyType.OK;
                ServerUser.TransferToServerUnassisted(gsi.IP, gsi.Port, Guid.Empty, gsi.Name, gsi.UserID);
            }
        }
Esempio n. 17
0
        public static void UnAuthorizeUser(ServerUser client, bool persist)
        {
            lock (m_AuthorizedAccountsSyncRoot)
            {
                if (client.AccountName == null || client.ID == null)
                {
                    return;
                }

                // Remove from local authorized clients list
                AuthorizedAccounts.Remove(client.AccountName.ToLower());

                // if we persist the unauthorization, the client will have to go through the login server again.
                if (persist)
                {
                    DB.Instance.User_UnauthorizeSession(client.AccountName);
                }
                Log1.Logger("Server").Debug("Unauthorized account [" + client.AccountName + "] and auth ticket [" + client.AuthTicket.ToString() + "]. [" + AuthorizedAccounts.Count.ToString() + "] authorized accounts left in cache.");
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Phase 2: Player requests to play on a specified game server.  This method forwards that request to the game server.
        /// </summary>
        private void OnClusterHandoffRequest(INetworkConnection con, Packet msg)
        {
            PacketRequestHandoffToServerCluster packetRequestHandoffToServer = msg as PacketRequestHandoffToServerCluster;

            if (!ServerUser.IsAuthenticated)
            {
                KillConnection(" [" + ServerUser.AccountName + "] requested server hand off to [" + packetRequestHandoffToServer.TargetServerName + "] without being authenticated.");
            }

            GameServerInfo <OutboundServerConnection> gsi = GetServerInfo(packetRequestHandoffToServer.TargetServerName);

            if (gsi == null) // cluster offline or at capacity?
            {
                PacketGameServerTransferResult p = (PacketGameServerTransferResult)CreatePacket((int)PacketType.PacketGameServerAccessGranted, 0, true, true);
                p.ReplyMessage = "Game service not currently available.";
                p.ReplyCode    = ReplyType.Failure;

                // send an updated listing of online servers
                string servers = "";
                foreach (GameServerInfoGroup gr in MyServer.OutboundServerGroups.Groups.Values)
                {
                    string serverInfo = gr.ID + "," + gr.HasLiveOutboundServerConnections;
                    servers += "|" + serverInfo;
                }

                servers = servers.Trim('|');
                p.Parms.SetProperty((int)PropertyID.ServerListing, servers);

                msg.ReplyPacket = p;
                return;
            }

            Log1.Logger("LoginServer.Inbound.Login").Info("Player " + ServerUser.AccountName + " is requesting handoff to game server " + gsi.Name);

            // request auth ticket from game server

            Log1.Logger("LoginServer.Inbound.Login").Debug("Requesting authenticated client *" + ServerUser.AccountName + "* (" + RemoteIP + ") to be handed off to server group " + packetRequestHandoffToServer.TargetServerName + ".");
            ServerUser.TransferToServerUnassisted(gsi.IP, gsi.Port, Guid.Empty, gsi.UserID, gsi.Name);
            //gsi.Connection.RequestPlayerHandoff(ServerUser.ID, ServerUser.AccountName, packetRequestHandoffToServer.TargetResource, ServerUser.Profile, null, "");
        }
Esempio n. 19
0
        public override void Deserialize(byte[] data, Pointer p, bool includeComponents)
        {
            m_CharacterInfo = new Shared.CharacterInfo();
            m_CharacterInfo.Deserialize(data, p, includeComponents);

            ServerUser su = new ServerUser();

            su.AuthTicket = Guid.Empty;

            su.OwningServer = BitPacker.GetString(data, p);
            su.ID           = new Guid(BitPacker.GetString(data, p));
            su.AccountName  = BitPacker.GetString(data, p);

            su.Profile = (AccountProfile)BitPacker.GetSerializableWispObject(data, p);

            su.CurrentCharacter = this;
            this.TargetResource = new Guid(BitPacker.GetString(data, p));

            OwningAccount = su;

            base.Deserialize(data, p, includeComponents);
        }
Esempio n. 20
0
        /// <summary>
        /// Transfers a player back to Central.
        /// </summary>
        /// <param name="targetPlayer">the player to transfer</param>
        /// <param name="reason">a reason message that will be packaged in the GameEnded message.  If the game has already ended and that is why we are transferring the player, this paramter will be ignored.</param>
        public void TransferPlayerToCentral(ServerCharacterInfo targetPlayer, string reason)
        {
            ServerUser su = (targetPlayer == null) ? null : targetPlayer.OwningAccount;

            if (su == null)
            {
                return;
            }

            RemovePlayer(targetPlayer, reason, false);

            if (su.MyConnection != null && su.MyConnection.IsAlive)
            {
                // Remove player, called in line above, uses the PFX queue and we need Remove player to go off before the transfer directive - otherwise the client
                // won't get the game end message if it needs one and will thus not display the game summary.  Thus, we need to add the transfer directives to the PFX
                // queue (after the RemovePlayer call).
                //Task t = new Task((state) =>
                {
                    ((GSLobbyInboundPlayerConnection)su.MyConnection).TransferToLobbyOrDisconnect();
                }//, "Transfer Player " + targetPlayer.ToString(), TaskCreationOptions.LongRunning);
                 //m_NetQ.AddTask(t);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Adds an entry to the DB listing of which servers are hosting which game.
        /// </summary>
        /// <param name="db"></param>
        /// <param name="owningClusterServerId"></param>
        /// <param name="gameId"></param>
        /// <param name="createdOnUTC"></param>
        /// <param name="createdByCharacter"></param>
        /// <returns></returns>
        public static bool Lobby_TrackGameForServer(this DB db, string owningClusterServerId, IGame game, DateTime createdOnUTC, ServerUser createdByCharacter)
        {
            bool          result = true;
            SqlConnection con    = DB.SessionDataConnection;

            SqlCommand cmd = DB.GetCommand(con, "Lobby_AddGameToServerMap", true);

            cmd.Parameters.Add(new SqlParameter("@ClusterServerID", owningClusterServerId));
            cmd.Parameters.Add(new SqlParameter("@GameID", game.GameID));
            cmd.Parameters.Add(new SqlParameter("@CreatedOn", createdOnUTC));
            cmd.Parameters.Add(new SqlParameter("@CreatedByCharacter", createdByCharacter.CurrentCharacter.CharacterInfo.ID));

            if (game.Name.Length > 512)
            {
                game.Name = game.Name.Substring(0, 512);
            }

            cmd.Parameters.Add(new SqlParameter("@GameName", game.Name));
            cmd.Parameters.Add(new SqlParameter("@MaxPlayers", game.MaxPlayers));

            SqlTransaction tran = null;

            try
            {
                con.Open();
                tran            = con.BeginTransaction(IsolationLevel.ReadCommitted);
                cmd.Connection  = con;
                cmd.Transaction = tran;
                cmd.ExecuteNonQuery();

                if (OnTrackGame != null && !OnTrackGame(owningClusterServerId, game, createdByCharacter, con, tran))
                {
                    tran.Rollback();
                    return(false);
                }

                tran.Commit();
            }
            catch (Exception e)
            {
                Log1.Logger("Server").Error("Failed to trac new game for server [" + owningClusterServerId + "], create by character ID [" + createdByCharacter + "] in database.", e);
                if (con.State != System.Data.ConnectionState.Closed && con.State != System.Data.ConnectionState.Connecting)
                {
                    if (tran != null)
                    {
                        tran.Rollback();
                    }
                }
                return(false);
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                    con.Dispose();
                    con = null;
                }

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

            return(result);
        }
Esempio n. 22
0
 public ServerCharacterInfo(CharacterInfo characterInfo, ServerUser owner)
 {
     OwningAccount   = owner;
     m_CharacterInfo = characterInfo;
     OnInitialize();
 }
Esempio n. 23
0
 /// <summary>
 /// Override to handle player transfer/handoff requests.  If this method is not overridden, ALL players will be able to connect.  If you wish
 /// to deny player login, return Guid.Empty, otherwise generate a new authentication ticket GUID and optionally track it at your leisure.
 /// </summary>
 /// <param name="player">the user that represents the account wanting to log in</param>
 /// <returns>The authentication ticket. Return Guid.Empty to deny login, otherwise return a new GUID</returns>
 public virtual Guid OnPlayerConnectionRequest(ServerUser player, ref string msg)
 {
     return(Guid.NewGuid());
 }
Esempio n. 24
0
        /// <summary>
        /// Gets called when we get a response to RequestPlayerHandoff().  Base method forwards a PacketGameServerAccessGranted packet to the player.
        /// Don't call the base method if you don't want that packet sent.
        /// </summary>
        protected virtual void OnPlayerHandoffResponseReceived(PacketPlayerAuthorizedForTransfer msg, ServerUser user)
        {
            if (user != null && RemoteEndPoint != null)
            {
                string     targetServer = "";
                IPEndPoint ep           = RemoteEndPoint as IPEndPoint;

                if (msg.ReplyCode == ReplyType.OK)
                {
                    targetServer = ServerUserID == null ? "Unknown Server User ID" : ServerUserID;
                }

                user.TransferToServerAssisted(
                    ep.Address.ToString(),
                    ep.Port,
                    msg.AuthTicket,
                    msg.TargetResource,
                    Name == null ? "" : Name,
                    targetServer,
                    msg.ReplyMessage,
                    msg.ReplyCode);
            }
        }
        protected override bool OnCharacterDeleting(SqlConnection con, SqlTransaction tran, int characterId, ServerUser owner)
        {
            bool rslt = CharacterUtil.Instance.DeleteCharacter_TSRating(characterId, con, tran);

            if (rslt)
            {
                return(base.OnCharacterDeleting(con, tran, characterId, owner));
            }

            return(false);
        }
Esempio n. 26
0
        /// <summary>
        /// Creates a new character in the DB using the character template XML file as a basis for stats and properties.  If you want to override any of the default
        /// properties, pass in the appropriate characterProperties property bag.
        /// </summary>
        /// <param name="msg">an error message, if any</param>
        /// <returns></returns>
        public bool PersistNewCharacter(ServerCharacterInfo ci, ServerUser owner, ref string msg, bool isTempCharacter)
        {
            SqlConnection  con  = null;
            SqlTransaction tran = null;

            try
            {
                if (ValidateCharacterCreateRequest(ci, ref msg))
                {
                    int maxCharacters = (int)owner.Profile.MaxCharacters;
                    if (maxCharacters < 1)
                    {
                        maxCharacters = 1;
                    }
                    int newCharId = 0;
                    if (DB.Instance.Character_Create(owner.ID, ci.Stats, ci.Properties, (int)PropertyID.Name, ci.CharacterName, true, maxCharacters, isTempCharacter, out msg, out tran, out con, out newCharId))
                    {
                        ci.CharacterInfo.ID = newCharId;
                        if (OnCharacterPersiting(con, tran, ci))
                        {
                            tran.Commit();
                        }
                        else
                        {
                            tran.Rollback();
                        }
                        return(true);
                    }
                    else
                    {
                        if (con.State != System.Data.ConnectionState.Closed && con.State != System.Data.ConnectionState.Connecting)
                        {
                            if (tran != null)
                            {
                                tran.Rollback();
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                if (con.State != System.Data.ConnectionState.Closed && con.State != System.Data.ConnectionState.Connecting)
                {
                    if (tran != null)
                    {
                        tran.Rollback();
                    }
                }
                return(false);
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                    con.Dispose();
                    con = null;
                }

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

            return(false);
        }
Esempio n. 27
0
        /// <summary>
        /// Gets called as the character is being created in the Database.  If you have additional DB tasks
        /// to add, now is the time.  Use the supplied connection and transaction objects.  The connection should already
        /// be open.
        /// Do NOT close the connection and do NOT commit /rollback the transaction.  Simply return true or false if
        /// you want the creation to be committed or not.
        /// </summary>
        /// <param name="characterId">the id of the character to delete</param>
        /// <param name="owner">the owner of the character to delete</param>
        /// <param name="permaPurge">should the data be permanently purged</param>
        /// <param name="reason">reason for service log</param>
        /// <param name="rsltMsg">a message saying why deletion failed, if any</param>
        /// <param name="con">the connection object to use for additional database work in relation to character creation</param>
        /// <param name="tran">the transaction object to use for additional database work in relation to character creation</param>
        /// <returns>return false if you do not want the transaction to be committed, which will also cause character creation to fail</returns>
        public bool DeleteCharacter(int characterId, ServerUser owner, bool permaPurge, string reason, ref string rsltMsg)
        {
            SqlConnection  con  = null;
            SqlTransaction tran = null;

            try
            {
                if (DB.Instance.Character_Delete(owner.ID, characterId, permaPurge, reason, out tran, out con))
                {
                    if (OnCharacterDeleting(con, tran, characterId, owner))
                    {
                        tran.Commit();
                    }
                    else
                    {
                        tran.Rollback();
                        rsltMsg = "Unknown failure deleting character.";
                        return(false);
                    }
                    return(true);
                }
                else
                {
                    if (con.State != System.Data.ConnectionState.Closed && con.State != System.Data.ConnectionState.Connecting)
                    {
                        if (tran != null)
                        {
                            tran.Rollback();
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                if (con.State != System.Data.ConnectionState.Closed && con.State != System.Data.ConnectionState.Connecting)
                {
                    if (tran != null)
                    {
                        tran.Rollback();
                    }
                }
                return(false);
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                    con.Dispose();
                    con = null;
                }

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

            return(false);
        }
Esempio n. 28
0
        /// <summary>
        /// Returns the authorized user object, or null if the user isn't currently authorized
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public static ServerUser GetAuthorizedUser(string account, ServerBase server, PacketLoginRequest.ConnectionType conType)
        {
            ServerUser u = null;

            if (conType == PacketLoginRequest.ConnectionType.AssistedTransfer)
            {
                lock (m_AuthorizedAccountsSyncRoot)
                {
                    AuthorizedAccounts.TryGetValue(account.ToLower(), out u);
                }
            }

            else if (conType == PacketLoginRequest.ConnectionType.UnassistedTransfer)
            {
                Guid     ticket         = Guid.Empty;
                string   authServer     = "";
                DateTime whenAuthd      = DateTime.MinValue;
                int      character      = -1;
                string   targetServerID = "";
                Guid     accountID      = Guid.Empty;
                if (!DB.Instance.User_GetAuthorizationTicket(account, out authServer, out ticket, out whenAuthd, out character, out targetServerID, out accountID) || ticket == Guid.Empty)
                {
                    return(null);
                }

                if (targetServerID != server.ServerUserID)
                {
                    // we weren't authorized to be on this server.
                    Log1.Logger(server.ServerUserID).Error("[" + account + "] attempted unassisted transfer to [" + server.ServerUserID + "], but that user was only authorized to transfer to target server ID [" + targetServerID + "]. Connection denied.");
                    return(null);
                }

                if (whenAuthd + AuthTicketLifetime < DateTime.UtcNow)
                {
                    // ticket expired.
                    Log1.Logger(server.ServerUserID).Error("[" + account + "] attempted unassisted transfer to [" + server.ServerUserID + "], but that user's auth ticket is expired. Connection denied.");
                    return(null);
                }

                // Got a ticket.  Load up the user from the DB.
                u = new ServerUser();

                u.OwningServer = server.ServerUserID;
                u.AuthTicket   = ticket;
                u.ID           = accountID;
                u.AccountName  = account;


                // load the profile
                AccountProfile ap = new AccountProfile(account);
                u.Profile = ap;
                ap.Load(server.RequireAuthentication);

                // load the character
                if (character > -1)
                {
                    string msg = "";
                    u.CurrentCharacter = CharacterUtil.Instance.LoadCharacter(u, character, ref msg);
                    if (u.CurrentCharacter == null)
                    {
                        // Couldn't load character.
                        Log1.Logger(server.ServerUserID).Error("[" + account + "] attempted unassisted transfer with characer [" + character + "], but that character could not be loaded from the DB: [" + msg + "]. Connection denied.");
                        return(null);
                    }
                    u.CurrentCharacter.OwningAccount = u;
                    CharacterCache.CacheCharacter(u.CurrentCharacter, server.ServerUserID);
                }
            }

            AuthorizeUser(u); // gotta call this to activate/renew the auth ticket on this server.
            return(u);
        }
Esempio n. 29
0
 public static void UnAuthorizeUser(ServerUser client)
 {
     UnAuthorizeUser(client, true);
 }
Esempio n. 30
0
 /// <summary>
 /// Adds the user's account to the authorized users list.  This method should also disconnect any previous sockets that might be connected using the same account
 /// </summary>
 /// <param name="client"></param>
 /// <returns></returns>
 public static bool AuthorizeUser(ServerUser client)
 {
     return(AuthorizeUser(client, ServerBase.UseDatabaseConnectivity));
 }