// Total Admin plugin. Copyright (c) 2026 Inxturnal (Total Admin). All rights reserved. // Source-available: you may read it and run it on servers you administer to use Total Admin (https://totaladmin.app/terms). // You may not copy, publish, redistribute, sell or sublicense it, share modified versions, use it (or anything taken from it) with any // service other than Total Admin, or build a competing or imitating service from it. Full terms: LICENSE.txt in the plugin folder of // the repository, and https://totaladmin.app/terms. No warranty. Security reports: support@totaladmin.app. // Reference: Rust.Clans using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Oxide.Core; using Oxide.Core.Libraries; using UnityEngine; namespace Oxide.Plugins { [Info("Total Admin", "Inxturnal", "0.27.0")] [Description("Manage your server from your phone with the Total Admin app: players, chat, reports, kicks and bans.")] public class TotalAdmin : RustPlugin { #region Configuration private Configuration _config; private class Configuration { [JsonProperty("Service address")] public string ServiceUrl = "https://api.totaladmin.app"; // The service signs everything this plugin acts on; replies that don't verify against this key are // ignored. Needed because Oxide makes plugin HTTPS accept any certificate, so the connection alone // doesn't prove who answered. // The live service's signing key (api.totaladmin.app) is baked in so a fresh install just works. If you run // your own service, swap in the key it prints at start-up. [JsonProperty("Service public key")] public string ServicePublicKey = "RSA:AQAB:qW5l3wxPAj4aV/xH6CugaKX7mCYi4bcLsFepDIGyMR7TGMEowVhgfznvPqMhQmdMIT5/Vj7SteQf2etLfcmHRJaLOE91E5HT5ec9p5u5R3bCe9ljiMER19F4XDFN80xnq7bhpzFhDRfB+Rhrzv+J1mv5MK97xqoXxBYVZsycG0RQmOUyKyEqx0KG4Tl0fBNKYmd5PpBvKvz/lkQMvnczSViH0X4oYN2NSbeLlf6X0swRTbBW6FpQ289BGerKj3mteOLj1TYr8qis2G/ci6xjTf9nT/lZemqHH12QTSamyDbVfp6QaoFATAd2kcFtEw6TySrHakqoovfYrex4p1Dz4cq/sHh3Qha5E+2/u7EEnWoY+9suG5oqqNiQG8/5T3cZNesDAWVkQlg25AhwMe/DQzIOMC9Do6g9R5AayNqyxL7YJ45VJ8/WEFBIy1w2btOMN//RA/8xGtBt1CrU0tVaF77zztYsEcBX5nC6S/F3p7Yk2sZOMtXtVOWACVjHwbWD"; [JsonProperty("Send chat")] public bool SendChat = true; [JsonProperty("Send player positions")] public bool SendPositions = true; [JsonProperty("Send player IP addresses")] public bool SendIps = false; // 0.24.0: the names and versions of the plugins this game server has loaded (read from the framework's own plugin list, nothing else on // the machine), so the owner can see them in the app and the operators can see which plugins run alongside this one. Off = never sent. [JsonProperty("Send loaded plugins list")] public bool SendPlugins = true; // 0.23.3: the game's newer animal AI also drives rabbits, squirrels, crabs, jellyfish and turtles; only these go to the map // (prefab short names). Empty = every animal, up to the cap. // 0.23.7: an exclude list instead of an include list, so a species the game adds (sheep and cows came with the November // 2026 update, panthers, tigers and crocodiles with the jungle) reaches the map without a plugin change. The old key // "Animals sent to the map" is ignored. // 0.26.1 (code review 2026-11-19): Replace, not the default Auto, which added the file's names onto these 16 defaults on // every load (TMRust's config had 368 entries, 23 copies). LoadConfig also drops the copies once. [JsonProperty("Animals kept off the map (prefab names: the small ambient creatures)", ObjectCreationHandling = ObjectCreationHandling.Replace)] public List MapAnimalsExcluded = new List { "rabbit", "squirrel", "crabs", "crab", "jellyfish", "seaturtle", "turtle", "fish", "trout", "salmon", "catfish", "sardine", "herring", "anchovy", "orca", "chicken_baby" }; [JsonProperty("Animals sent to the map, and only these (prefab names; empty = every animal not kept off)")] public List MapAnimalsOnly = new List(); [JsonProperty("Send world details (events, NPCs, vehicles, sleepers, Deep Sea)")] public bool SendWorld = true; [JsonProperty("Send bases (tool cupboards: owner, authorised players, upkeep)")] public bool SendBases = true; [JsonProperty("Send the terrain for the sharp zoomed-in map (roads, rivers, coastlines, monument footprints; once per wipe, read slowly over a few seconds)")] public bool SendVectorMap = true; [JsonProperty("Send buildings seen from above for the zoomed-in map (monuments once per wipe, bases when they change shape; read slowly, a few thousand points at a time)")] public bool SendBuildingShapes = true; [JsonProperty("Also save the terrain data to the data folder as TotalAdmin_VectorMap.json when it is sent (for testing; leave off)")] public bool SaveVectorMapCopy = false; [JsonProperty("Compress requests to the service (turn off only if the service is older than 0.19.4)")] public bool Compress = true; [JsonProperty("Say hello to Total Admin once a day (the plugin release, Oxide or Carbon, whether it is paired, and a random id it made for itself: nothing about your server or players), so we can see it is installed and when an update is due")] public bool SendInstallPing = true; [JsonProperty("Send sleeping bags (beds, bags and towels: where, who placed them, who they are assigned to)")] public bool SendBags = true; [JsonProperty("Send land mines (where each one is and who placed it)")] public bool SendLandmines = true; [JsonProperty("Send shops (broadcasting vending machines and their sell orders)")] public bool SendShops = true; [JsonProperty("Send explosive use (raid alerts)")] public bool SendExplosives = true; [JsonProperty("Send downed and revived events")] public bool SendWounds = true; [JsonProperty("Allow teleport from the app")] public bool AllowTeleport = false; [JsonProperty("Allow console commands from the app (owners only)")] public bool AllowConsole = false; // 0.25.1: in the app's live console, a line that keeps repeating (a mod stuck in a loop, any game) shows a few times and then "N more like this hidden" [JsonProperty("Hide repeated log lines in the app's console view")] public bool CollapseRepeatedLogLines = true; public bool AllowDangerousConsole = false; // 0.18.0: ban, kick, quit, restart, give*, spawn, entity.*: bypass the app's kick/ban limits, so a separate opt-in // 0.13.0: lets the server's owner schedule a wipe from the app. Off until the person running THIS server turns it on // (here, or with the console command totaladmin.wipes on): the app alone can never wipe a server. [JsonProperty("Allow scheduled wipes from the app (owners only)")] public bool AllowWipes = false; // Even with console commands allowed, only these commands (first word, e.g. "server.save") may run. // Anything else is refused, so the app can never run arbitrary commands such as ownerid or oxide.grant. [JsonProperty("Console commands the app may run")] public List ConsoleAllowlist = new List(); // Brakes on how much the app can do in a burst, no matter who's asking. [JsonProperty("Max kicks per hour from the app")] public int MaxKicksPerHour = 20; [JsonProperty("Max bans per hour from the app")] public int MaxBansPerHour = 10; [JsonProperty("Batch interval (seconds)")] public float BatchInterval = 2f; [JsonProperty("Event buffer while the service is unreachable")] public int MaxQueuedEvents = 2000; // A new wipe's map is rendered while the server starts, before anyone joins. Rendering // later freezes the server for several seconds, so by default it only happens when empty. [JsonProperty("Render the map image during play only when this many players or fewer are online")] public int MapRenderMaxPlayers = 0; } protected override void LoadDefaultConfig() => _config = new Configuration(); protected override void LoadConfig() { base.LoadConfig(); try { _config = Config.ReadObject(); if (_config == null) throw new Exception("empty"); // 0.26.1 (code review 2026-11-19): clean out the copies the old Auto handling piled up (kept in first-seen order). if (_config.MapAnimalsExcluded != null) _config.MapAnimalsExcluded = _config.MapAnimalsExcluded.Where(n => !string.IsNullOrWhiteSpace(n)).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); SaveConfig(); } catch { PrintError("The config file couldn't be read, so defaults are in use until it's fixed."); LoadDefaultConfig(); } } protected override void SaveConfig() => Config.WriteObject(_config, true); // Requests are signed and bodies encrypted whatever the transport, but HTTPS is still required (plain http only // to this machine, for development): it keeps the metadata (which server talks to which service, when) private. private bool ServiceUrlSafe() { Uri uri; if (!Uri.TryCreate(_config.ServiceUrl ?? "", UriKind.Absolute, out uri)) return false; if (uri.Scheme == Uri.UriSchemeHttps) return true; return uri.Scheme == Uri.UriSchemeHttp && (uri.Host == "localhost" || uri.Host == "127.0.0.1"); } private RSA _serviceKey; private RSA ServiceKey() { if (_serviceKey != null) return _serviceKey; var parts = (_config.ServicePublicKey ?? "").Split(':'); if (parts.Length != 3 || parts[0] != "RSA") return null; try { var rsa = RSA.Create(); rsa.ImportParameters(new RSAParameters { Exponent = Convert.FromBase64String(parts[1]), Modulus = Convert.FromBase64String(parts[2]) }); return _serviceKey = rsa; } catch (Exception e) { PrintError($"\"Service public key\" isn't valid: {e.Message}"); return null; } } private float _lastSkewWarning = -999f; // Returns the signed payload if the envelope verifies against the pinned key and is fresh, else null. The signature // is checked over the exact bytes first; only then is an encrypted body ("iv" present) decrypted with the transport // key. With a nonce given, the payload must name it: a reply then answers that one request and nothing else. private JObject Verified(JToken envelope, string nonce = null, bool allowPlain = false) { var key = ServiceKey(); if (key == null || !(envelope is JObject)) return null; try { var body = Convert.FromBase64String((string)envelope["signed"] ?? ""); var sig = Convert.FromBase64String((string)envelope["sig"] ?? ""); var iv = (string)envelope["iv"]; // Once paired, only encrypted replies count (the pair reply is the one plain one): a stolen signing key // alone must not be enough to instruct this server. if (iv == null && !allowPlain) return null; if (iv != null && !Paired) return null; var ivBytes = iv != null ? Convert.FromBase64String(iv) : new byte[0]; var signedBytes = new byte[ivBytes.Length + body.Length]; // the service signs iv || ciphertext Buffer.BlockCopy(ivBytes, 0, signedBytes, 0, ivBytes.Length); Buffer.BlockCopy(body, 0, signedBytes, ivBytes.Length, body.Length); if (!key.VerifyData(signedBytes, sig, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) return null; if (iv != null) body = AesDecrypt(Convert.FromBase64String(_pairing.TransportKey), ivBytes, body); var payload = JObject.Parse(Encoding.UTF8.GetString(body)); var issued = payload.Value("issued_at") ?? 0; var skew = Epoch() - issued; if (Math.Abs(skew) > 300) // stale, replayed, or this server's clock is wrong { var now = UnityEngine.Time.realtimeSinceStartup; if (now - _lastSkewWarning > 60f) { _lastSkewWarning = now; PrintWarning($"Ignored a service reply stamped {skew:F0} s off this server's clock. If this keeps happening the server's time is wrong, and actions won't run until it's fixed."); } return null; } if (nonce != null && (string)payload["nonce"] != nonce) return null; return payload; } catch { return null; } } private JObject VerifiedFor(string response) { JObject payload; try { payload = Verified(JObject.Parse(response), _replyNonce); } catch { return null; } return payload != null && (string)payload["server_id"] == _pairing.ServerId ? payload : null; } // A 401 only ends the pairing if the service signed "unpaired" for this server. private bool SignedUnpaired(string response) { try { var payload = Verified(JObject.Parse(response)["detail"], _replyNonce); return payload != null && (string)payload["server_id"] == _pairing.ServerId && (string)payload["error"] == "unpaired"; } catch { return false; } } #region Keys and ciphers private RSA _pluginKey; /// This plugin's own RSA key from the pairing file, or null when not paired. private RSA PluginKey() { if (_pluginKey != null) return _pluginKey; var k = _pairing.PluginKey; if (k == null) return null; try { var rsa = RSA.Create(); rsa.ImportParameters(new RSAParameters { Modulus = Convert.FromBase64String(k["Modulus"]), Exponent = Convert.FromBase64String(k["Exponent"]), D = Convert.FromBase64String(k["D"]), P = Convert.FromBase64String(k["P"]), Q = Convert.FromBase64String(k["Q"]), DP = Convert.FromBase64String(k["DP"]), DQ = Convert.FromBase64String(k["DQ"]), InverseQ = Convert.FromBase64String(k["InverseQ"]), }); return _pluginKey = rsa; } catch (Exception e) { PrintError($"The pairing file's key is damaged ({e.Message}). Pair again with totaladmin.pair."); return null; } } private static Dictionary KeyToData(RSAParameters k) => new Dictionary { ["Modulus"] = Convert.ToBase64String(k.Modulus), ["Exponent"] = Convert.ToBase64String(k.Exponent), ["D"] = Convert.ToBase64String(k.D), ["P"] = Convert.ToBase64String(k.P), ["Q"] = Convert.ToBase64String(k.Q), ["DP"] = Convert.ToBase64String(k.DP), ["DQ"] = Convert.ToBase64String(k.DQ), ["InverseQ"] = Convert.ToBase64String(k.InverseQ), }; /// "RSA::", the form the service stores and fingerprints. private static string PublicKeyText(RSAParameters k) => "RSA:" + Convert.ToBase64String(k.Exponent) + ":" + Convert.ToBase64String(k.Modulus); private static string Sha256Hex(byte[] data) { using (var sha = SHA256.Create()) { var sb = new StringBuilder(); foreach (var b in sha.ComputeHash(data)) sb.Append(b.ToString("x2")); return sb.ToString(); } } private static string NewNonce() { var bytes = new byte[18]; using (var rng = RandomNumberGenerator.Create()) rng.GetBytes(bytes); return Convert.ToBase64String(bytes).Replace('+', '-').Replace('/', '_').TrimEnd('='); } /// The request signature the service checks: method, path (with query), time, nonce and the body's hash. private string SignRequest(string method, string path, string ts, string nonce, string body) { var key = PluginKey(); if (key == null) return null; var line = string.Join("\n", new[] { method, path, ts, nonce, Sha256Hex(Encoding.UTF8.GetBytes(body ?? "")) }); return Convert.ToBase64String(key.SignData(Encoding.UTF8.GetBytes(line), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)); } private static byte[] AesRun(byte[] key, byte[] iv, byte[] data, bool encrypt) { using (var aes = Aes.Create()) { aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = key; aes.IV = iv; using (var t = encrypt ? aes.CreateEncryptor() : aes.CreateDecryptor()) return t.TransformFinalBlock(data, 0, data.Length); } } private static byte[] AesDecrypt(byte[] key, byte[] iv, byte[] data) => AesRun(key, iv, data, false); /// A request body as the service expects it: {"v":1,"iv":...,"data":...}, AES-256-CBC with a fresh IV. private string EncryptBody(string json) { var iv = new byte[16]; using (var rng = RandomNumberGenerator.Create()) rng.GetBytes(iv); var raw = Encoding.UTF8.GetBytes(json ?? "{}"); var env = new Dictionary { ["v"] = 1 }; // 0.19.0: bodies over 600 bytes are gzipped before they are encrypted ("z": 1); the numbers in them compress five to ten times. Needs service 0.19.4+. if (raw.Length > 600 && _config.Compress) { using (var ms = new MemoryStream()) { using (var z = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) z.Write(raw, 0, raw.Length); raw = ms.ToArray(); } env["z"] = 1; } var data = AesRun(Convert.FromBase64String(_pairing.TransportKey), iv, raw, true); env["iv"] = Convert.ToBase64String(iv); env["data"] = Convert.ToBase64String(data); return JsonConvert.SerializeObject(env); } #endregion // Action ids already run, with when and how they ended. Saved to disk so a captured reply replayed after a // reload or restart (inside the issued_at window) is still refused, and a redelivered action gets its // original result back instead of silence. private class SeenAction { public double T; public bool Ok; public string Error; } private Dictionary _seen = new Dictionary(); private const long SeenKeepSeconds = 900; // well past the 300 s issued_at window private string SeenFile => Name + "_SeenActions"; private void LoadSeen() { try { _seen = Interface.Oxide.DataFileSystem.ReadObject>(SeenFile) ?? new Dictionary(); } catch { _seen = new Dictionary(); } PruneSeen(); } private void SaveSeen() => Interface.Oxide.DataFileSystem.WriteObject(SeenFile, _seen); private void PruneSeen() { double cutoff = Epoch() - SeenKeepSeconds; foreach (var k in _seen.Where(kv => kv.Value == null || kv.Value.T < cutoff).Select(kv => kv.Key).ToList()) _seen.Remove(k); } #endregion #region Localization protected override void LoadDefaultMessages() => lang.RegisterMessages(_defaultMessages, this); private readonly Dictionary _defaultMessages = new Dictionary { ["PairUsage"] = "Usage: totaladmin.pair (get the code from Add server in the Total Admin app)", ["Pairing"] = "Pairing with Total Admin...", ["Paired"] = "Paired with Total Admin. Server owners can now sign in to the app with Steam. Using Total Admin means you accept its Terms (https://totaladmin.app/terms) and this plugin's licence (https://totaladmin.app/plugin/LICENSE.txt).", ["PairFailed"] = "Pairing failed: {0}", ["PairTampered"] = "Pairing refused: the service paired a key that isn't this plugin's, so something between this server and the service changed the request. Unpair the new entry in the app and check the server's network and DNS before having another go.", ["Unpaired"] = "Unpaired from Total Admin.", ["NotPaired"] = "Not paired. Use totaladmin.pair .", ["Status"] = "Total Admin {0}: {1}. Last contact {2}. Events waiting: {3}.", ["StatusService"] = "Service: {0}", ["OwnerOnly"] = "Only server owners can use this command.", ["AdminPrefix"] = "[Admin]", ["Warning"] = "Warning from the admins: {0}", ["KickDefault"] = "Kicked by an admin", ["ChatFilterWarn"] = "Your message was blocked by the server's chat filter ({0}).", ["YouAreMuted"] = "You are muted, so your message was not sent.", ["WipeWarn"] = "Server wipe in {0}. The server will restart and the map is replaced.", ["MutedFor"] = "You have been muted for {0}.", ["MutedPermanently"] = "You have been muted permanently.", ["BanDefault"] = "Banned by an admin", ["BanKick"] = "Banned: {0}", ["code_invalid"] = "that code is not valid", ["code_expired"] = "that code has expired; make a new one in the app", ["NoServiceKey"] = "Set \"Service public key\" in oxide/config/TotalAdmin.json first (the service prints it at start-up).", ["too_many_servers"] = "that account already has the maximum number of paired servers", ["not_owner"] = "the app account that made this code isn't a server owner: add it with ownerid, or give it app-only access with oxide.grant user totaladmin.owner", }; private string Msg(string key, params object[] args) { var text = lang.GetMessage(key, this); // Oxide keeps the language file it loaded at start-up in memory, so after an update a key that is new in this // release comes back as the key itself until the server restarts. Fall back to the built-in text (0.8.10). if (text == key && _defaultMessages.TryGetValue(key, out var fallback)) text = fallback; return args.Length > 0 ? string.Format(text, args) : text; } #endregion #region State private const string PermOwner = "totaladmin.owner"; private const string PermViewer = "totaladmin.viewer"; private const string PermModerator = "totaladmin.moderator"; private const string PermAdmin = "totaladmin.admin"; // What pairing leaves behind (oxide/data/TotalAdmin.json): the server's id at the service, this plugin's own RSA // key (it signs every request, so no secret ever travels), and the transport key the service handed over encrypted // to that RSA key (it encrypts every request and reply body). Treat the file like a password. private class PairingData { public string ServerId; public Dictionary PluginKey; // RSA parameters, base64 (Modulus, Exponent, D, P, Q, DP, DQ, InverseQ) public string TransportKey; // base64, 32 bytes public string MapUploadedFor; // wipe id of the last map image the service accepted public string Owner; // the paired (or transferred-to) owner, as the service reports it on each poll; set_role never touches them } private PairingData _pairing = new PairingData(); private readonly List> _events = new List>(); private int _seq; private bool _sending; private bool _polling; private float _sendingSince, _pollSince, _mapBusySince, _staticBusySince; private int _sendGen, _pollGen; private const float StuckRequestSeconds = 90f; // longest request timeout is 35 s // Every now and then Oxide never calls a web callback back. Without this, one lost callback stopped all batches // (or all action polling) until the plugin was reloaded. private void Watchdog() { var now = UnityEngine.Time.realtimeSinceStartup; if (_sending && now - _sendingSince > StuckRequestSeconds) { _sending = false; _sendGen++; _gateHash.Clear(); PrintWarning("A batch request never came back - sending it again."); } if (_mapBusy && now - _mapBusySince > StuckRequestSeconds) _mapBusy = false; if (_chatFetching && now - _chatFetchSince > StuckRequestSeconds) _chatFetching = false; // 0.18.0: requests whose reply never came would stay "busy" for good if (_tailSending && now - _tailSendingSince > StuckRequestSeconds) _tailSending = false; if (_commandsSent && !_commandsDone && now - _commandsSentAt > StuckRequestSeconds) _commandsSent = false; if (_staticBusy && now - _staticBusySince > StuckRequestSeconds) _staticBusy = false; if (_vectorBusy && now - _vectorBusySince > 300f) { _vectorBusy = false; _vecCells = null; _vecHeights = null; } if (_polling && now - _pollSince > StuckRequestSeconds) { PrintWarning("An action poll never came back - polling again."); _polling = false; _pollGen++; StartPolling(); } } private bool _unloading; private float _pollBackoff = 2f; private float _positionInterval = 30f; private float _snapshotInterval = 10f; private float _lastSnapshot = -999f; private string _noticedVersion; // the release already announced in the console this load, so the notice shows once private float _lastPositions = -999f; private DateTime _lastContact = DateTime.MinValue; private Timer _batchTimer; private bool _mapWanted; private bool _mapBusy; private float _lastMapAttempt = -9999f; private Dictionary _mapReady; // rendered at startup, waiting for the service to ask private const float MapScale = 0.5f; private float _lastPlugins = -999999f; // 0.24.0: when the loaded-plugins list was last sent (it is sent again whenever one loads or unloads) private float _lastWorld = -999f, _lastBases = -999f, _lastShops = -999f, _lastBags = -999f, _lastMines = -999f; private bool _staticWanted, _staticBusy; // 0.21.0: the vector map. The terrain is read a slice per tick (about 16,000 samples), so a server never stalls, then sent once. private bool _vectorBusy; private float _vectorBusySince, _lastVectorAttempt = -9999f; private string _vecWipe; private int _vecGrid, _vecHeightGrid, _vecRow, _vecStage; private byte[] _vecCells; private float[] _vecHeights; private readonly HashSet _tracked = new HashSet(); // world events + vehicles private readonly HashSet _animals = new HashSet(); // 0.23.2: bears, wolves, boars, stags, chickens (BaseNPC2, the newer animal AI) and any BaseAnimalNPC private const int MaxAnimals = 1000; private readonly HashSet _landmines = new HashSet(); // 0.22.0 private readonly HashSet _cupboards = new HashSet(); private readonly HashSet _vendors = new HashSet(); private const int MaxNpcs = 1000, MaxVehicles = 500, MaxSleepers = 1000, MaxBases = 3000, MaxShops = 500; private const int MaxOnline = 1000, MaxTeams = 1000; // 0.20.0: the most players one snapshot or position sample lists; above it the rest are left out and the snapshot says so private bool Paired => !string.IsNullOrEmpty(_pairing.TransportKey) && _pairing.PluginKey != null && !string.IsNullOrEmpty(_pairing.ServerId); private float _worldInterval = 10f; // Banned SteamIDs (with names) as of now, so only a genuinely new ban is reported. At startup the server // re-adds every ban from its ban list, which used to show up as fresh bans after each restart. private readonly Dictionary _knownBans = new Dictionary(); // Who asked for a kick or ban from the app, so the kick/ban event that follows names them: the service then // does not tell that admin about their own action. Read within ten seconds of the action, else ignored. private readonly Dictionary> _actionActor = new Dictionary>(); private bool _ready; // false until OnServerInitialized: ban list entries before that are existing bans // Events not yet sent when the plugin unloads (server restart, reload) are kept here and sent after. private string QueueFile => Name + "_Queue"; private string InstallFile => Name + "_Install"; // 0.20.2: a random id this copy of the plugin makes for itself (kept in oxide/data/TotalAdmin_Install.json) so a daily hello can be counted once. private class InstallData { public string Id; } private string _installId; private string InstallId() { if (!string.IsNullOrEmpty(_installId)) return _installId; try { _installId = SafeRead(InstallFile)?.Id; } catch { } if (string.IsNullOrEmpty(_installId) || _installId.Length != 32) { _installId = Guid.NewGuid().ToString("N"); try { SafeWrite(InstallFile, new InstallData { Id = _installId }); } catch { } } return _installId; } // Once a day, unsigned (an unpaired copy has no key yet), and never allowed to matter: a failure is ignored. The switch is in the config. private void SendHello() { if (_unloading) return; try { if (_config.SendInstallPing && ServiceUrlSafe()) Request("/v1/plugin/hello", JsonConvert.SerializeObject(new Dictionary { ["id"] = InstallId(), ["version"] = Version.ToString(), ["framework"] = DetectFramework(), ["paired"] = Paired, }), RequestMethod.POST, false, 15f, (status, response) => { }); } catch (Exception) { } timer.Once(86400f + UnityEngine.Random.Range(0f, 1800f), SendHello); } // 0.8.12: mutes made from the app, online or offline, timed or permanent (oxide/data/TotalAdmin_Mutes.json). The game's // ChatMute flag is what actually silences a player; this list is what says who is muted, by whom, why and until when, // so it survives the player leaving, a plugin reload and a server restart, and so an expiry can lift it. private class MuteEntry { public double Until; public string By; public string Reason; public double At; public string Name; } // Until -1 = permanent private string MutesFile => Name + "_Mutes"; private Dictionary _mutes = new Dictionary(); private float _lastMuteSweep = -999f; private const int MaxMutes = 2000; private void LoadMutes() { try { _mutes = SafeRead>(MutesFile) ?? new Dictionary(); } catch (Exception e) { PrintWarning($"The mute list could not be read and starts empty: {e.Message}"); _mutes = new Dictionary(); } } private void SaveMutes() => SafeWrite(MutesFile, _mutes); // 0.18.0: data files are written to a temporary file and swapped in, with the last good copy kept as .bak, so a crash mid-write cannot // leave a half file; a file that will not read is set aside as .bad and the .bak is tried before starting empty. private static string DataPath(string name) => Path.Combine(Interface.Oxide.DataDirectory, name + ".json"); private void SafeWrite(string name, object value) { try { Interface.Oxide.DataFileSystem.WriteObject(name + "_tmp", value); var tmp = DataPath(name + "_tmp"); var dst = DataPath(name); if (File.Exists(dst)) File.Replace(tmp, dst, dst + ".bak"); else File.Move(tmp, dst); } catch (Exception e) { PrintWarning($"Safe write of {name} failed ({e.Message}); writing directly."); Interface.Oxide.DataFileSystem.WriteObject(name, value); } } private T SafeRead(string name) where T : class { try { return Interface.Oxide.DataFileSystem.ReadObject(name); } catch (Exception e) { PrintError($"{name}.json could not be read ({e.Message}); it is set aside as .bad."); try { var p = DataPath(name); if (File.Exists(p)) File.Copy(p, p + ".bad", true); } catch { } try { var bak = DataPath(name) + ".bak"; if (File.Exists(bak)) return JsonConvert.DeserializeObject(File.ReadAllText(bak)); } catch { } return null; } } private static bool MuteLive(MuteEntry m) => m != null && (m.Until < 0 || m.Until > Epoch()); /// Set or clear the game's chat-mute flag on a player who is online or asleep in the world; nobody else holds the flag. private const long PermanentMuteUntil = 4102444800; // 2100-01-01: the game's own mute state wants an expiry time, so "permanent" is far away /// 0.8.13: the game keeps a mute in the player's saved state (State.chatMuted + the expiry) and re-derives the /// ChatMute flag from it every few seconds, so a flag set on its own is wiped at once. Set both, as the game's own /// global.mute does; the game then also ends a timed mute and keeps it across restarts by itself. private static void ApplyChatMute(BasePlayer p, bool muted, double until) { if (p == null) return; var state = p.State; if (state != null) { state.chatMuted = muted; state.chatMuteExpiryTimestamp = muted ? (until < 0 ? PermanentMuteUntil : (long)until) : 0; } if (p.HasPlayerFlag(BasePlayer.PlayerFlags.ChatMute) != muted) p.SetPlayerFlag(BasePlayer.PlayerFlags.ChatMute, muted); } private static void SetChatMute(ulong steamId, bool muted, double until = -1) { ApplyChatMute(BasePlayer.FindByID(steamId) ?? BasePlayer.FindSleeping(steamId), muted, until); } /// Tell a muted player they are muted and for how long, like the game's own mute command does: the game /// drops a muted player's chat silently, so without this they get no feedback at all. private void TellMuted(BasePlayer p, MuteEntry m) { if (p == null || m == null || !p.IsConnected) return; if (m.Until < 0) { p.ChatMessage(Msg("MutedPermanently")); return; } var left = TimeSpan.FromSeconds(Math.Max(1, m.Until - Epoch())); var text = left.TotalHours >= 1 ? $"{(int)left.TotalHours} hour(s) {left.Minutes} minute(s)" : left.TotalMinutes >= 1 ? $"{(int)Math.Ceiling(left.TotalMinutes)} minute(s)" : $"{(int)left.TotalSeconds} second(s)"; p.ChatMessage(Msg("MutedFor", text)); } /// Lift every mute whose time is up. Runs with the batch tick, so a mute ends within a few seconds of its expiry. private float _lastMapSweep; // 0.18.0: the small per-player maps (invites, accepts, kicks, chat hits, repeats) forget old entries and stop at a fixed size. private void SweepMaps() { var cutoff = Epoch() - 3600; foreach (var k in _invites.Where(kv => kv.Value.Value < cutoff).Select(kv => kv.Key).ToList()) _invites.Remove(k); foreach (var k in _recentAccepts.Where(kv => kv.Value < cutoff).Select(kv => kv.Key).ToList()) _recentAccepts.Remove(k); foreach (var k in _teamKicks.Where(kv => kv.Value.Value < cutoff).Select(kv => kv.Key).ToList()) _teamKicks.Remove(k); foreach (var k in _chatHits.Where(kv => kv.Value.Count == 0 || kv.Value[kv.Value.Count - 1] < Epoch() - 3600).Select(kv => kv.Key).ToList()) _chatHits.Remove(k); if (_invites.Count > 2000) _invites.Clear(); if (_recentAccepts.Count > 2000) _recentAccepts.Clear(); if (_teamKicks.Count > 2000) _teamKicks.Clear(); if (_chatHits.Count > 2000) _chatHits.Clear(); } private void SweepMutes() { if (_mutes.Count == 0) return; var now = Epoch(); var ended = _mutes.Where(kv => kv.Value == null || (kv.Value.Until >= 0 && kv.Value.Until <= now)).Select(kv => kv.Key).ToList(); if (ended.Count == 0) return; foreach (var id in ended) { _mutes.Remove(id); SetChatMute(id, false); } SaveMutes(); SnapshotSoon(); } private List> MuteList(out bool truncated) { truncated = false; var list = new List>(); foreach (var kv in _mutes) { if (!MuteLive(kv.Value)) continue; var m = kv.Value; list.Add(new Dictionary { ["id"] = kv.Key.ToString(), ["until"] = m.Until > 0 ? (object)m.Until : -1L, ["by"] = m.By, ["reason"] = m.Reason, ["at"] = m.At, ["name"] = m.Name }); if (list.Count >= MaxMutes) { truncated = true; break; } } return list; } #endregion #region Lifecycle private void Init() { permission.RegisterPermission(PermOwner, this); permission.RegisterPermission(PermViewer, this); permission.RegisterPermission(PermModerator, this); permission.RegisterPermission(PermAdmin, this); _pairing = SafeRead(Name) ?? new PairingData(); LoadSeen(); LoadQueue(); LoadMutes(); LoadTeams(); LoadWipe(); } // initial: true when the server itself is starting, false when the plugin is (re)loaded later. private void OnServerInitialized(bool initial) { WipeStartup(initial); timer.Once(45f, SendHello); // 0.20.2: the daily hello (see SendInstallPing) // Server start is the cheap moment to render a new wipe's map: nobody is playing yet. if (initial && Paired && _pairing.MapUploadedFor != WipeId()) _mapReady = RenderMap(); foreach (var net in BaseNetworkable.serverEntities) Track(net as BaseEntity); _knownBans.Clear(); foreach (var u in ServerUsers.GetAll(ServerUsers.UserGroup.Banned)) _knownBans[u.steamid] = u.username; _ready = true; if (initial) AddEvent("server_start", new Dictionary { ["bans"] = _knownBans.Count, ["plugin_version"] = Version.ToString(), ["wipe_id"] = WipeId() }); _batchTimer = timer.Every(Mathf.Max(1f, _config.BatchInterval), Tick); if (Paired) StartPolling(); } // Called before plugins unload on a shutdown; the event is saved with the queue and sent after the restart. private void OnServerShutdown() { AddEvent("server_stop", new Dictionary()); _stopping = true; // 0.22.1: the teardown after this (everyone dropped, sleepers and NPCs killed, bases unloaded) is not play: it is not listed } private bool _stopping; private void Unload() { _unloading = true; foreach (var t in _wipeTimers) t?.Destroy(); StopTail(); _batchTimer?.Destroy(); // A batch still in flight may also arrive; the service drops the repeat. if (Paired) SafeWrite(QueueFile, _events); } private void LoadQueue() { try { var saved = Interface.Oxide.DataFileSystem.ReadObject>>(QueueFile); if (saved != null && Paired) _events.AddRange(saved.Where(e => e != null)); } catch { } // Cleared once read, so a crash (no Unload) doesn't send the same events again on the next start. SafeWrite(QueueFile, new List>()); } private void SavePairing() => SafeWrite(Name, _pairing); #endregion #region Scheduled wipe (0.13.0) // The owner schedules a wipe in the app; the service only arms and cancels it. The plugin keeps the plan in its own data file and runs // its own timers, so the wipe happens (or not) whatever the service is doing. The sequence: warnings in chat, then `restart 60` // (Rust saves, counts down and EXITS: the host must start it again), then at the next start-up, in the window after the game has set // its seed and before it builds the map, the old save is renamed aside, the seed is changed if asked, and the game makes a new world. // Files are renamed (name.pre-wipe-