Exemple #1
0
        /// <summary>
        /// 33 - "@a"
        /// </summary>
        private void SendMsg()
        {
            uint   buddyID = Request.PopWireduint();
            string sText   = Request.PopFixedString();

            // Buddy in list?
            if (mSession.GetMessenger().GetBuddy(buddyID) != null)
            {
                // Buddy online?
                GameClient buddyClient = IonEnvironment.GetHabboHotel().GetClients().GetClientOfHabbo(buddyID);
                if (buddyClient == null)
                {
                    Response.Initialize(ResponseOpcodes.InstantMessageError); // Opcode
                    Response.AppendInt32(5);                                  // Error code
                    Response.AppendUInt32(mSession.GetHabbo().ID);
                    SendResponse();
                }
                else
                {
                    ServerMessage notify = new ServerMessage(ResponseOpcodes.NewConsole);
                    notify.AppendUInt32(mSession.GetHabbo().ID);
                    notify.AppendString(sText);
                    buddyClient.GetConnection().SendMessage(notify);
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Closes the connections of database clients that have been inactive for too long. Connections can be opened again when needed.
        /// </summary>
        private void MonitorClientsLoop()
        {
            while (true)
            {
                try
                {
                    lock (this)
                    {
                        DateTime dtNow = DateTime.Now;
                        for (int i = 0; i < mClients.Length; i++)
                        {
                            if (mClients[i].State != ConnectionState.Closed)
                            {
                                if (mClients[i].Inactivity >= 60) // Not used in the last %x% seconds
                                {
                                    mClients[i].Disconnect();     // Temporarily close connection

                                    IonEnvironment.GetLog().WriteInformation("Disconnected database client #" + mClients[i].Handle);
                                }
                            }
                        }
                    }

                    Thread.Sleep(10000); // 10 seconds
                }
                catch (ThreadAbortException) { } // Nothing special
                catch (Exception ex)
                {
                    IonEnvironment.GetLog().WriteError(ex.Message);
                }
            }
        }
Exemple #3
0
        public void ReloadRights()
        {
            mRights.Clear();
            using (DatabaseClient dbClient = IonEnvironment.GetDatabase().GetClient())
            {
                // Search for all roles
                for (byte role = 0; role <= mMaxRoles; role++)
                {
                    // Get rights for roles (and roles inherited)
                    DataTable result = dbClient.ReadDataTable("SELECT userright FROM access_userrights WHERE role <= " + role.ToString() + ";");
                    if (result.Rows.Count > 0)
                    {
                        // Shove rights to a string array
                        string[] rights = new string[result.Rows.Count];
                        for (int position = 0; position < result.Rows.Count; position++)
                        {
                            rights[position] = (string)result.Rows[position]["userright"];
                        }

                        // Add rights for this role to the dictionary
                        mRights.Add(role, rights);
                    }
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Constructs a Habbo Hotel environment and tries to initialize it.
        /// </summary>
        public HabboHotel()
        {
            // Try to parse version
            IonEnvironment.Configuration.TryParseUInt32("projects.habbo.client.version", out mVersion);

            // Initialize HabboHotel project modules
            mExternalTexts      = new KeyValueDictionary("external_texts", "xkey", "xvalue");
            mExternalVariables  = new KeyValueDictionary("external_variables", "xkey", "xvalue");
            mClientManager      = new GameClientManager();
            mHabboManager       = new HabboManager();
            mAuthenticator      = new HabboAuthenticator();
            mUserRightManager   = new UserRightManager(20);
            mAchievementManager = new AchievementManager();
            mMessengerManager   = new MessengerManager();
            mCatalog            = new Catalog.Catalog();

            // Start connection checker for clients
            mClientManager.StartConnectionChecker();

            // Load external texts and external variables
            mExternalTexts.Reload();
            mExternalVariables.Reload();

            // Load user rights
            mUserRightManager.ReloadRights();

            // Load catalog
            mCatalog.ReloadPages();

            // Print that we are done!
            IonEnvironment.GetLog().WriteLine(string.Format("Initialized project 'Habbo Hotel' for version {0}.", mVersion));
        }
Exemple #5
0
 public void ReleaseClient(uint Handle)
 {
     if (mClients.Length >= (Handle - 1)) // Ensure client exists
     {
         mClientAvailable[Handle - 1] = true;
         IonEnvironment.GetLog().WriteLine("Released client #" + Handle);
     }
 }
Exemple #6
0
        /// <summary>
        /// Handles a given amount of data in a given byte array, by attempting to parse messages from the received data and process them in the message handler.
        /// </summary>
        /// <param name="Data">The byte array with the data to process.</param>
        /// <param name="numBytesToProcess">The actual amount of bytes in the byte array to process.</param>
        public void HandleConnectionData(ref byte[] data)
        {
            // Gameclient protocol or policyrequest?
            if (data[0] != 64)
            {
                IonEnvironment.GetLog().WriteInformation("Client " + mID + " sent non-gameclient message: " + IonEnvironment.GetDefaultTextEncoding().GetString(data));

                string xmlPolicy =
                    "<?xml version=\"1.0\"?>\r\n" +
                    "<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\">\r\n" +
                    "<cross-domain-policy>\r\n" +
                    "<allow-access-from domain=\"*\" to-ports=\"1-31111\" />\r\n" +
                    "</cross-domain-policy>\x0";

                IonEnvironment.GetLog().WriteInformation("Client " + mID + ": sending XML cross domain policy file: " + xmlPolicy);
                mConnection.SendData(xmlPolicy);

                mMessageHandler.GetResponse().Initialize(ResponseOpcodes.SecretKey); // "@A"
                mMessageHandler.GetResponse().Append("ION/Deltar");
                mMessageHandler.SendResponse();
            }
            else
            {
                int pos = 0;
                while (pos < data.Length)
                {
                    try
                    {
                        // Total length of message (without this): 3 Base64 bytes
                        int messageLength = Base64Encoding.DecodeInt32(new byte[] { data[pos++], data[pos++], data[pos++] });

                        // ID of message: 2 Base64 bytes
                        uint messageID = Base64Encoding.DecodeUInt32(new byte[] { data[pos++], data[pos++] });

                        // Data of message: (messageLength - 2) bytes
                        byte[] Content = new byte[messageLength - 2];
                        for (int i = 0; i < Content.Length; i++)
                        {
                            Content[i] = data[pos++];
                        }

                        // Create message object
                        ClientMessage message = new ClientMessage(messageID, Content);

                        // Handle message object
                        mMessageHandler.HandleRequest(message);
                    }
                    catch (IndexOutOfRangeException) // Bad formatting!
                    {
                        IonEnvironment.GetHabboHotel().GetClients().StopClient(mID);
                    }
                    catch (Exception ex)
                    {
                        IonEnvironment.GetLog().WriteUnhandledExceptionError("GameClient.HandleConnectionData", ex);
                    }
                }
            }
        }
 public bool HasAchievement(uint userID, string sAchievement)
 {
     using (DatabaseClient dbClient = IonEnvironment.GetDatabase().GetClient())
     {
         dbClient.AddParamWithValue("@userid", userID);
         dbClient.AddParamWithValue("@achievement", sAchievement);
         return(dbClient.ReadInt32("SELECT COUNT(userID) FROM users_achievements WHERE userid = @userid AND achievement = @achievement LIMIT 1;") > 0);
     }
 }
Exemple #8
0
        /// <summary>
        /// Attempts to save the Habbo DataObject of this session to the Database.
        /// </summary>
        public bool SaveUserObject()
        {
            if (mHabbo != null)
            {
                return(IonEnvironment.GetHabboHotel().GetHabbos().UpdateHabbo(mHabbo));
            }

            return(false);
        }
Exemple #9
0
        /// <summary>
        /// Reads a length prefixed string from the message content and encodes it with a given System.Text.Encoding.
        /// </summary>
        /// <param name="pEncoding">The System.Text.Encoding to encode the string with.</param>
        /// <returns>String</returns>
        public String PopFixedString(Encoding pEncoding)
        {
            if (pEncoding == null)
            {
                pEncoding = IonEnvironment.GetDefaultTextEncoding();
            }

            return(pEncoding.GetString(this.ReadFixedValue()));
        }
Exemple #10
0
 public void RemoveAchievement(uint userID, string sAchievement)
 {
     using (DatabaseClient dbClient = IonEnvironment.GetDatabase().GetClient())
     {
         dbClient.AddParamWithValue("@userid", userID);
         dbClient.AddParamWithValue("@achievement", sAchievement);
         dbClient.ExecuteQuery("DELETE FROM users_achievements WHERE userid = @userid AND achievement = @achievement;");
     }
 }
Exemple #11
0
 public void AddAchievement(uint userID, string sAchievement)
 {
     using (DatabaseClient dbClient = IonEnvironment.GetDatabase().GetClient())
     {
         dbClient.AddParamWithValue("@userid", userID);
         dbClient.AddParamWithValue("@achievement", sAchievement);
         dbClient.ExecuteQuery("INSERT INTO users_achievements(userid,achievement) VALUES (@userid,@achievement);");
     }
 }
Exemple #12
0
        public void Destroy()
        {
            // Clear clients
            if (GetClients() != null)
            {
                GetClients().Clear();
                GetClients().StopConnectionChecker();
            }

            IonEnvironment.GetLog().WriteLine(string.Format("Destroyed project 'Habbo Hotel' for version {0}.", mVersion));
        }
Exemple #13
0
        public bool TryParseUInt32(string sField, out uint i)
        {
            bool Success = uint.TryParse(this[sField], out i);

            if (!Success)
            {
                IonEnvironment.GetLog().WriteConfigurationParseError(sField);
            }

            return(Success);
        }
        public void DropConnection(uint clientID)
        {
            IonTcpConnection connection = GetConnection(clientID);

            if (connection != null)
            {
                IonEnvironment.GetLog().WriteInformation("Dropped IonTcpConnection [" + clientID + "] of " + connection.ipAddress);

                connection.Stop();
                mConnections.Remove(clientID);
            }
        }
Exemple #15
0
        private void DataReceived(IAsyncResult iAr)
        {
            // Connection not stopped yet?
            if (this.Alive == false)
            {
                return;
            }

            // Do an optional wait before processing the data
            if (RECEIVEDATA_MILLISECONDS_DELAY > 0)
            {
                Thread.Sleep(RECEIVEDATA_MILLISECONDS_DELAY);
            }

            // How many bytes has server received?
            int numReceivedBytes = 0;

            try
            {
                numReceivedBytes = mSocket.EndReceive(iAr);
            }
            catch (ObjectDisposedException)
            {
                ConnectionDead();
                return;
            }
            catch (Exception ex)
            {
                IonEnvironment.GetLog().WriteUnhandledExceptionError("IonTcpConnection.DataReceived", ex);

                ConnectionDead();
                return;
            }

            if (numReceivedBytes > 0)
            {
                // Copy received data buffer
                byte[] dataToProcess = ByteUtility.ChompBytes(mDataBuffer, 0, numReceivedBytes);

                // Decipher received data?
                if (mEncryptionStarted)
                {
                    dataToProcess = mRc4.Decipher(dataToProcess, numReceivedBytes);
                }

                // Route data to GameClient to parse and process messages
                RouteData(ref dataToProcess);
                //Environment.GetHabboHotel().GetClients().GetClient(this.ID).HandleConnectionData(ref dataToProcess);
            }

            // Wait for new data
            WaitForData();
        }
Exemple #16
0
        /// <summary>
        /// Encodes a string with a given text encoding and appends it to the message content.
        /// </summary>
        /// <param name="s">The string to append.</param>
        /// <param name="pEncoding">A System.Text.Encoding to use for encoding the string.</param>
        public void Append(string s, Encoding pEncoding)
        {
            if (s != null && s.Length > 0)
            {
                if (pEncoding == null)
                {
                    pEncoding = IonEnvironment.GetDefaultTextEncoding();
                }

                Append(pEncoding.GetBytes(s));
            }
        }
        /// <summary>
        /// Handles a newly created IonTcpConnection and performs some checks, before adding it to the connection collection and starting the client session.
        /// </summary>
        /// <param name="connection">The IonTcpConnection instance representing the new connection to handle.</param>
        public void HandleNewConnection(IonTcpConnection connection)
        {
            // TODO: check max simultaneous connections
            // TODO: check max simultaneous connections per IP
            // TODO: check project specific actions

            // INFO: client ID = connection ID, client ID = session ID
            // Add connection to collection
            mConnections.Add(connection.ID, connection);

            // Create session for new client
            IonEnvironment.GetHabboHotel().GetClients().StartClient(connection.ID);
        }
Exemple #18
0
        /// <summary>
        /// Creates an IonTcpConnection instance for a given socket and assigns it an unique ID.
        /// </summary>
        /// <param name="pSocket">The System.Net.Socket.Sockets object to base the connection on.</param>
        /// <returns>IonTcpConnection</returns>
        public IonTcpConnection CreateConnection(Socket pSocket)
        {
            if (pSocket == null)
            {
                return(null);
            }

            IonTcpConnection connection = new IonTcpConnection(++mConnectionCounter, pSocket);

            IonEnvironment.GetLog().WriteInformation(string.Format("Created IonTcpConnection [{0}] for {1}.", connection.ID, connection.ipAddress));

            return(connection);
        }
Exemple #19
0
        public Habbo GetHabbo(string sUsername)
        {
            // TODO: some sort of cache?

            Habbo habbo = new Habbo();

            if (habbo.LoadByUsername(IonEnvironment.GetDatabase(), sUsername))
            {
                return(habbo);
            }

            return(null);
        }
Exemple #20
0
        /// <summary>
        /// Attempts to reload the Habbo DataObject of this session from the Database. If no DataObject is found anymore, the old one is kept.
        /// </summary>
        public bool ReloadUserObject()
        {
            if (mHabbo != null)
            {
                Habbo newObject = IonEnvironment.GetHabboHotel().GetHabbos().GetHabbo(mHabbo.ID);
                if (newObject != null)
                {
                    mHabbo = newObject;
                    return(true);
                }
            }

            return(false);
        }
Exemple #21
0
        /// <summary>
        /// 370 - "Er"
        /// </summary>
        private void GetAchievements()
        {
            // Get achievements from Database
            List <string> achievements = IonEnvironment.GetHabboHotel().GetAchievements().GetAchievements(mSession.GetHabbo().ID);

            // Build response
            Response.Initialize(ResponseOpcodes.Achievements); // "Ce"
            Response.AppendInt32(achievements.Count);
            foreach (string achievement in achievements)
            {
                Response.AppendString(achievement);
            }
            SendResponse();
        }
Exemple #22
0
        public List <string> GetAchievements(uint userID)
        {
            List <string> achievements = new List <string>();

            using (DatabaseClient dbClient = IonEnvironment.GetDatabase().GetClient())
            {
                dbClient.AddParamWithValue("@userid", userID);
                foreach (DataRow row in dbClient.ReadDataTable("SELECT achievement FROM users_achievements WHERE userid = @userid;").Rows)
                {
                    achievements.Add((string)row["achievement"]);
                }
            }

            return(achievements);
        }
Exemple #23
0
 public void ReloadBuddies()
 {
     mBuddies.Clear();
     using (DatabaseClient dbClient = IonEnvironment.GetDatabase().GetClient())
     {
         dbClient.AddParamWithValue("@userid", mClient.GetHabbo().ID);
         foreach (DataRow row in dbClient.ReadDataTable("SELECT id,username,figure,motto FROM users WHERE id IN(SELECT buddyid FROM messenger_buddylist WHERE userid = @userid AND accepted = 0x01) OR id IN(SELECT userid FROM messenger_buddylist WHERE buddyid = @userid AND accepted = 0x01);").Rows)
         {
             MessengerBuddy buddy = MessengerBuddy.Parse(row);
             if (buddy != null)
             {
                 mBuddies.Add(buddy);
             }
         }
     }
 }
Exemple #24
0
        public void Reload()
        {
            this.Clear();

            using (DatabaseClient dbClient = IonEnvironment.GetDatabase().GetClient())
            {
                foreach (DataRow row in dbClient.ReadDataTable("SELECT " + mKeyName + ", " + mValueName + " FROM " + mTableName + ";").Rows)
                {
                    string key   = (string)row[0];
                    string value = (string)row[1];
                    if (!mDictionary.ContainsKey(key))
                    {
                        mDictionary.Add(key, value);
                    }
                }
            }
        }
        /// <summary>
        /// Constructs an IonTcpConnection listener and binds it to a given local IP address and TCP port.
        /// </summary>
        /// <param name="sLocalIP">The IP address string to parse and bind the listener to.</param>
        /// <param name="Port">The TCP port number to parse the listener to.</param>
        public IonTcpConnectionListener(string sLocalIP, int Port, IonTcpConnectionManager pManager)
        {
            IPAddress pIP = null;

            if (!IPAddress.TryParse(sLocalIP, out pIP))
            {
                pIP = IPAddress.Loopback;
                IonEnvironment.GetLog().WriteWarning(string.Format("Connection listener was unable to parse the given local IP address '{0}', now binding listener to '{1}'.", sLocalIP, pIP.ToString()));
            }

            mListener = new TcpListener(pIP, Port);
            mConnectionRequestCallback = new AsyncCallback(ConnectionRequest);
            mFactory = new IonTcpConnectionFactory();
            mManager = pManager;

            IonEnvironment.GetLog().WriteLine(string.Format("IonTcpConnectionListener initialized and bound to {0}:{1}.", pIP.ToString(), Port.ToString()));
        }
Exemple #26
0
        /// <summary>
        /// Invokes the matching request handler for a given ClientMessage.
        /// </summary>
        /// <param name="request">The ClientMessage object to process.</param>
        public void HandleRequest(ClientMessage request)
        {
            IonEnvironment.GetLog().WriteLine("[" + mSession.ID + "] --> " + request.Header + request.GetContentString());

            if (request.ID > HIGHEST_MESSAGEID)
            {
                return; // Not in protocol
            }
            if (mRequestHandlers[request.ID] == null)
            {
                return; // Handler not registered
            }
            // Handle request
            Request = request;
            mRequestHandlers[request.ID].Invoke();
            Request = null;
        }
Exemple #27
0
        public Habbo Login(string sTicket)
        {
            // Do not use HabboManager.GetHabbo(string) here, as caching is planned to be implemented there
            Habbo habbo = new Habbo();

            if (!habbo.LoadBySsoTicket(IonEnvironment.GetDatabase(), sTicket))
            {
                throw new IncorrectLoginException("login incorrect: Wrong ticket");
            }
            else
            {
                // Drop old client (if logged in via other connection)
                IonEnvironment.GetHabboHotel().GetClients().KillClientOfHabbo(habbo.ID);

                return(habbo);
            }
        }
Exemple #28
0
        /// <summary>
        /// Tries to login this client on a Habbo account with a given username and password.
        /// </summary>
        /// <param name="sUsername">The username of the Habbo to attempt to login on.</param>
        /// <param name="sPassword">The login password of the Habbo username. Case sensitive.</param>
        public void Login(string sUsername, string sPassword)
        {
            try
            {
                // Try to login
                mHabbo = IonEnvironment.GetHabboHotel().GetAuthenticator().Login(sUsername, sPassword);

                // Authenticator has forced unique login now
                this.CompleteLogin();
            }
            catch (IncorrectLoginException exLogin)
            {
                SendClientError(exLogin.Message);
            }
            catch (ModerationBanException exBan)
            {
                SendBanMessage(exBan.Message);
            }
        }
Exemple #29
0
        public void StopClient(uint clientID)
        {
            GameClient client = GetClient(clientID);

            if (client != null)
            {
                // Stop & drop connection
                IonEnvironment.GetTcpConnections().DropConnection(clientID);

                // Stop client
                client.Stop();

                // Drop client
                mClients.Remove(clientID);

                // Log event
                IonEnvironment.GetLog().WriteInformation("Stopped client " + clientID);
            }
        }
Exemple #30
0
        public List <MessengerBuddy> SearchHabbos(string criteria)
        {
            List <MessengerBuddy> matches = new List <MessengerBuddy>();

            using (DatabaseClient dbClient = IonEnvironment.GetDatabase().GetClient())
            {
                dbClient.AddParamWithValue("@criteria", criteria + "%");
                foreach (DataRow row in dbClient.ReadDataTable("SELECT id,username,figure,motto FROM users WHERE username LIKE @criteria;").Rows)
                {
                    MessengerBuddy match = MessengerBuddy.Parse(row);
                    if (match != null)
                    {
                        matches.Add(match);
                    }
                }
            }

            return(matches);
        }