/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.Data.Common; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Services.Interfaces; using OpenSim.Framework.Console; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Services.UserAccountService { public class UserAccountService : UserAccountServiceBase, IUserAccountService, IOglPortalAccountProvisioner, IOglLocalAvatarDeletion { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static UserAccountService m_RootInstance; private readonly IConfigSource m_DeletionConfig; /// /// Should we create default entries (minimum body parts/clothing, avatar wearable entries) for a new avatar? /// private bool m_CreateDefaultAvatarEntries; private bool m_OglStarterTemplatesEnabled; private string m_OglBenjaminTemplate; private string m_OglLunaTemplate; private bool m_OglRequirePublishedModels; private string m_OglBenjaminPublishedModel; private string m_OglLunaPublishedModel; protected IGridService m_GridService; protected IAuthenticationService m_AuthenticationService; protected IGridUserService m_GridUserService; protected IInventoryService m_InventoryService; protected IAvatarService m_AvatarService; public UserAccountService(IConfigSource config) : base(config) { m_DeletionConfig = config; IConfig userConfig = config.Configs["UserAccountService"]; if (userConfig == null) throw new Exception("No UserAccountService configuration"); string gridServiceDll = userConfig.GetString("GridService", string.Empty); if (gridServiceDll != string.Empty) m_GridService = LoadPlugin(gridServiceDll, new Object[] { config }); string authServiceDll = userConfig.GetString("AuthenticationService", string.Empty); if (authServiceDll != string.Empty) m_AuthenticationService = LoadPlugin(authServiceDll, new Object[] { config }); string presenceServiceDll = userConfig.GetString("GridUserService", string.Empty); if (presenceServiceDll != string.Empty) m_GridUserService = LoadPlugin(presenceServiceDll, new Object[] { config }); string invServiceDll = userConfig.GetString("InventoryService", string.Empty); if (invServiceDll != string.Empty) m_InventoryService = LoadPlugin(invServiceDll, new Object[] { config }); string avatarServiceDll = userConfig.GetString("AvatarService", string.Empty); if (avatarServiceDll != string.Empty) m_AvatarService = LoadPlugin(avatarServiceDll, new Object[] { config }); m_CreateDefaultAvatarEntries = userConfig.GetBoolean("CreateDefaultAvatarEntries", false); IConfig starterConfig = config.Configs["OglAvatarTemplates"]; m_OglStarterTemplatesEnabled = starterConfig != null && starterConfig.GetBoolean("Enabled", false); m_OglBenjaminTemplate = starterConfig?.GetString("BenjaminModel", "Benjamin Resident") ?? "Benjamin Resident"; m_OglLunaTemplate = starterConfig?.GetString("LunaModel", "Luna Resident") ?? "Luna Resident"; // Published model accounts are dedicated, versioned source avatars. // They must not be used for ordinary logins or outfit editing. m_OglRequirePublishedModels = starterConfig == null || starterConfig.GetBoolean("RequirePublishedModels", true); m_OglBenjaminPublishedModel = starterConfig?.GetString("BenjaminPublishedModel", "") ?? ""; m_OglLunaPublishedModel = starterConfig?.GetString("LunaPublishedModel", "") ?? ""; if (m_RootInstance == null) { m_RootInstance = this; // create a system grid god account UserAccount ggod = GetUserAccount(UUID.Zero, Constants.servicesGodAgentID); if(ggod == null) { UserAccountData d = new UserAccountData(); d.FirstName = "GRID"; d.LastName = "SERVICES"; d.PrincipalID = Constants.servicesGodAgentID; d.ScopeID = UUID.Zero; d.Data = new Dictionary(); d.Data["Email"] = string.Empty; d.Data["Created"] = Util.UnixTimeSinceEpoch().ToString(); d.Data["UserLevel"] = "240"; d.Data["UserFlags"] = "0"; d.Data["ServiceURLs"] = string.Empty; m_Database.Store(d); } // In case there are several instances of this class in the same process, // the console commands are only registered for the root instance if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand("Users", false, "create user", "create user [ [ [ [ [ []]]]]]", "Create a new user", HandleCreateUser); MainConsole.Instance.Commands.AddCommand("Users", false, "delete user", "delete user [--confirm]", "Preview deletion of an offline avatar or irreversibly purge core local account data with --confirm", HandleDeleteUser); MainConsole.Instance.Commands.AddCommand("Users", false, "reset user password", "reset user password [ [ []]]", "Reset a user password", HandleResetUserPassword); MainConsole.Instance.Commands.AddCommand("Users", false, "reset user email", "reset user email [ [ []]]", "Reset a user email address", HandleResetUserEmail); MainConsole.Instance.Commands.AddCommand("Users", false, "set user level", "set user level [ [ []]]", "Set user level. If >= 200 and 'allow_grid_gods = true' in OpenSim.ini, " + "this account will be treated as god-moded. " + "It will also affect the 'login level' command. ", HandleSetUserLevel); MainConsole.Instance.Commands.AddCommand("Users", false, "show account", "show account ", "Show account details for the given user", HandleShowAccount); } } } #region IUserAccountService public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName) { // m_log.DebugFormat( // "[USER ACCOUNT SERVICE]: Retrieving account by username for {0} {1}, scope {2}", // firstName, lastName, scopeID); UserAccountData[] d; if (!scopeID.IsZero()) { d = m_Database.Get( new string[] { "ScopeID", "FirstName", "LastName" }, new string[] { scopeID.ToString(), firstName, lastName }); if (d.Length < 1) { d = m_Database.Get( new string[] { "ScopeID", "FirstName", "LastName" }, new string[] { UUID.Zero.ToString(), firstName, lastName }); } } else { d = m_Database.Get( new string[] { "FirstName", "LastName" }, new string[] { firstName, lastName }); } if (d.Length < 1) return null; return MakeUserAccount(d[0]); } private UserAccount MakeUserAccount(UserAccountData d) { UserAccount u = new UserAccount(); u.FirstName = d.FirstName; u.LastName = d.LastName; u.PrincipalID = d.PrincipalID; u.ScopeID = d.ScopeID; if (d.Data.ContainsKey("Email") && d.Data["Email"] != null) u.Email = d.Data["Email"].ToString(); else u.Email = string.Empty; u.Created = Convert.ToInt32(d.Data["Created"].ToString()); if (d.Data.ContainsKey("UserTitle") && d.Data["UserTitle"] != null) u.UserTitle = d.Data["UserTitle"].ToString(); else u.UserTitle = string.Empty; if (d.Data.ContainsKey("UserLevel") && d.Data["UserLevel"] != null) Int32.TryParse(d.Data["UserLevel"], out u.UserLevel); if (d.Data.ContainsKey("UserFlags") && d.Data["UserFlags"] != null) Int32.TryParse(d.Data["UserFlags"], out u.UserFlags); if (d.Data.ContainsKey("UserCountry") && d.Data["UserCountry"] != null) u.UserCountry = d.Data["UserCountry"].ToString(); else u.UserCountry = string.Empty; if (d.Data.ContainsKey("DisplayName") && d.Data["DisplayName"] != null) u.DisplayName = d.Data["DisplayName"].ToString(); else u.DisplayName = string.Empty; if (d.Data.ContainsKey("DisplayNameChanged") && d.Data["DisplayNameChanged"] != null) Int32.TryParse(d.Data["DisplayNameChanged"], out u.DisplayNameChanged); u.Active = true; if (d.Data.ContainsKey("active") && d.Data["active"] != null) { string active = d.Data["active"].ToString(); if (!Boolean.TryParse(active, out u.Active) && Int32.TryParse(active, out int activeInt)) u.Active = activeInt != 0; } if (d.Data.ContainsKey("NexVerseState") && d.Data["NexVerseState"] != null) u.NexVerseState = d.Data["NexVerseState"].ToString(); else u.NexVerseState = "active"; if (d.Data.ContainsKey("NexVerseStateReason") && d.Data["NexVerseStateReason"] != null) u.NexVerseStateReason = d.Data["NexVerseStateReason"].ToString(); else u.NexVerseStateReason = string.Empty; if (d.Data.ContainsKey("NexVerseStateChanged") && d.Data["NexVerseStateChanged"] != null) Int32.TryParse(d.Data["NexVerseStateChanged"], out u.NexVerseStateChanged); // These columns already exist in the UserAccounts SQL migrations. // Without mapping them back into UserAccount, PATCH authorization // appears successful but every following GET/login sees resident + // empty explicit scopes, regardless of the database contents. if (d.Data.ContainsKey("NexVerseRoles") && d.Data["NexVerseRoles"] != null) u.NexVerseRoles = d.Data["NexVerseRoles"].ToString(); if (d.Data.ContainsKey("NexVerseScopes") && d.Data["NexVerseScopes"] != null) u.NexVerseScopes = d.Data["NexVerseScopes"].ToString(); if (d.Data.ContainsKey("NexVerseTosAcceptedVersion")) u.NexVerseTosAcceptedVersion = d.Data["NexVerseTosAcceptedVersion"] ?? string.Empty; if (d.Data.ContainsKey("NexVerseTosAcceptedAtUtc") && d.Data["NexVerseTosAcceptedAtUtc"] != null) Int32.TryParse(d.Data["NexVerseTosAcceptedAtUtc"], out u.NexVerseTosAcceptedAtUtc); if (d.Data.ContainsKey("ServiceURLs") && d.Data["ServiceURLs"] != null) { string[] URLs = d.Data["ServiceURLs"].ToString().Split(new char[] { ' ' }); u.ServiceURLs = new Dictionary(); foreach (string url in URLs) { string[] parts = url.Split(new char[] { '=' }); if (parts.Length != 2) continue; string name = System.Web.HttpUtility.UrlDecode(parts[0]); string val = System.Web.HttpUtility.UrlDecode(parts[1]); u.ServiceURLs[name] = val; } } else u.ServiceURLs = new Dictionary(); return u; } public UserAccount GetUserAccount(UUID scopeID, string email) { UserAccountData[] d; if (!scopeID.IsZero()) { d = m_Database.Get( new string[] { "ScopeID", "Email" }, new string[] { scopeID.ToString(), email }); if (d.Length < 1) { d = m_Database.Get( new string[] { "ScopeID", "Email" }, new string[] { UUID.Zero.ToString(), email }); } } else { d = m_Database.Get( new string[] { "Email" }, new string[] { email }); } if (d.Length < 1) return null; return MakeUserAccount(d[0]); } public UserAccount GetUserAccount(UUID scopeID, UUID principalID) { UserAccountData[] d; if (!scopeID.IsZero()) { d = m_Database.Get( new string[] { "ScopeID", "PrincipalID" }, new string[] { scopeID.ToString(), principalID.ToString() }); if (d.Length < 1) { d = m_Database.Get( new string[] { "ScopeID", "PrincipalID" }, new string[] { UUID.Zero.ToString(), principalID.ToString() }); } } else { d = m_Database.Get( new string[] { "PrincipalID" }, new string[] { principalID.ToString() }); } if (d.Length < 1) { return null; } return MakeUserAccount(d[0]); } public List GetUserAccounts(UUID scopeID, List IDs) { UserAccountData[] ret = m_Database.GetUsersWhere(scopeID, "PrincipalID in ('" + String.Join("', '", IDs) + "')"); if(ret == null || ret.Length == 0) return new List(); return new List(ret.Select((x) => MakeUserAccount(x))); } public void InvalidateCache(UUID userID) { } public bool StoreUserAccount(UserAccount data) { // m_log.DebugFormat( // "[USER ACCOUNT SERVICE]: Storing user account for {0} {1} {2}, scope {3}", // data.FirstName, data.LastName, data.PrincipalID, data.ScopeID); UserAccountData d = new UserAccountData(); d.FirstName = data.FirstName; d.LastName = data.LastName; d.PrincipalID = data.PrincipalID; d.ScopeID = data.ScopeID; d.Data = new Dictionary(); d.Data["Email"] = data.Email; d.Data["Created"] = data.Created.ToString(); d.Data["UserLevel"] = data.UserLevel.ToString(); d.Data["UserFlags"] = data.UserFlags.ToString(); d.Data["UserTitle"] = data.UserTitle ?? string.Empty; d.Data["UserCountry"] = data.UserCountry ?? string.Empty; d.Data["DisplayName"] = data.DisplayName ?? string.Empty; d.Data["DisplayNameChanged"] = data.DisplayNameChanged.ToString(); d.Data["active"] = data.Active ? "1" : "0"; d.Data["NexVerseState"] = string.IsNullOrWhiteSpace(data.NexVerseState) ? "active" : data.NexVerseState; d.Data["NexVerseStateReason"] = data.NexVerseStateReason ?? string.Empty; d.Data["NexVerseStateChanged"] = data.NexVerseStateChanged.ToString(); // Preserve explicit resident role/scope assignments across the // SQL Store/Get cycle, including unrelated account updates. // Missing columns in a live schema are a migration error and // must not be silently treated as successful authorization. d.Data["NexVerseRoles"] = string.IsNullOrWhiteSpace(data.NexVerseRoles) ? "resident" : data.NexVerseRoles; d.Data["NexVerseScopes"] = data.NexVerseScopes ?? string.Empty; d.Data["NexVerseTosAcceptedVersion"] = data.NexVerseTosAcceptedVersion ?? string.Empty; d.Data["NexVerseTosAcceptedAtUtc"] = data.NexVerseTosAcceptedAtUtc.ToString(); List parts = new List(); foreach (KeyValuePair kvp in data.ServiceURLs) { string key = System.Web.HttpUtility.UrlEncode(kvp.Key); string val = System.Web.HttpUtility.UrlEncode(kvp.Value.ToString()); parts.Add(key + "=" + val); } d.Data["ServiceURLs"] = string.Join(" ", parts.ToArray()); return m_Database.Store(d); } public List GetUserAccounts(UUID scopeID, string query) { UserAccountData[] d = m_Database.GetUsers(scopeID, query.Trim()); if (d == null) return new List(); List ret = new List(); foreach (UserAccountData data in d) ret.Add(MakeUserAccount(data)); return ret; } public List GetUserAccountsWhere(UUID scopeID, string where) { UserAccountData[] d = m_Database.GetUsersWhere(scopeID, where); if (d == null) return new List(); List ret = new List(); foreach (UserAccountData data in d) ret.Add(MakeUserAccount(data)); return ret; } #endregion #region Console commands /// /// Handle the create user command from the console. /// /// string array with parameters: firstname, lastname, password, locationX, locationY, email, userID, model name protected void HandleCreateUser(string module, string[] cmdparams) { string firstName; string lastName; string password = ""; string email; string rawPrincipalId; string model; // List excluded = new List(new char[]{' '}); List excluded = new List(new char[]{' ', '@', '.', ':' }); //Protect user names from using valid HG identifiers. if (cmdparams.Length < 3) firstName = MainConsole.Instance.Prompt("First name", "Default", excluded); else firstName = cmdparams[2]; if (cmdparams.Length < 4) lastName = MainConsole.Instance.Prompt("Last name", "User", excluded); else lastName = cmdparams[3]; if (cmdparams.Length < 5) { int retries = 3; while(--retries >= 0) { password = MainConsole.Instance.Prompt("Password", null, null, false); if(String.IsNullOrWhiteSpace(password)) MainConsole.Instance.Output(" You must provide a Password"); else break; } if (string.IsNullOrWhiteSpace(password)) { MainConsole.Instance.Output("create user aborted"); return; } } else password = cmdparams[4]; if (cmdparams.Length < 6) email = MainConsole.Instance.Prompt("Email", ""); else email = cmdparams[5]; if (cmdparams.Length < 7) rawPrincipalId = MainConsole.Instance.Prompt("User ID (enter for random)", ""); else rawPrincipalId = cmdparams[6]; if (cmdparams.Length < 8) model = MainConsole.Instance.Prompt("Model name",""); else model = cmdparams[7]; UUID principalId = UUID.Zero; if(String.IsNullOrWhiteSpace(rawPrincipalId)) principalId = UUID.Random(); else if (!UUID.TryParse(rawPrincipalId, out principalId)) throw new Exception(string.Format("ID {0} is not a valid UUID", rawPrincipalId)); CreateUser(UUID.Zero, principalId, firstName, lastName, password, email, model); } // Deletes the standard OpenSim local avatar identity from a single // authoritative DB, inside one transaction. Do not claim that this // deletes third-party economy, groups, estates, inworld objects or // shared asset blobs: operators must audit those integrations first. // If any required store is on another database, refuse the action. protected void HandleDeleteUser(string module, string[] cmdparams) { if (cmdparams.Length != 5 && cmdparams.Length != 6) { MainConsole.Instance.Output("Usage: delete user [--confirm]"); return; } if (cmdparams.Length == 6 && cmdparams[5] != "--confirm") { MainConsole.Instance.Output("Only --confirm is supported for permanent deletion."); return; } if (!UUID.TryParse(cmdparams[4], out UUID userId) || userId.IsZero()) { MainConsole.Instance.Output("Specify the exact non-zero avatar UUID from 'show account'."); return; } UserAccount account = GetUserAccount(UUID.Zero, cmdparams[2], cmdparams[3]); if (account == null || account.PrincipalID != userId || !account.LocalToGrid) { MainConsole.Instance.Output("Deletion refused: avatar name/UUID mismatch or non-local account."); return; } if (userId == Constants.servicesGodAgentID || account.UserLevel >= 200) { MainConsole.Instance.Output("Deletion refused: protected grid service or administrator account."); return; } if (m_GridUserService == null) { MainConsole.Instance.Output("Deletion refused: authoritative GridUserService unavailable."); return; } try { GridUserInfo loginState = m_GridUserService.GetGridUserInfo(userId.ToString()); if (loginState != null && loginState.Online) { MainConsole.Instance.Output("Deletion refused: avatar is currently online. Log out and retry."); return; } string provider = DeletionStorageSetting("UserAccountService", "StorageProvider"); string connectionString = DeletionStorageSetting("UserAccountService", "ConnectionString"); if (string.IsNullOrWhiteSpace(provider) || string.IsNullOrWhiteSpace(connectionString)) throw new InvalidOperationException("No authoritative UserAccountService database configured."); foreach (string service in new[] { "AuthenticationService", "GridUserService", "InventoryService", "AvatarService", "PresenceService", "FriendsService" }) { if (!string.Equals(provider, DeletionStorageSetting(service, "StorageProvider"), StringComparison.OrdinalIgnoreCase) || !string.Equals(connectionString, DeletionStorageSetting(service, "ConnectionString"), StringComparison.Ordinal)) throw new InvalidOperationException(service + " uses a different data store. Cross-database purge is unsafe."); } // Only well-known migration realms are supported. No table or // column names are ever supplied by a console argument. foreach (string[] realm in new[] { new[] { "UserAccountService", "UserAccounts" }, new[] { "AuthenticationService", "auth" }, new[] { "GridUserService", "GridUser" }, new[] { "AvatarService", "Avatars" }, new[] { "FriendsService", "Friends" }, new[] { "PresenceService", "Presence" } }) { IConfig section = m_DeletionConfig.Configs[realm[0]]; string configuredRealm = section?.GetString("Realm", string.Empty); if (!string.IsNullOrWhiteSpace(configuredRealm) && !string.Equals(configuredRealm, realm[1], StringComparison.Ordinal)) throw new InvalidOperationException("Custom realm for " + realm[0] + " requires manual deletion audit."); } bool postgres = provider.IndexOf("PGSQL", StringComparison.OrdinalIgnoreCase) >= 0; string providerType = provider.IndexOf("MySQL", StringComparison.OrdinalIgnoreCase) >= 0 ? "MySql.Data.MySqlClient.MySqlConnection, MySql.Data" : postgres ? "Npgsql.NpgsqlConnection, Npgsql" : provider.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) >= 0 ? "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite" : null; if (providerType == null) throw new InvalidOperationException("Unsupported database backend for console deletion: " + provider); Type type = Type.GetType(providerType, throwOnError: false); if (type == null || !typeof(DbConnection).IsAssignableFrom(type)) throw new InvalidOperationException("Database driver unavailable: " + providerType); using DbConnection connection = (DbConnection)Activator.CreateInstance(type, connectionString); connection.Open(); using DbTransaction transaction = connection.BeginTransaction(); // PostgreSQL uses UUID-typed columns for these four records; // MySQL and SQLite store GUIDs as text. string[][] rows = new string[][] { new[] { "tokens", "UUID", "uuid" }, new[] { "auth", "UUID", "uuid" }, new[] { "inventoryitems", "avatarID", "text" }, new[] { "inventoryfolders", "agentID", "text" }, new[] { "Avatars", "PrincipalID", "uuid" }, new[] { "GridUser", "UserID", "text" }, new[] { "Presence", "UserID", "text" }, new[] { "Friends", "PrincipalID", "text" }, new[] { "UserAccounts", "PrincipalID", "uuid" } }; string quote = postgres || provider.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) >= 0 ? "\"" : "`"; string Quote(string name) => quote + name + quote; // PostgreSQL migration table identifiers are unquoted (folded // to lowercase). Column names are generally case-preserving, // except auth/tokens where uuid is an unquoted column. string TableName(string name) => postgres ? name : Quote(name); string ColumnName(string table, string column) => postgres && (table == "auth" || table == "tokens") && column == "UUID" ? "uuid" : Quote(column); // Preflight all required tables before mutating anything. int[] counts = new int[rows.Length]; for (int i = 0; i < rows.Length; i++) { string[] row = rows[i]; string sql = "SELECT COUNT(*) FROM " + TableName(row[0]) + " WHERE " + ColumnName(row[0], row[1]) + " = @userId"; counts[i] = DeletionSql(connection, transaction, sql, userId, postgres && row[2] == "uuid", false); MainConsole.Instance.Output(" {0}: {1} rows", row[0], counts[i]); } int reverseFriends = DeletionSql(connection, transaction, "SELECT COUNT(*) FROM " + TableName("Friends") + " WHERE " + ColumnName("Friends", "Friend") + " LIKE @userId", userId, false, false, true); MainConsole.Instance.Output(" Friends (reverse): {0} rows", reverseFriends); if (counts[8] != 1 || counts[6] != 0) throw new InvalidOperationException("Account no longer unique or an active Presence session still exists. Nothing deleted."); // Release read locks before prompting an administrator. transaction.Commit(); if (cmdparams.Length == 5) { MainConsole.Instance.Output("Dry run only. To purge core avatar records: delete user {0} {1} {2} --confirm", cmdparams[2], cmdparams[3], userId); MainConsole.Instance.Output("WARNING: Land, rezzed objects, groups, NV$ and external addon/portal data are NOT covered."); return; } string phrase = "DELETE " + userId; string confirmation = MainConsole.Instance.Prompt("Enter exactly '" + phrase + "' to irreversibly purge core avatar records", "CANCEL"); if (!string.Equals(confirmation, phrase, StringComparison.Ordinal)) { MainConsole.Instance.Output("Deletion cancelled, no records changed."); return; } using DbTransaction deletionTransaction = connection.BeginTransaction(); if (DeletionSql(connection, deletionTransaction, "SELECT COUNT(*) FROM " + TableName("UserAccounts") + " WHERE " + ColumnName("UserAccounts", "PrincipalID") + " = @userId", userId, postgres, false) != 1 || DeletionSql(connection, deletionTransaction, "SELECT COUNT(*) FROM " + TableName("Presence") + " WHERE " + ColumnName("Presence", "UserID") + " = @userId", userId, false, false) != 0) throw new InvalidOperationException("Account or login state changed during confirmation."); GridUserInfo currentState = m_GridUserService.GetGridUserInfo(userId.ToString()); if (currentState != null && currentState.Online) throw new InvalidOperationException("Avatar became online during confirmation."); DeletionSql(connection, deletionTransaction, "DELETE FROM " + TableName("Friends") + " WHERE " + ColumnName("Friends", "Friend") + " LIKE @userId", userId, false, true, true); for (int i = 0; i < rows.Length; i++) { string[] row = rows[i]; DeletionSql(connection, deletionTransaction, "DELETE FROM " + TableName(row[0]) + " WHERE " + ColumnName(row[0], row[1]) + " = @userId", userId, postgres && row[2] == "uuid", true); } deletionTransaction.Commit(); m_log.WarnFormat("[USER ACCOUNT]: Administrative core avatar purge committed for {0} ({1})", account.Name, userId); MainConsole.Instance.Output("Core avatar identity permanently deleted: {0} ({1})", account.Name, userId); MainConsole.Instance.Output("External groups, parcels, rezzed objects, economy, profile and portal data need a separate audit."); } catch (Exception ex) { m_log.ErrorFormat("[USER ACCOUNT]: delete user failed for {0}: {1}", userId, ex.Message); MainConsole.Instance.Output("Deletion aborted / rolled back where supported: {0}", ex.Message); } } /// /// Core-only purge for an authenticated and password-reverified local /// resident. This does NOT erase land, groups, money or external addons. /// Never call directly from a client-supplied avatar identifier. /// public bool TryDeleteLocalAvatar(UUID avatarId, out string failureReason) { failureReason = "account_deletion_failed"; if (avatarId.IsZero() || avatarId == Constants.servicesGodAgentID) { failureReason = "protected_account"; return false; } UserAccount account = GetUserAccount(UUID.Zero, avatarId); if (account == null || !account.LocalToGrid || account.UserLevel >= 200) { failureReason = "protected_account"; return false; } if (m_GridUserService == null) { failureReason = "grid_user_service_unavailable"; return false; } try { GridUserInfo state = m_GridUserService.GetGridUserInfo(avatarId.ToString()); if (state != null && state.Online) { failureReason = "avatar_online"; return false; } string provider = DeletionStorageSetting("UserAccountService", "StorageProvider"); string connectionString = DeletionStorageSetting("UserAccountService", "ConnectionString"); if (string.IsNullOrWhiteSpace(provider) || string.IsNullOrWhiteSpace(connectionString)) throw new InvalidOperationException("Authoritative database not configured."); foreach (string service in new[] { "AuthenticationService", "GridUserService", "InventoryService", "AvatarService", "PresenceService", "FriendsService" }) { if (!string.Equals(provider, DeletionStorageSetting(service, "StorageProvider"), StringComparison.OrdinalIgnoreCase) || !string.Equals(connectionString, DeletionStorageSetting(service, "ConnectionString"), StringComparison.Ordinal)) throw new InvalidOperationException("Differing " + service + " database configuration."); } foreach (string[] realm in new[] { new[] { "UserAccountService", "UserAccounts" }, new[] { "AuthenticationService", "auth" }, new[] { "GridUserService", "GridUser" }, new[] { "AvatarService", "Avatars" }, new[] { "FriendsService", "Friends" }, new[] { "PresenceService", "Presence" } }) { string selected = m_DeletionConfig.Configs[realm[0]]?.GetString("Realm", string.Empty); if (!string.IsNullOrWhiteSpace(selected) && !string.Equals(selected, realm[1], StringComparison.Ordinal)) throw new InvalidOperationException("Custom realm not supported for " + realm[0]); } bool pg = provider.IndexOf("PGSQL", StringComparison.OrdinalIgnoreCase) >= 0; bool mysql = provider.IndexOf("MySQL", StringComparison.OrdinalIgnoreCase) >= 0; string typeName = mysql ? "MySql.Data.MySqlClient.MySqlConnection, MySql.Data" : pg ? "Npgsql.NpgsqlConnection, Npgsql" : provider.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) >= 0 ? "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite" : null; if (typeName == null) throw new InvalidOperationException("Unsupported deletion database."); Type type = Type.GetType(typeName, false); if (type == null || !typeof(DbConnection).IsAssignableFrom(type)) throw new InvalidOperationException("Deletion database driver not available."); using DbConnection db = (DbConnection)Activator.CreateInstance(type, connectionString); db.Open(); using DbTransaction tx = db.BeginTransaction(); string quote = mysql ? "`" : "\""; string Q(string value) => quote + value + quote; string T(string table) => pg ? table : Q(table); string C(string table, string column) => pg && (table == "auth" || table == "tokens") && column == "UUID" ? "uuid" : Q(column); int Count(string table, string column, bool guid) { return DeletionSql(db, tx, "SELECT COUNT(*) FROM " + T(table) + " WHERE " + C(table, column) + " = @userId", avatarId, guid, false); } // Fail closed before any deletion when the record has changed, // login is still in progress, or inventory/auth tables are missing. if (Count("UserAccounts", "PrincipalID", pg) != 1 || Count("Presence", "UserID", false) != 0) { failureReason = "account_state_changed"; return false; } GridUserInfo latest = m_GridUserService.GetGridUserInfo(avatarId.ToString()); if (latest != null && latest.Online) { failureReason = "avatar_online"; return false; } DeletionSql(db, tx, "DELETE FROM " + T("Friends") + " WHERE " + C("Friends", "Friend") + " LIKE @userId", avatarId, false, true, true); string[][] records = { new[] { "tokens", "UUID", "uuid" }, new[] { "auth", "UUID", "uuid" }, new[] { "inventoryitems", "avatarID", "text" }, new[] { "inventoryfolders", "agentID", "text" }, new[] { "Avatars", "PrincipalID", "uuid" }, new[] { "GridUser", "UserID", "text" }, new[] { "Friends", "PrincipalID", "text" }, new[] { "UserAccounts", "PrincipalID", "uuid" } }; foreach (string[] record in records) { int changed = DeletionSql(db, tx, "DELETE FROM " + T(record[0]) + " WHERE " + C(record[0], record[1]) + " = @userId", avatarId, pg && record[2] == "uuid", true); if (record[0] == "UserAccounts" && changed != 1) throw new InvalidOperationException("Account vanished before commit."); } tx.Commit(); InvalidateCache(avatarId); m_log.WarnFormat("[USER ACCOUNT]: Authenticated self deletion committed for account {0}", avatarId); failureReason = string.Empty; return true; } catch (Exception e) { // No success or misleading 'complete deletion' result if the // transaction failed. Never include connection strings in API. m_log.ErrorFormat("[USER ACCOUNT]: Account self-deletion {0} failed: {1}", avatarId, e.Message); failureReason = "deletion_backend_unavailable"; return false; } } private string DeletionStorageSetting(string sectionName, string name) { string fallback = m_DeletionConfig.Configs["DatabaseService"]?.GetString(name, string.Empty) ?? string.Empty; string sectionValue = m_DeletionConfig.Configs[sectionName]?.GetString(name, string.Empty); return string.IsNullOrWhiteSpace(sectionValue) ? fallback : sectionValue; } private static int DeletionSql(DbConnection connection, DbTransaction transaction, string sql, UUID userId, bool guidValue, bool mutate, bool prefix = false) { using DbCommand command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = sql; DbParameter parameter = command.CreateParameter(); parameter.ParameterName = "@userId"; parameter.Value = prefix ? userId.ToString() + "%" : guidValue ? (object)userId.Guid : userId.ToString(); command.Parameters.Add(parameter); return mutate ? command.ExecuteNonQuery() : Convert.ToInt32(command.ExecuteScalar()); } protected void HandleShowAccount(string module, string[] cmdparams) { if (cmdparams.Length != 4) { MainConsole.Instance.Output("Usage: show account "); return; } string firstName = cmdparams[2]; string lastName = cmdparams[3]; UserAccount ua = GetUserAccount(UUID.Zero, firstName, lastName); if (ua == null) { MainConsole.Instance.Output("No user named {0} {1}", firstName, lastName); return; } MainConsole.Instance.Output("Name: {0}", ua.Name); MainConsole.Instance.Output("ID: {0}", ua.PrincipalID); MainConsole.Instance.Output("Title: {0}", ua.UserTitle); MainConsole.Instance.Output("E-mail: {0}", ua.Email); MainConsole.Instance.Output("Created: {0}", Utils.UnixTimeToDateTime(ua.Created)); MainConsole.Instance.Output("Level: {0}", ua.UserLevel); MainConsole.Instance.Output("Flags: {0}", ua.UserFlags); foreach (KeyValuePair kvp in ua.ServiceURLs) MainConsole.Instance.Output("{0}: {1}", kvp.Key, kvp.Value); } protected void HandleResetUserPassword(string module, string[] cmdparams) { string firstName; string lastName; string newPassword; if (cmdparams.Length < 4) firstName = MainConsole.Instance.Prompt("First name"); else firstName = cmdparams[3]; if (cmdparams.Length < 5) lastName = MainConsole.Instance.Prompt("Last name"); else lastName = cmdparams[4]; if (cmdparams.Length < 6) newPassword = MainConsole.Instance.Prompt("New password", null, null, false); else newPassword = cmdparams[5]; UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); if (account == null) { MainConsole.Instance.Output("No such user as {0} {1}", firstName, lastName); return; } bool success = false; if (m_AuthenticationService != null) success = m_AuthenticationService.SetPassword(account.PrincipalID, newPassword); if (!success) MainConsole.Instance.Output("Unable to reset password for account {0} {1}.", firstName, lastName); else MainConsole.Instance.Output("Password reset for user {0} {1}", firstName, lastName); } protected void HandleResetUserEmail(string module, string[] cmdparams) { string firstName; string lastName; string newEmail; if (cmdparams.Length < 4) firstName = MainConsole.Instance.Prompt("First name"); else firstName = cmdparams[3]; if (cmdparams.Length < 5) lastName = MainConsole.Instance.Prompt("Last name"); else lastName = cmdparams[4]; if (cmdparams.Length < 6) newEmail = MainConsole.Instance.Prompt("New Email"); else newEmail = cmdparams[5]; UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); if (account == null) { MainConsole.Instance.Output("No such user as {0} {1}", firstName, lastName); return; } bool success = false; account.Email = newEmail; success = StoreUserAccount(account); if (!success) MainConsole.Instance.Output("Unable to set Email for account {0} {1}.", firstName, lastName); else MainConsole.Instance.Output("User Email set for user {0} {1} to {2}", firstName, lastName, account.Email); } protected void HandleSetUserLevel(string module, string[] cmdparams) { string firstName; string lastName; string rawLevel; int level; if (cmdparams.Length < 4) firstName = MainConsole.Instance.Prompt("First name"); else firstName = cmdparams[3]; if (cmdparams.Length < 5) lastName = MainConsole.Instance.Prompt("Last name"); else lastName = cmdparams[4]; UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); if (account == null) { MainConsole.Instance.Output("No such user"); return; } if (cmdparams.Length < 6) rawLevel = MainConsole.Instance.Prompt("User level"); else rawLevel = cmdparams[5]; if(int.TryParse(rawLevel, out level) == false) { MainConsole.Instance.Output("Invalid user level"); return; } account.UserLevel = level; bool success = StoreUserAccount(account); if (!success) MainConsole.Instance.Output("Unable to set user level for account {0} {1}.", firstName, lastName); else MainConsole.Instance.Output("User level set for user {0} {1} to {2}", firstName, lastName, level); } #endregion /// /// Create a user /// /// Allows hosting of multiple grids in a single database. Normally left as UUID.Zero /// ID of the user /// /// /// /// /// public UserAccount CreatePortalAvatar(string firstName, string lastName, string password, string email, string modelAlias) { if (modelAlias != "ogl:benjamin" && modelAlias != "ogl:luna") return null; return CreateUser(UUID.Zero, UUID.Random(), firstName, lastName, password, email, modelAlias); } public UserAccount CreatePortalAvatar(string firstName, string lastName, string password, string email, string modelAlias, string homeRegionId, string homeRegionName, Vector3 position) { // For a portal signup the viewer's first spawn is not optional. // Validate the authoritative destination *before* creating an // avatar, inventory, password or starter outfit. if ((modelAlias != "ogl:benjamin" && modelAlias != "ogl:luna") || m_GridService == null || m_GridUserService == null || !float.IsFinite(position.X) || !float.IsFinite(position.Y) || !float.IsFinite(position.Z)) return null; GridRegion home = null; if (!string.IsNullOrWhiteSpace(homeRegionId)) { if (!UUID.TryParse(homeRegionId.Trim(), out UUID id) || id.IsZero()) return null; home = m_GridService.GetRegionByUUID(UUID.Zero, id); if (home != null && !string.IsNullOrWhiteSpace(homeRegionName) && !string.Equals(home.RegionName, homeRegionName.Trim(), StringComparison.OrdinalIgnoreCase)) return null; } else if (!string.IsNullOrWhiteSpace(homeRegionName)) home = m_GridService.GetRegionByName(UUID.Zero, homeRegionName.Trim()); if (home == null || home.RegionID.IsZero() || home.RegionSizeX < 16 || home.RegionSizeY < 16 || position.X < 0 || position.Y < 0 || position.X >= home.RegionSizeX || position.Y >= home.RegionSizeY || position.Z < 1 || position.Z > 4096) { m_log.WarnFormat( "[OGL-REGISTRIERUNG] FEHLER: Startregion '{0}' (ID {1}) oder Position {2} ungültig/nicht im GridService registriert.", homeRegionName, homeRegionId, position); return null; } UserAccount account = CreateUser( UUID.Zero, UUID.Random(), firstName, lastName, password, email, modelAlias); if (account == null) { m_log.WarnFormat( "[OGL-REGISTRIERUNG] FEHLER: Modellvorlage oder Accountanlage für {0} {1} fehlgeschlagen (Modell {2}).", firstName, lastName, modelAlias); return null; } bool positioned = false; try { string userId = account.PrincipalID.ToString(); Vector3 lookAt = new Vector3(0, 1, 0); // Writing both values is essential. OpenSim login can pick // Last even when Home has already been initialized. bool homeOk = m_GridUserService.SetHome( userId, home.RegionID, position, lookAt); bool lastOk = m_GridUserService.SetLastPosition( userId, UUID.Zero, home.RegionID, position, lookAt); positioned = homeOk && lastOk; if (!positioned) m_log.ErrorFormat( "[OGL-REGISTRIERUNG] FEHLER: Home={0}, Last={1} für Avatar {2} (UUID {3}) auf {4}/{5}.", homeOk ? "OK" : "FEHLER", lastOk ? "OK" : "FEHLER", firstName + " " + lastName, account.PrincipalID, home.RegionName, position); } catch (Exception e) { m_log.Error("[OGL PORTAL REGISTRATION]: Failed to seed Home/Last positions", e); } if (!positioned) { // Do not return a login-capable orphan on partial placement // failure. Recovery is explicit: never silently claim 201. account.Active = false; account.NexVerseState = "provisioning_failed"; account.NexVerseStateReason = "Home/Last position initialization failed"; account.NexVerseStateChanged = Math.Max( OpenSim.Framework.Util.UnixTimeSinceEpoch(), account.NexVerseStateChanged + 1); try { if (!StoreUserAccount(account)) m_log.ErrorFormat("[OGL PORTAL REGISTRATION]: Manual account lock required for {0}", account.PrincipalID); InvalidateCache(account.PrincipalID); } catch (Exception e) { m_log.Error("[OGL PORTAL REGISTRATION]: Unable to lock incomplete account", e); } return null; } m_log.InfoFormat( "[OGL-REGISTRIERUNG] ERFOLG: Avatar {0} {1} | UUID {2} | Vorlage {3} | Home+Last {4}/{5}", account.FirstName, account.LastName, account.PrincipalID, modelAlias, home.RegionName, position); return account; } public UserAccount CreateUser(UUID scopeID, UUID principalID, string firstName, string lastName, string password, string email, string model = "") { if (string.IsNullOrWhiteSpace(firstName) || string.IsNullOrWhiteSpace(lastName)) { m_log.Warn("[USER ACCOUNT SERVICE]: Refusing empty account name"); return null; } firstName = firstName.Trim(); lastName = lastName.Trim(); // Reject missing credentials before writing any starter account. if (!string.IsNullOrEmpty(model) && model.StartsWith("ogl:", StringComparison.OrdinalIgnoreCase) && (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(email))) { m_log.Warn("[OGL AVATAR TEMPLATES]: Starter registration requires password and email"); return null; } // Starter registrations require an authentication backend. Otherwise // the legacy path could persist an account without login credentials. if (!string.IsNullOrEmpty(model) && model.StartsWith("ogl:", StringComparison.OrdinalIgnoreCase) && m_AuthenticationService == null) { m_log.Warn("[OGL AVATAR TEMPLATES]: Authentication service unavailable"); return null; } // Reject invalid OGL starter requests before creating a user account. // The legacy OpenSim model parameter remains backward compatible. if (!string.IsNullOrEmpty(model) && model.StartsWith("ogl:", StringComparison.OrdinalIgnoreCase)) { string resolvedModel = ResolveOglStarterModel(model); if (string.IsNullOrWhiteSpace(resolvedModel)) { m_log.Warn("[OGL AVATAR TEMPLATES]: No published starter model configured"); return null; } string[] names = resolvedModel.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (names.Length != 2) { m_log.Warn("[OGL AVATAR TEMPLATES]: Refusing disabled or unknown template"); return null; } UserAccount templateAccount = GetUserAccount(UUID.Zero, names[0], names[1]); if (templateAccount != null && (templateAccount.PrincipalID == principalID || (string.Equals(firstName, names[0], StringComparison.OrdinalIgnoreCase) && string.Equals(lastName, names[1], StringComparison.OrdinalIgnoreCase)))) { m_log.Warn("[OGL AVATAR TEMPLATES]: Model avatar cannot register using itself as template"); return null; } if (templateAccount == null || m_AvatarService == null || m_InventoryService == null || m_AvatarService.GetAppearance(templateAccount.PrincipalID) == null) { m_log.Warn("[OGL AVATAR TEMPLATES]: Refusing missing or unready model avatar"); return null; } // Validate every currently worn item before creating the account. // This prevents partial starter inventories caused by missing or // non-transferable source items. Object contents need separate review. if (!ValidateOglStarterItems(templateAccount.PrincipalID, m_AvatarService.GetAppearance(templateAccount.PrincipalID))) return null; if (!m_CreateDefaultAvatarEntries) { m_log.Warn("[OGL AVATAR TEMPLATES]: Default avatar inventory creation is disabled"); return null; } } UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); if (null == account) { account = new UserAccount(UUID.Zero, principalID, firstName, lastName, email); if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0)) { account.ServiceURLs = new Dictionary(); account.ServiceURLs["HomeURI"] = string.Empty; account.ServiceURLs["InventoryServerURI"] = string.Empty; account.ServiceURLs["AssetServerURI"] = string.Empty; } if (StoreUserAccount(account)) { bool success; if (m_AuthenticationService != null) { success = m_AuthenticationService.SetPassword(account.PrincipalID, password); if (!success) { m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.", firstName, lastName); if (!string.IsNullOrEmpty(model) && model.StartsWith("ogl:", StringComparison.OrdinalIgnoreCase)) { CompensateFailedOglStarterRegistration(account.PrincipalID); return null; } } } GridRegion home = null; if (m_GridService != null) { List defaultRegions = m_GridService.GetDefaultRegions(UUID.Zero); if (defaultRegions != null && defaultRegions.Count >= 1) home = defaultRegions[0]; if (m_GridUserService != null && home != null) m_GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0)); else m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.", firstName, lastName); } else { m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.", firstName, lastName); } if (m_InventoryService != null) { success = m_InventoryService.CreateUserInventory(account.PrincipalID); if (!success) { m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.", firstName, lastName); } else { m_log.DebugFormat( "[USER ACCOUNT SERVICE]: Created user inventory for {0} {1}", firstName, lastName); } // A starter registration must never continue with an // uninitialized inventory: the outfit would be lost. if (!success && !string.IsNullOrEmpty(model) && model.StartsWith("ogl:", StringComparison.OrdinalIgnoreCase)) { m_log.Error("[OGL AVATAR TEMPLATES]: Starter inventory initialization failed"); CompensateFailedOglStarterRegistration(account.PrincipalID); return null; } if (m_CreateDefaultAvatarEntries) { if (String.IsNullOrEmpty(model)) CreateDefaultAppearanceEntries(account.PrincipalID); else if (model.StartsWith("ogl:", StringComparison.OrdinalIgnoreCase)) { if (!TryEstablishAppearance(account.PrincipalID, ResolveOglStarterModel(model), true)) { m_log.Error("[OGL AVATAR TEMPLATES]: Starter appearance initialization failed"); CompensateFailedOglStarterRegistration(account.PrincipalID); return null; } } else EstablishAppearance(account.PrincipalID, ResolveOglStarterModel(model)); } } m_log.InfoFormat( "[USER ACCOUNT SERVICE]: Account {0} {1} {2} created successfully", firstName, lastName, account.PrincipalID); } else { m_log.ErrorFormat("[USER ACCOUNT SERVICE]: Account creation failed for account {0} {1}", firstName, lastName); // Never return a non-persisted UserAccount object as a // successfully provisioned portal avatar (HTTP 201). if (!string.IsNullOrEmpty(model) && model.StartsWith("ogl:", StringComparison.OrdinalIgnoreCase)) return null; } } else { m_log.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} {1} already exists!", firstName, lastName); // A portal registration must never treat an existing account as // a newly created one or expose its principal identifier. if (!string.IsNullOrEmpty(model) && model.StartsWith("ogl:", StringComparison.OrdinalIgnoreCase)) return null; } return account; } // Best-effort compensation for a failed starter registration. // The storage API supports account deletion, but authentication, // inventory and appearance services have no shared transaction. // Never report this as an atomic rollback. private void CompensateFailedOglStarterRegistration(UUID principalID) { try { if (!m_Database.Delete("PrincipalID", principalID.ToString())) m_log.ErrorFormat("[OGL AVATAR TEMPLATES]: Manual cleanup required for failed registration {0}", principalID); else m_log.WarnFormat("[OGL AVATAR TEMPLATES]: Removed account record for failed registration {0}; check orphaned authentication and inventory data", principalID); } catch (Exception e) { m_log.ErrorFormat("[OGL AVATAR TEMPLATES]: Account cleanup failed for {0}: {1}", principalID, e.Message); } } /// /// Maps explicit portal template identifiers to existing OpenSimulator model /// avatars. Never interprets an arbitrary portal value as an account name. /// Legacy full-name model arguments retain their existing behavior. /// private string ResolveOglStarterModel(string model) { if (string.IsNullOrEmpty(model) || !model.StartsWith("ogl:", StringComparison.OrdinalIgnoreCase)) return model; if (!m_OglStarterTemplatesEnabled) { m_log.Warn("[OGL AVATAR TEMPLATES]: Starter template requested while disabled"); return string.Empty; } if (string.Equals(model, "ogl:benjamin", StringComparison.OrdinalIgnoreCase)) return m_OglRequirePublishedModels ? m_OglBenjaminPublishedModel : m_OglBenjaminTemplate; if (string.Equals(model, "ogl:luna", StringComparison.OrdinalIgnoreCase)) return m_OglRequirePublishedModels ? m_OglLunaPublishedModel : m_OglLunaTemplate; m_log.Warn("[OGL AVATAR TEMPLATES]: Unknown starter template identifier"); return string.Empty; } private bool ValidateOglStarterItems(UUID owner, AvatarAppearance appearance) { if (appearance == null || appearance.Wearables == null) return false; // Empty outfits cannot be published as starter models. bool hasWearables = false; foreach (AvatarWearable wearableSet in appearance.Wearables) { if (wearableSet == null) continue; for (int i = 0; i < wearableSet.Count; i++) { hasWearables = true; if (!ValidateOglStarterItem(owner, wearableSet[i].ItemID)) return false; } } if (!hasWearables) { m_log.Warn("[OGL AVATAR TEMPLATES]: Published model has no wearables"); return false; } List attachments = appearance.GetAttachments(); if (attachments == null) return false; foreach (AvatarAttachment attachment in attachments) { if (attachment == null || !ValidateOglStarterItem(owner, attachment.ItemID)) return false; } return true; } private InventoryItemBase ResolveOglStarterItem(UUID owner, UUID itemId) { if (itemId.IsZero()) return null; InventoryItemBase item = m_InventoryService.GetItem(owner, itemId); // Limit resolution to a single link, as supported by the legacy // avatar copy path. Reject nested or cyclic links. if (item != null && item.AssetType == (int)AssetType.Link) { if (item.AssetID.IsZero() || item.AssetID == itemId) return null; item = m_InventoryService.GetItem(owner, item.AssetID); } return item != null && item.AssetType != (int)AssetType.Link ? item : null; } private bool ValidateOglStarterItem(UUID owner, UUID itemId) { if (itemId.IsZero()) return false; InventoryItemBase item = ResolveOglStarterItem(owner, itemId); uint required = (uint)(PermissionMask.Copy | PermissionMask.Transfer); if (item == null || item.Owner != owner || item.AssetID.IsZero() || (item.CurrentPermissions & required) != required || (item.NextPermissions & required) != required) { m_log.WarnFormat( "[OGL-REGISTRIERUNG] FEHLER: Getragenes Vorlagen-Item {0} (Name={1}, Asset={2}) " + "von Avatar {3} fehlt oder besitzt keine Copy+Transfer-Rechte. " + "Aktuell={4}, NächsterBesitzer={5}; CopyAktuell={6}, TransferAktuell={7}, " + "CopyNaechster={8}, TransferNaechster={9}. " + "Die Vorlage muss mit echten Copy+Transfer-Rechten neu bereitgestellt werden.", itemId, item != null ? item.Name : "nicht gefunden", item != null ? item.AssetID.ToString() : "nicht gefunden", owner, item != null ? item.CurrentPermissions.ToString("X") : "nicht gefunden", item != null ? item.NextPermissions.ToString("X") : "nicht gefunden", item != null && (item.CurrentPermissions & (uint)PermissionMask.Copy) != 0, item != null && (item.CurrentPermissions & (uint)PermissionMask.Transfer) != 0, item != null && (item.NextPermissions & (uint)PermissionMask.Copy) != 0, item != null && (item.NextPermissions & (uint)PermissionMask.Transfer) != 0); return false; } return true; } protected void CreateDefaultAppearanceEntries(UUID principalID) { m_log.DebugFormat("[USER ACCOUNT SERVICE]: Creating default appearance items for {0}", principalID); InventoryFolderBase bodyPartsFolder = m_InventoryService.GetFolderForType(principalID, FolderType.BodyPart); // Get Current Outfit folder InventoryFolderBase currentOutfitFolder = m_InventoryService.GetFolderForType(principalID, FolderType.CurrentOutfit); InventoryItemBase eyes = new InventoryItemBase(UUID.Random(), principalID); eyes.AssetID = AvatarWearable.DEFAULT_EYES_ASSET; eyes.Name = "Default Eyes"; eyes.CreatorId = principalID.ToString(); eyes.AssetType = (int)AssetType.Bodypart; eyes.InvType = (int)InventoryType.Wearable; eyes.Folder = bodyPartsFolder.ID; eyes.BasePermissions = (uint)PermissionMask.All; eyes.CurrentPermissions = (uint)PermissionMask.All; eyes.EveryOnePermissions = (uint)PermissionMask.All; eyes.GroupPermissions = (uint)PermissionMask.All; eyes.NextPermissions = (uint)PermissionMask.All; eyes.Flags = (uint)WearableType.Eyes; m_InventoryService.AddItem(eyes); CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Eyes, eyes.Name, eyes.ID, principalID, currentOutfitFolder.ID); InventoryItemBase shape = new InventoryItemBase(UUID.Random(), principalID); shape.AssetID = AvatarWearable.DEFAULT_BODY_ASSET; shape.Name = "Default Shape"; shape.CreatorId = principalID.ToString(); shape.AssetType = (int)AssetType.Bodypart; shape.InvType = (int)InventoryType.Wearable; shape.Folder = bodyPartsFolder.ID; shape.BasePermissions = (uint)PermissionMask.All; shape.CurrentPermissions = (uint)PermissionMask.All; shape.EveryOnePermissions = (uint)PermissionMask.All; shape.GroupPermissions = (uint)PermissionMask.All; shape.NextPermissions = (uint)PermissionMask.All; shape.Flags = (uint)WearableType.Shape; m_InventoryService.AddItem(shape); CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Shape, shape.Name, shape.ID, principalID, currentOutfitFolder.ID); InventoryItemBase skin = new InventoryItemBase(UUID.Random(), principalID); skin.AssetID = AvatarWearable.DEFAULT_SKIN_ASSET; skin.Name = "Default Skin"; skin.CreatorId = principalID.ToString(); skin.AssetType = (int)AssetType.Bodypart; skin.InvType = (int)InventoryType.Wearable; skin.Folder = bodyPartsFolder.ID; skin.BasePermissions = (uint)PermissionMask.All; skin.CurrentPermissions = (uint)PermissionMask.All; skin.EveryOnePermissions = (uint)PermissionMask.All; skin.GroupPermissions = (uint)PermissionMask.All; skin.NextPermissions = (uint)PermissionMask.All; skin.Flags = (uint)WearableType.Skin; m_InventoryService.AddItem(skin); CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Skin, skin.Name, skin.ID, principalID, currentOutfitFolder.ID); InventoryItemBase hair = new InventoryItemBase(UUID.Random(), principalID); hair.AssetID = AvatarWearable.DEFAULT_HAIR_ASSET; hair.Name = "Default Hair"; hair.CreatorId = principalID.ToString(); hair.AssetType = (int)AssetType.Bodypart; hair.InvType = (int)InventoryType.Wearable; hair.Folder = bodyPartsFolder.ID; hair.BasePermissions = (uint)PermissionMask.All; hair.CurrentPermissions = (uint)PermissionMask.All; hair.EveryOnePermissions = (uint)PermissionMask.All; hair.GroupPermissions = (uint)PermissionMask.All; hair.NextPermissions = (uint)PermissionMask.All; hair.Flags = (uint)WearableType.Hair; m_InventoryService.AddItem(hair); CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Hair, hair.Name, hair.ID, principalID, currentOutfitFolder.ID); InventoryFolderBase clothingFolder = m_InventoryService.GetFolderForType(principalID, FolderType.Clothing); InventoryItemBase shirt = new InventoryItemBase(UUID.Random(), principalID); shirt.AssetID = AvatarWearable.DEFAULT_SHIRT_ASSET; shirt.Name = "Default Shirt"; shirt.CreatorId = principalID.ToString(); shirt.AssetType = (int)AssetType.Clothing; shirt.InvType = (int)InventoryType.Wearable; shirt.Folder = clothingFolder.ID; shirt.BasePermissions = (uint)PermissionMask.All; shirt.CurrentPermissions = (uint)PermissionMask.All; shirt.EveryOnePermissions = (uint)PermissionMask.All; shirt.GroupPermissions = (uint)PermissionMask.All; shirt.NextPermissions = (uint)PermissionMask.All; shirt.Flags = (uint)WearableType.Shirt; m_InventoryService.AddItem(shirt); CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Shirt, shirt.Name, shirt.ID, principalID, currentOutfitFolder.ID); InventoryItemBase pants = new InventoryItemBase(UUID.Random(), principalID); pants.AssetID = AvatarWearable.DEFAULT_PANTS_ASSET; pants.Name = "Default Pants"; pants.CreatorId = principalID.ToString(); pants.AssetType = (int)AssetType.Clothing; pants.InvType = (int)InventoryType.Wearable; pants.Folder = clothingFolder.ID; pants.BasePermissions = (uint)PermissionMask.All; pants.CurrentPermissions = (uint)PermissionMask.All; pants.EveryOnePermissions = (uint)PermissionMask.All; pants.GroupPermissions = (uint)PermissionMask.All; pants.NextPermissions = (uint)PermissionMask.All; pants.Flags = (uint)WearableType.Pants; m_InventoryService.AddItem(pants); CreateCurrentOutfitLink((int)InventoryType.Wearable, (uint)WearableType.Pants, pants.Name, pants.ID, principalID, currentOutfitFolder.ID); if (m_AvatarService != null) { m_log.DebugFormat("[USER ACCOUNT SERVICE]: Creating default avatar entries for {0}", principalID); AvatarWearable[] wearables = new AvatarWearable[6]; wearables[AvatarWearable.EYES] = new AvatarWearable(eyes.ID, eyes.AssetID); wearables[AvatarWearable.BODY] = new AvatarWearable(shape.ID, shape.AssetID); wearables[AvatarWearable.SKIN] = new AvatarWearable(skin.ID, skin.AssetID); wearables[AvatarWearable.HAIR] = new AvatarWearable(hair.ID, hair.AssetID); wearables[AvatarWearable.SHIRT] = new AvatarWearable(shirt.ID, shirt.AssetID); wearables[AvatarWearable.PANTS] = new AvatarWearable(pants.ID, pants.AssetID); AvatarAppearance ap = new AvatarAppearance(); // this loop works, but is questionable for (int i = 0; i < 6; i++) { ap.SetWearable(i, wearables[i]); } m_AvatarService.SetAppearance(principalID, ap); } } protected void EstablishAppearance(UUID destinationAgent, string model) { TryEstablishAppearance(destinationAgent, model); } private bool TryEstablishAppearance(UUID destinationAgent, string model, bool strictStarter = false) { m_log.DebugFormat("[USER ACCOUNT SERVICE]: Establishing new appearance for {0} - {1}", destinationAgent.ToString(), model); if (string.IsNullOrWhiteSpace(model)) return false; string[] modelSpecifiers = model.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (modelSpecifiers.Length != 2) { m_log.WarnFormat("[USER ACCOUNT SERVICE]: Invalid model name \'{0}\'. Falling back to Ruth for {1}", model, destinationAgent); if (!strictStarter) CreateDefaultAppearanceEntries(destinationAgent); return false; } // Does the source model exist? UserAccount modelAccount = GetUserAccount(UUID.Zero, modelSpecifiers[0], modelSpecifiers[1]); if (modelAccount == null) { m_log.WarnFormat("[USER ACCOUNT SERVICE]: Requested model \'{0}\' not found. Falling back to Ruth for {1}", model, destinationAgent); if (!strictStarter) CreateDefaultAppearanceEntries(destinationAgent); return false; } // Does the source model have an established appearance herself? AvatarAppearance modelAppearance = m_AvatarService.GetAppearance(modelAccount.PrincipalID); if (modelAppearance == null) { m_log.WarnFormat("USER ACCOUNT SERVICE]: Requested model \'{0}\' does not have an established appearance. Falling back to Ruth for {1}", model, destinationAgent); if (!strictStarter) CreateDefaultAppearanceEntries(destinationAgent); return false; } try { // Recheck immediately before copying to narrow the window in which // a model owner could revoke permissions after registration preflight. if (m_OglStarterTemplatesEnabled && (string.Equals(model, m_OglBenjaminTemplate, StringComparison.Ordinal) || string.Equals(model, m_OglLunaTemplate, StringComparison.Ordinal) || string.Equals(model, m_OglBenjaminPublishedModel, StringComparison.Ordinal) || string.Equals(model, m_OglLunaPublishedModel, StringComparison.Ordinal)) && !ValidateOglStarterItems(modelAccount.PrincipalID, modelAppearance)) throw new InvalidOperationException("Starter outfit changed or is not transferable"); // Work on a private appearance copy: copying replaces wearable // and attachment inventory IDs and must not mutate the source model. modelAppearance = new AvatarAppearance(modelAppearance); CopyWearablesAndAttachments(destinationAgent, modelAccount.PrincipalID, modelAppearance); if (!m_AvatarService.SetAppearance(destinationAgent, modelAppearance)) throw new InvalidOperationException("Unable to persist starter avatar appearance"); } catch (Exception e) { m_log.WarnFormat("[USER ACCOUNT SERVICE]: Error transferring appearance for {0} : {1}", destinationAgent, e.Message); return false; } m_log.DebugFormat("[USER ACCOUNT SERVICE]: Finished establishing appearance for {0}", destinationAgent.ToString()); return true; } /// /// This method is called by EstablishAppearance to do a copy all inventory items /// worn or attached to the Clothing inventory folder of the receiving avatar. /// In parallel the avatar wearables and attachments are updated. /// private void CopyWearablesAndAttachments(UUID destination, UUID source, AvatarAppearance avatarAppearance) { AvatarWearable[] wearables = avatarAppearance.Wearables; if(wearables.Length == 0) throw new Exception("Model does not have wearables"); // Get Clothing folder of receiver InventoryFolderBase destinationFolder = m_InventoryService.GetFolderForType(destination, FolderType.Clothing); if (destinationFolder == null) throw new InvalidOperationException("Cannot locate destination clothing folder"); // Get Current Outfit folder InventoryFolderBase currentOutfitFolder = m_InventoryService.GetFolderForType(destination, FolderType.CurrentOutfit); // Repair an incorrectly typed clothing folder without modifying // the existing folder's metadata in place. if (destinationFolder.Type != (short)FolderType.Clothing) { destinationFolder = new InventoryFolderBase(); destinationFolder.ID = UUID.Random(); destinationFolder.Name = "Clothing"; destinationFolder.Owner = destination; destinationFolder.Type = (short)FolderType.Clothing; InventoryFolderBase rootFolder = m_InventoryService.GetRootFolder(destination); if (rootFolder == null) throw new InvalidOperationException("Cannot locate destination inventory root folder"); destinationFolder.ParentID = rootFolder.ID; destinationFolder.Version = 1; if (!m_InventoryService.AddFolder(destinationFolder)) throw new InvalidOperationException("Unable to create destination clothing folder"); m_log.InfoFormat("[USER ACCOUNT SERVICE]: Created clothing folder for destination {0}", destination); } if (currentOutfitFolder == null) throw new InvalidOperationException("Cannot locate Current Outfit folder"); // Wearables AvatarWearable basewearable; WearableItem wearable; // Each wearable slot needs a distinct instance. Reusing one mutable // AvatarWearable aliases multiple slots and corrupts the resulting outfit. // copy wearables creating new inventory entries for (int i = 0; i < wearables.Length; i++) { basewearable = wearables[i]; if(basewearable == null || basewearable.Count == 0) continue; AvatarWearable newbasewearable = new AvatarWearable(); for(int j = 0; j < basewearable.Count; j++) { wearable = basewearable[j]; if (!wearable.ItemID.IsZero()) { m_log.DebugFormat("[XXX]: Getting item {0} from avie {1} for {2} {3}", wearable.ItemID, source, i, j); // Get inventory item and copy it InventoryItemBase item = ResolveOglStarterItem(source, wearable.ItemID); if (item != null) { InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination); destinationItem.Name = item.Name; destinationItem.Owner = destination; destinationItem.Description = item.Description; destinationItem.InvType = item.InvType; destinationItem.CreatorId = item.CreatorId; destinationItem.CreatorData = item.CreatorData; destinationItem.NextPermissions = item.NextPermissions; destinationItem.CurrentPermissions = item.CurrentPermissions; destinationItem.BasePermissions = item.BasePermissions; destinationItem.EveryOnePermissions = item.EveryOnePermissions; destinationItem.GroupPermissions = item.GroupPermissions; destinationItem.AssetType = item.AssetType; destinationItem.AssetID = item.AssetID; destinationItem.GroupID = item.GroupID; destinationItem.GroupOwned = item.GroupOwned; destinationItem.SalePrice = item.SalePrice; destinationItem.SaleType = item.SaleType; destinationItem.Flags = item.Flags; destinationItem.CreationDate = item.CreationDate; destinationItem.Folder = destinationFolder.ID; ApplyNextOwnerPermissions(destinationItem); if (!m_InventoryService.AddItem(destinationItem)) throw new InvalidOperationException("Unable to copy starter wearable into destination inventory"); m_log.DebugFormat("[USER ACCOUNT SERVICE]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID); // Wear item newbasewearable.Add(destinationItem.ID,wearable.AssetID); // Add to Current Outfit CreateCurrentOutfitLink((int)InventoryType.Wearable, item.Flags, item.Name, destinationItem.ID, destination, currentOutfitFolder.ID); } else { throw new InvalidOperationException("Starter wearable disappeared during copy"); } } } avatarAppearance.SetWearable(i, newbasewearable); } // Attachments List attachments = avatarAppearance.GetAttachments(); avatarAppearance.ClearAttachments(); foreach (AvatarAttachment attachment in attachments) { int attachpoint = attachment.AttachPoint; UUID itemID = attachment.ItemID; if (!itemID.IsZero()) { // Get inventory item and copy it InventoryItemBase item = ResolveOglStarterItem(source, itemID); if (item != null) { InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination); destinationItem.Name = item.Name; destinationItem.Owner = destination; destinationItem.Description = item.Description; destinationItem.InvType = item.InvType; destinationItem.CreatorId = item.CreatorId; destinationItem.CreatorData = item.CreatorData; destinationItem.NextPermissions = item.NextPermissions; destinationItem.CurrentPermissions = item.CurrentPermissions; destinationItem.BasePermissions = item.BasePermissions; destinationItem.EveryOnePermissions = item.EveryOnePermissions; destinationItem.GroupPermissions = item.GroupPermissions; destinationItem.AssetType = item.AssetType; destinationItem.AssetID = item.AssetID; destinationItem.GroupID = item.GroupID; destinationItem.GroupOwned = item.GroupOwned; destinationItem.SalePrice = item.SalePrice; destinationItem.SaleType = item.SaleType; destinationItem.Flags = item.Flags; destinationItem.CreationDate = item.CreationDate; destinationItem.Folder = destinationFolder.ID; ApplyNextOwnerPermissions(destinationItem); if (!m_InventoryService.AddItem(destinationItem)) throw new InvalidOperationException("Unable to copy starter attachment into destination inventory"); m_log.DebugFormat("[USER ACCOUNT SERVICE]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID); // Attach item avatarAppearance.SetAttachment(attachpoint, destinationItem.ID, destinationItem.AssetID); m_log.DebugFormat("[USER ACCOUNT SERVICE]: Attached {0}", destinationItem.ID); // Add to Current Outfit CreateCurrentOutfitLink(destinationItem.InvType, item.Flags, item.Name, destinationItem.ID, destination, currentOutfitFolder.ID); } else { throw new InvalidOperationException("Starter attachment disappeared during copy"); } } } } protected void CreateCurrentOutfitLink(int invType, uint itemType, string name, UUID itemID, UUID userID, UUID currentOutfitFolderUUID) { UUID LinkInvItem = UUID.Random(); InventoryItemBase itembase = new InventoryItemBase(LinkInvItem, userID) { AssetID = itemID, AssetType = (int)AssetType.Link, CreatorId = userID.ToString(), InvType = invType, Description = "", //Folder = m_InventoryService.GetFolderForType(userID, FolderType.CurrentOutfit).ID, Folder = currentOutfitFolderUUID, Flags = itemType, Name = name, BasePermissions = (uint)PermissionMask.Copy, CurrentPermissions = (uint)PermissionMask.Copy, EveryOnePermissions = (uint)PermissionMask.Copy, GroupPermissions = (uint)PermissionMask.Copy, NextPermissions = (uint)PermissionMask.Copy }; if (!m_InventoryService.AddItem(itembase)) throw new InvalidOperationException("Unable to create Current Outfit link"); } /// /// Apply next owner permissions. /// private void ApplyNextOwnerPermissions(InventoryItemBase item) { if (item.InvType == (int)InventoryType.Object) { uint perms = item.CurrentPermissions; item.CurrentPermissions = perms; } item.CurrentPermissions &= item.NextPermissions; item.BasePermissions &= item.NextPermissions; item.EveryOnePermissions &= item.NextPermissions; } } }