Example #1
0
        private static bool ShouldServerRestart()
        {
            bool flag = false;

            try
            {
                int num = ConfigFile.ServerConfig.GetInt("restart_after_rounds");
                flag = num > 0 && RoundRestart.UptimeRounds >= num;
            }
            catch (Exception ex)
            {
                ServerConsole.AddLog("Failed to check the restart_after_rounds config value: " + ex.Message, ConsoleColor.Red);
            }

            return(flag);
        }
Example #2
0
        public void Enable()
        {
            Harmony.PatchAll();
            foreach (var arg in Environment.GetCommandLineArgs())
            {
                const string consoleArg = "-console";

                if (arg.StartsWith(consoleArg))
                {
                    if (ushort.TryParse(arg.Substring(consoleArg.Length), out var consolePort))
                    {
                        ConsolePort = consolePort;
                    }
                }
            }

            ServerConsole.AddLog($"Starting TcpClient on port {ConsolePort}");

            TcpClient = new TcpClient();

            try
            {
                TcpClient.Connect(new IPEndPoint(IPAddress.Loopback, ConsolePort));
            }
            catch
            {
                return;
            }

            SendMessage("LocalAdminPlus Companion connected!");

            var streamReader = new StreamReader(TcpClient.GetStream());

            Task.Run(async() =>
            {
                while (true)
                {
                    if (!streamReader.EndOfStream)
                    {
                        ServerConsole.EnterCommand(streamReader.ReadLine());
                    }

                    await Task.Delay(10);
                }
            });
        }
Example #3
0
        /// <summary>
        /// Runs the plugin manager, by loading all dependencies, plugins, configs and then enables all plugins.
        /// </summary>
        /// <param name="dependencies">The dependencies that could have been loaded by Exiled.Bootstrap.</param>
        public static void Run(Assembly[] dependencies = null)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? CheckUAC() : geteuid() == 0)
            {
                ServerConsole.AddLog("YOU ARE RUNNING THE SERVER AS ROOT / ADMINISTRATOR. THIS IS HIGHLY UNRECOMMENDED. PLEASE INSTALL YOUR SERVER AS A NON-ROOT/ADMIN USER.", ConsoleColor.Red);
                Thread.Sleep(5000);
            }

            if (dependencies?.Length > 0)
            {
                Dependencies.AddRange(dependencies);
            }

            LoadDependencies();
            LoadPlugins();

            ConfigManager.Reload();
            TranslationManager.Reload();

            if (!Config.IsEnabled)
            {
                Log.Warn("Loading EXILED has been disabled in a config. No plugins will be enabled.");
                return;
            }

            EnablePlugins();

            BuildInfoCommand.ModDescription = string.Join(
                "\n",
                AppDomain.CurrentDomain.GetAssemblies()
                .Where(a => a.FullName.StartsWith("Exiled.", StringComparison.OrdinalIgnoreCase))
                .Select(a => $"{a.GetName().Name} - Version {a.GetName().Version.ToString(3)}"));
            ServerConsole.AddLog(
                @"Welcome to
   ▄████████ ▀████    ▐████▀  ▄█   ▄█          ▄████████ ████████▄
  ███    ███   ███▌   ████▀  ███  ███         ███    ███ ███   ▀███
  ███    █▀     ███  ▐███    ███▌ ███         ███    █▀  ███    ███
 ▄███▄▄▄        ▀███▄███▀    ███▌ ███        ▄███▄▄▄     ███    ███
▀▀███▀▀▀        ████▀██▄     ███▌ ███       ▀▀███▀▀▀     ███    ███
  ███    █▄    ▐███  ▀███    ███  ███         ███    █▄  ███    ███
  ███    ███  ▄███     ███▄  ███  ███▌    ▄   ███    ███ ███   ▄███
  ██████████ ████       ███▄ █▀   █████▄▄██   ██████████ ████████▀
                                  ▀                                 ", ConsoleColor.Green);
        }
Example #4
0
        // ReSharper disable once UnusedMember.Global
        public static void LoadModSystem()
        {
            if (_loaded)
            {
                return;
            }
            ServerConsole.AddLog("Synapse Mod-Loader is now initialising.. :)", ConsoleColor.Blue);

            try
            {
                var startupFile = Assembly.GetExecutingAssembly().Location.Replace($"SCPSL_Data{Path.DirectorySeparatorChar}Managed{Path.DirectorySeparatorChar}Assembly-CSharp.dll", "SynapseStart-config.yml");
                if (!File.Exists(startupFile))
                {
                    ServerConsole.AddLog($"Synapse Mod-Loader Start file is missing ... creating: {startupFile}", ConsoleColor.Blue);
                    File.Create(startupFile).Close();
                    File.WriteAllLines(startupFile, new [] { "synapse_installation: default" });
                }
                var config = new YamlConfig(startupFile);

                var text = config.GetString("synapse_installation", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Synapse"));
                if (!Directory.Exists(text))
                {
                    Directory.CreateDirectory(text);
                }
                if (!File.Exists(Path.Combine(text, "Synapse.dll")))
                {
                    ServerConsole.AddLog("Error while loading Synapse! The Synapse.dll is missing!", ConsoleColor.Red);
                    return;
                }
                var methodInfo = Assembly.Load(ReadFile(Path.Combine(text, "Synapse.dll"))).GetTypes()
                                 .SelectMany(p => p.GetMethods()).FirstOrDefault(f => f.Name == "LoaderExecutionCode");
                if (!(methodInfo != null))
                {
                    return;
                }
                methodInfo.Invoke(null, null);
                _loaded = true;
            }
            catch (Exception e)
            {
                ServerConsole.AddLog($"Synapse Mod-Loader startup Error: {e}", ConsoleColor.Red);
            }
        }
Example #5
0
        //The below method gets called when the plugin is enabled by the EXILED loader.
        public override void OnEnable()
        {
            Log.Info(Environment.CurrentDirectory);
            Log.Info("Enabled.");
            Log.Info($"Checking version status...");
            ServerConsole.AddLog($"ServerMod - Version {Version.Major}.{Version.Minor}.{Version.Patch}-EXILED LOGTYPE-8");
            if (Config.GetBool("exiled_auto_update", true))
            {
                if (IsUpdateAvailable())
                {
                    Log.Info("There is an new version of EXILED available.");
                    AutoUpdate();
                }
            }

            ReloadConfigs();
            Log.Debug("Adding Event Handlers...");
            handlers = new EventHandlers(this);

            Events.WaitingForPlayersEvent  += handlers.OnWaitingForPlayers;
            Events.RoundStartEvent         += handlers.OnRoundStart;
            Events.RemoteAdminCommandEvent += ReloadCommandHandler.CommandHandler;
            Events.PlayerLeaveEvent        += handlers.OnPlayerLeave;
            Events.PlayerDeathEvent        += handlers.OnPlayerDeath;
            Events.PlayerJoinEvent         += handlers.OnPlayerJoin;
            Events.SetClassEvent           += handlers.OnSetClass;

            Log.Debug("Patching...");
            try
            {
                //You must use an incrementer for the harmony instance name, otherwise the new instance will fail to be created if the plugin is reloaded.
                patchFixer++;
                instance = HarmonyInstance.Create($"exiled.patches{patchFixer}");
                instance.PatchAll();
            }
            catch (Exception exception)
            {
                Log.Error($"Patching failed! {exception}");
            }

            Log.Debug("Patching complete. c:");
            ServerConsole.ReloadServerName();
        }
Example #6
0
        public override void OnEnable()
        {
            Plugin.Info("[OnEnable] Enabled.");

            ServerConsole.AddLog($"ServerMod - Version {EventPlugin.Version.Major}.{EventPlugin.Version.Minor}.{EventPlugin.Version.Patch}-EXILED");
            ServerConsole.AddLog($"Player connect: ");

            try
            {
                eventHandler = new EventHandler();
                Events.RoundRestartEvent += eventHandler.OnRoundRestart;
                Events.RemoteAdminCommandEvent += eventHandler.OnRACommand;

                harmony = HarmonyInstance.Create("com.sanyae2439." + this.getName);
                harmony.PatchAll();
            }
            catch(System.Exception e)
            {
                Plugin.Error($"[OnEnable] Error:{e}");
            }
        }
Example #7
0
        static MultiAdminFeatures()
        {
            foreach (string startArg in Environment.GetCommandLineArgs())
            {
                if (startArg.StartsWith(MULTIADMIN_CONSOLE_PREFIX, StringComparison.OrdinalIgnoreCase))
                {
                    MultiAdminUsed = true;

                    IEnumerable <string> separatedInfo = startArg.Split(MultiAdminValueSeparator).Skip(1);
                    MultiAdminVersion = separatedInfo.ElementAtOrDefault(0);
                    string features = separatedInfo.ElementAtOrDefault(1);
                    if (!string.IsNullOrEmpty(features) && int.TryParse(features, out int modFeatures))
                    {
                        MultiAdminModFeatures = (ModFeatures)modFeatures;
                        return;
                    }

                    ServerConsole.AddLog($"Failed to parse MultiAdmin ModFeatures! Source: {features}", ConsoleColor.Red);
                    break;
                }
            }
        }
Example #8
0
 // Token: 0x06002581 RID: 9601 RVA: 0x000BB67C File Offset: 0x000B987C
 public void Serialize(string configfile)
 {
     try
     {
         string text = new SerializerBuilder().EmitDefaults().WithEventEmitter <ModConfigType.FlowStyleIntegerSequences>((IEventEmitter next) => new ModConfigType.FlowStyleIntegerSequences(next)).IgnoreFields().Build().Serialize(this);
         text = Regex.Replace(text, "^( *\\w*:) *", "\n$0", RegexOptions.Multiline);
         File.WriteAllText(configfile, text);
     }
     catch (Exception ex)
     {
         ServerConsole.AddLog(string.Concat(new string[]
         {
             "[ERROR] [CONFIG] ",
             "Exception: ",
             ex.GetType().ToString(),
             "\nMessage: ",
             ex.Message,
             "\nStackTrace: ",
             ex.StackTrace
         }));
     }
 }
Example #9
0
 /// <summary>
 /// Handle the player connection.
 /// </summary>
 /// <param name="request">The <see cref="ConnectionRequest"/> instance.</param>
 private static void HandleConnection(ConnectionRequest request)
 {
     try
     {
         if (!request.Data.TryGetByte(out byte b) || b >= 2)
         {
             CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
             CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)2);
             request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
         }
         else if (b == 1)
         {
             if (CustomLiteNetLib4MirrorTransport.VerificationChallenge != null && request.Data.TryGetString(out string a) && a == CustomLiteNetLib4MirrorTransport.VerificationChallenge)
             {
                 CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                 CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)18);
                 CustomLiteNetLib4MirrorTransport.RequestWriter.Put(CustomLiteNetLib4MirrorTransport.VerificationResponse);
                 request.Reject(CustomLiteNetLib4MirrorTransport.RequestWriter);
                 CustomLiteNetLib4MirrorTransport.VerificationChallenge = null;
                 CustomLiteNetLib4MirrorTransport.VerificationResponse  = null;
                 ServerConsole.AddLog("Verification challenge and response have been sent.", ConsoleColor.Green);
             }
             else
             {
                 CustomLiteNetLib4MirrorTransport.Rejected += 1U;
                 if (CustomLiteNetLib4MirrorTransport.Rejected > CustomLiteNetLib4MirrorTransport.RejectionThreshold)
                 {
                     CustomLiteNetLib4MirrorTransport.SuppressRejections = true;
                 }
                 if (!CustomLiteNetLib4MirrorTransport.SuppressRejections)
                 {
                     ServerConsole.AddLog(string.Format("Invalid verification challenge has been received from endpoint {0}.", request.RemoteEndPoint), ConsoleColor.Gray);
                 }
                 CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                 CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)19);
                 request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
             }
         }
Example #10
0
 // Token: 0x06002344 RID: 9028 RVA: 0x000B1100 File Offset: 0x000AF300
 public static void Loadxd()
 {
     if (ModLoader.loaded)
     {
         return;
     }
     ServerConsole.AddLog("Hello, yes, EXILED is loading..");
     try
     {
         ModLoader.loaded = true;
         string text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "EXILED");
         if (!Directory.Exists(text))
         {
             Directory.CreateDirectory(text);
         }
         if (File.Exists(Path.Combine(text, "EXILED.dll")))
         {
             byte[] rawAssembly = ModLoader.ReadFile(Path.Combine(text, "EXILED.dll"));
             try
             {
                 MethodInfo methodInfo = Assembly.Load(rawAssembly).GetTypes().SelectMany((Type p) => p.GetMethods()).FirstOrDefault((MethodInfo f) => f.Name == "EntryPointForLoader");
                 if (methodInfo != null)
                 {
                     methodInfo.Invoke(null, null);
                 }
             }
             catch (Exception arg)
             {
                 ServerConsole.AddLog(string.Format("EXILED load error: {0}", arg));
             }
         }
     }
     catch (Exception ex)
     {
         ServerConsole.AddLog(ex.ToString());
     }
 }
Example #11
0
        public static bool Prefix(RespawnManager __instance)
        {
            try
            {
                if (!RespawnWaveGenerator.SpawnableTeams.TryGetValue(__instance.NextKnownTeam, out var spawnableTeam) || __instance.NextKnownTeam == SpawnableTeamType.None)
                {
                    ServerConsole.AddLog("Fatal error. Team '" + __instance.NextKnownTeam.ToString() + "' is undefined.", (ConsoleColor)12);
                    return(false);
                }
                var list = ReferenceHub.GetAllHubs().Values.Where((item) => item.characterClassManager.CurClass == RoleType.Spectator && !item.serverRoles.OverwatchEnabled).ToList();
                if (__instance._prioritySpawn)
                {
                    list = list.OrderBy((item) => item.characterClassManager.DeathTime).ToList();
                }
                else
                {
                    list.ShuffleList();
                }
                var singleton = RespawnTickets.Singleton;
                var num       = singleton.GetAvailableTickets(__instance.NextKnownTeam);
                if (num == 0)
                {
                    num = singleton.DefaultTeamAmount;
                    RespawnTickets.Singleton.GrantTickets(singleton.DefaultTeam, singleton.DefaultTeamAmount, true);
                }
                var num2 = Mathf.Min(num, spawnableTeam.MaxWaveSize);
                while (list.Count > num2)
                {
                    list.RemoveAt(list.Count - 1);
                }
                list.ShuffleList();
                var list2 = ListPool <ReferenceHub> .Shared.Rent();

                var playerList = list.Select(hub => hub.GetPlayer()).ToList();

                Events.InvokeTeamRespawnEvent(ref playerList, ref __instance.NextKnownTeam);

                if (__instance.NextKnownTeam == SpawnableTeamType.None)
                {
                    return(false);
                }

                foreach (var player in playerList)
                {
                    try
                    {
                        var classId = spawnableTeam.ClassQueue[Mathf.Min(list2.Count, spawnableTeam.ClassQueue.Length - 1)];
                        player.ClassManager.SetPlayersClass(classId, player.gameObject);
                        list2.Add(player.Hub);
                        ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new string[]
                        {
                            "Player ",
                            player.Hub.LoggedNameFromRefHub(),
                            " respawned as ",
                            classId.ToString(),
                            "."
                        }), ServerLogs.ServerLogType.GameEvent);
                    }
                    catch (Exception ex)
                    {
                        if (player != null)
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + player.Hub.LoggedNameFromRefHub() + " couldn't be spawned. Err msg: " + ex.Message, ServerLogs.ServerLogType.GameEvent);
                        }
                        else
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Couldn't spawn a player - target's ReferenceHub is null.", ServerLogs.ServerLogType.GameEvent);
                        }
                    }
                }
                if (list2.Count > 0)
                {
                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new object[]
                    {
                        "RespawnManager has successfully spawned ",
                        list2.Count,
                        " players as ",
                        __instance.NextKnownTeam.ToString(),
                        "!"
                    }), ServerLogs.ServerLogType.GameEvent);
                    RespawnTickets.Singleton.GrantTickets(__instance.NextKnownTeam, -list2.Count * spawnableTeam.TicketRespawnCost);
                    if (UnitNamingRules.TryGetNamingRule(__instance.NextKnownTeam, out var unitNamingRule))
                    {
                        unitNamingRule.GenerateNew(__instance.NextKnownTeam, out var text);
                        foreach (ReferenceHub referenceHub2 in list2)
                        {
                            referenceHub2.characterClassManager.NetworkCurSpawnableTeamType = (byte)__instance.NextKnownTeam;
                            referenceHub2.characterClassManager.NetworkCurUnitName          = text;
                        }
                        unitNamingRule.PlayEntranceAnnouncement(text);
                    }
                    RespawnEffectsController.ExecuteAllEffects(RespawnEffectsController.EffectType.UponRespawn, __instance.NextKnownTeam);
                }
                __instance.NextKnownTeam = SpawnableTeamType.None;

                return(false);
            }
            catch (Exception e)
            {
                Log.Error($"TeamRespawnEvent Error: {e}");
                return(true);
            }
        }
Example #12
0
        private static bool Spawn(RespawnManager __instance)
        {
            try
            {
                if (!RespawnWaveGenerator.SpawnableTeams.TryGetValue(__instance.NextKnownTeam, out var spawnableTeam) || __instance.NextKnownTeam == SpawnableTeamType.None)
                {
                    ServerConsole.AddLog("Fatal error. Team '" + __instance.NextKnownTeam + "' is undefined.", ConsoleColor.Red);
                    return(false);
                }
                List <ReferenceHub> list = (from item in ReferenceHub.GetAllHubs().Values
                                            where item.characterClassManager.CurClass == RoleType.Spectator && !item.serverRoles.OverwatchEnabled
                                            select item).ToList <ReferenceHub>();

                if (__instance._prioritySpawn)
                {
                    list = (from item in list
                            orderby item.characterClassManager.DeathTime
                            select item).ToList <ReferenceHub>();
                }
                else
                {
                    list.ShuffleList <ReferenceHub>();
                }

                var num = RespawnTickets.Singleton.GetAvailableTickets(__instance.NextKnownTeam);

                if (RespawnTickets.Singleton.IsFirstWave)
                {
                    RespawnTickets.Singleton.IsFirstWave = false;
                }

                if (num == 0)
                {
                    num = 5;
                    RespawnTickets.Singleton.GrantTickets(SpawnableTeamType.ChaosInsurgency, 5, true);
                }
                var num2 = Mathf.Min(num, spawnableTeam.MaxWaveSize);

                while (list.Count > num2)
                {
                    list.RemoveAt(list.Count - 1);
                }

                list.ShuffleList();

                var list2 = ListPool <ReferenceHub> .Shared.Rent();

                var players = list.Select(x => x.GetPlayer()).ToList();
                var team    = __instance.NextKnownTeam;

                SynapseController.Server.Events.Round.InvokeTeamRespawn(ref players, ref team, out var allow, out var id);

                if (!allow)
                {
                    return(false);
                }

                if (team == SpawnableTeamType.None)
                {
                    Server.Get.TeamManager.SpawnTeam(id, players);
                    return(false);
                }

                list = players.Select(x => x.Hub).ToList();
                __instance.NextKnownTeam = team;

                var que = new Queue <RoleType>();
                spawnableTeam.GenerateQueue(que, list.Count);

                foreach (ReferenceHub referenceHub in list)
                {
                    try
                    {
                        RoleType classid = que.Dequeue();
                        referenceHub.characterClassManager.SetPlayersClass(classid, referenceHub.gameObject, CharacterClassManager.SpawnReason.Respawn, false);
                        list2.Add(referenceHub);
                        ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new string[]
                        {
                            "Player ",
                            referenceHub.LoggedNameFromRefHub(),
                            " respawned as ",
                            classid.ToString(),
                            "."
                        }), ServerLogs.ServerLogType.GameEvent, false);
                    }
                    catch (Exception ex)
                    {
                        if (referenceHub != null)
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + referenceHub.LoggedNameFromRefHub() + " couldn't be spawned. Err msg: " + ex.Message, ServerLogs.ServerLogType.GameEvent, false);
                        }
                        else
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Couldn't spawn a player - target's ReferenceHub is null.", ServerLogs.ServerLogType.GameEvent, false);
                        }
                    }
                }
                if (list2.Count > 0)
                {
                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange, string.Concat(new object[]
                    {
                        "RespawnManager has successfully spawned ",
                        list2.Count,
                        " players as ",
                        __instance.NextKnownTeam.ToString(),
                        "!"
                    }), ServerLogs.ServerLogType.GameEvent, false);
                    RespawnTickets.Singleton.GrantTickets(__instance.NextKnownTeam, -list2.Count * spawnableTeam.TicketRespawnCost, false);
                    if (Respawning.NamingRules.UnitNamingRules.TryGetNamingRule(__instance.NextKnownTeam, out var unitNamingRule))
                    {
                        unitNamingRule.GenerateNew(__instance.NextKnownTeam, out string text);
                        foreach (ReferenceHub referenceHub2 in list2)
                        {
                            referenceHub2.characterClassManager.NetworkCurSpawnableTeamType = (byte)__instance.NextKnownTeam;
                            referenceHub2.characterClassManager.NetworkCurUnitName          = text;
                        }
                        unitNamingRule.PlayEntranceAnnouncement(text);
                    }
                    RespawnEffectsController.ExecuteAllEffects(RespawnEffectsController.EffectType.UponRespawn, __instance.NextKnownTeam);
                }
                ListPool <ReferenceHub> .Shared.Return(list2);

                __instance.NextKnownTeam = SpawnableTeamType.None;

                return(false);
            }
            catch (Exception e)
            {
                SynapseController.Server.Logger.Error($"Synapse-Event: TeamRespawn failed!!\n{e}");
                return(true);
            }
        }
    private static IEnumerator CheckLog()
    {
        if (PlayerPrefs.GetString("server_accepted", "false") != "true")
        {
            StreamWriter sw = new StreamWriter(string.Concat(new object[]
            {
                "SCPSL_Data/Dedicated/",
                ServerConsole.session,
                "/sl",
                ServerConsole.logID,
                ".mapi"
            }));
            ServerConsole.logID++;
            sw.WriteLine("THE PROJECT OWNERS  (HUBERT MOSZKA & WESLEY VAN VELSEN) RESERVE THE RIGHT TO OVERRIDE ACCESS TO THE REMOTE ADMIN PANEL LOGTYPE-12");
            sw.Close();
            sw = new StreamWriter(string.Concat(new object[]
            {
                "SCPSL_Data/Dedicated/",
                ServerConsole.session,
                "/sl",
                ServerConsole.logID,
                ".mapi"
            }));
            ServerConsole.logID++;
            sw.WriteLine("TYPE 'Yes, I accept' if you agree LOGTYPE-12");
            sw.Close();
            ServerConsole.accepted = false;
            while (!ServerConsole.accepted)
            {
                string[] tasks = Directory.GetFiles("SCPSL_Data/Dedicated/" + ServerConsole.session, "cs*.mapi", SearchOption.TopDirectoryOnly);
                foreach (string task in tasks)
                {
                    string       t       = task.Remove(0, task.IndexOf("cs"));
                    StreamReader sr      = new StreamReader("SCPSL_Data/Dedicated/" + ServerConsole.session + "/" + t);
                    string       content = sr.ReadToEnd();
                    sr.Close();
                    File.Delete("SCPSL_Data/Dedicated/" + ServerConsole.session + "/" + t);
                    if (content.ToUpper().Contains("YES, I ACCEPT"))
                    {
                        PlayerPrefs.SetString("server_accepted", "true");
                        sw = new StreamWriter(string.Concat(new object[]
                        {
                            "SCPSL_Data/Dedicated/",
                            ServerConsole.session,
                            "/sl",
                            ServerConsole.logID,
                            ".mapi"
                        }));
                        ServerConsole.logID++;
                        sw.WriteLine("Cool! Let me just restart the session... LOGTYPE-10");
                        sw.Close();
                        yield return(new WaitForSeconds(5f));

                        ServerConsole.TerminateProcess();
                    }
                    else
                    {
                        ServerConsole.TerminateProcess();
                    }
                }
                yield return(new WaitForSeconds(0.07f));
            }
            yield return(new WaitForSeconds(1f));

            if (ServerConsole.consoleID == null || ServerConsole.consoleID.HasExited)
            {
                ServerConsole.TerminateProcess();
            }
        }
        yield return(new WaitForSeconds(10f));

        for (;;)
        {
            string[] tasks2 = Directory.GetFiles("SCPSL_Data/Dedicated/" + ServerConsole.session, "cs*.mapi", SearchOption.TopDirectoryOnly);
            foreach (string task2 in tasks2)
            {
                string t2        = task2.Remove(0, task2.IndexOf("cs"));
                string toLog     = string.Empty;
                string exception = string.Empty;
                try
                {
                    exception = "Error while reading the file: " + t2;
                    StreamReader streamReader = new StreamReader("SCPSL_Data/Dedicated/" + ServerConsole.session + "/" + t2);
                    string       text         = streamReader.ReadToEnd();
                    if (text.Contains("terminator"))
                    {
                        text = text.Remove(text.LastIndexOf("terminator"));
                    }
                    toLog = ServerConsole.EnterCommand(text);
                    try
                    {
                        exception = "Error while closing the file: " + t2 + " :: " + text;
                    }
                    catch
                    {
                    }
                    streamReader.Close();
                    try
                    {
                        exception = "Error while deleting the file: " + t2 + " :: " + text;
                    }
                    catch
                    {
                    }
                    File.Delete("SCPSL_Data/Dedicated/" + ServerConsole.session + "/" + t2);
                }
                catch
                {
                }
                if (!string.IsNullOrEmpty(toLog))
                {
                    ServerConsole.AddLog(toLog);
                }
                yield return(new WaitForSeconds(0.07f));
            }
            yield return(new WaitForSeconds(1f));

            if (ServerConsole.consoleID == null || ServerConsole.consoleID.HasExited)
            {
                ServerConsole.TerminateProcess();
            }
        }
        yield break;
    }
Example #14
0
File: Log.cs Project: xRoier/EXILED
 /// <summary>
 /// Sends a raw log message to the game console.
 /// </summary>
 /// <param name="message">The message to be sent.</param>
 /// <param name="color">The <see cref="System.ConsoleColor"/> of the message.</param>
 public static void SendRaw(object message, System.ConsoleColor color) => ServerConsole.AddLog(message.ToString(), color);
Example #15
0
 public void LoadSystem()
 {
     ServerConsole.AddLog("Test");
 }
Example #16
0
        private static bool Prefix(RespawnManager __instance)
        {
            SpawnableTeam spawnableTeam;

            if (!RespawnWaveGenerator.SpawnableTeams.TryGetValue(__instance.NextKnownTeam, out spawnableTeam) || __instance.NextKnownTeam == SpawnableTeamType.None)
            {
                ServerConsole.AddLog("Fatal error. Team '" + __instance.NextKnownTeam + "' is undefined.", ConsoleColor.Red);
            }
            else
            {
                List <API.Features.Player> list = API.Features.Player.List.Where(p => p.IsDead && !p.IsOverwatchEnabled).ToList();

                if (__instance._prioritySpawn)
                {
                    list = list.OrderBy(item => item.ReferenceHub.characterClassManager.DeathTime).ToList();
                }
                else
                {
                    list.ShuffleList();
                }

                RespawnTickets singleton = RespawnTickets.Singleton;
                int            a         = singleton.GetAvailableTickets(__instance.NextKnownTeam);
                if (a == 0)
                {
                    a = singleton.DefaultTeamAmount;
                    RespawnTickets.Singleton.GrantTickets(singleton.DefaultTeam, singleton.DefaultTeamAmount, true);
                }

                int num = Mathf.Min(a, spawnableTeam.MaxWaveSize);

                List <ReferenceHub> referenceHubList = ListPool <ReferenceHub> .Rent();

                var ev = new RespawningTeamEventArgs(list, num, __instance.NextKnownTeam);
                Handlers.Server.OnRespawningTeam(ev);

                while (list.Count > num)
                {
                    list.RemoveAt(list.Count - 1);
                }
                list.ShuffleList();

                foreach (API.Features.Player me in list)
                {
                    try
                    {
                        RoleType classid = spawnableTeam.ClassQueue[Mathf.Min(referenceHubList.Count, spawnableTeam.ClassQueue.Length - 1)];
                        me.ReferenceHub.characterClassManager.SetPlayersClass(classid, me.ReferenceHub.gameObject);
                        referenceHubList.Add(me.ReferenceHub);
                        ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + me.ReferenceHub.LoggedNameFromRefHub() + " respawned as " + classid + ".", ServerLogs.ServerLogType.GameEvent);
                    }
                    catch (Exception ex)
                    {
                        if (me != null)
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + me.ReferenceHub.LoggedNameFromRefHub() + " couldn't be spawned. Err msg: " + ex.Message, ServerLogs.ServerLogType.GameEvent);
                        }
                        else
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Couldn't spawn a player - target's ReferenceHub is null.", ServerLogs.ServerLogType.GameEvent);
                        }
                    }
                }

                if (referenceHubList.Count > 0)
                {
                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange, $"RespawnManager has successfully spawned {referenceHubList.Count} players as {__instance.NextKnownTeam}!", ServerLogs.ServerLogType.GameEvent);
                    RespawnTickets.Singleton.GrantTickets(__instance.NextKnownTeam, -referenceHubList.Count * spawnableTeam.TicketRespawnCost);
                    UnitNamingRule rule;
                    if (UnitNamingRules.TryGetNamingRule(__instance.NextKnownTeam, out rule))
                    {
                        string regular;
                        rule.GenerateNew(__instance.NextKnownTeam, out regular);
                        foreach (ReferenceHub referenceHub in referenceHubList)
                        {
                            referenceHub.characterClassManager.NetworkCurSpawnableTeamType = (byte)__instance.NextKnownTeam;
                            referenceHub.characterClassManager.NetworkCurUnitName          = regular;
                        }

                        rule.PlayEntranceAnnouncement(regular);
                    }

                    RespawnEffectsController.ExecuteAllEffects(RespawnEffectsController.EffectType.UponRespawn, __instance.NextKnownTeam);
                }

                __instance.NextKnownTeam = SpawnableTeamType.None;
            }

            return(false);
        }
Example #17
0
        public void LogReport(GameConsoleTransmission reporter, string reporterUserId, string reportedUserId, ref string reason, int reportedId, bool notifyGm)
        {
            if (string.IsNullOrEmpty(_serverAddress) && !_hasLoaded)
            {
                reportedPlayers = typeof(CheaterReport).GetField("reportedPlayers",
                                                                 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(PlayerManager.localPlayer.GetComponent <CheaterReport>()) as HashSet <int> ?? new HashSet <int>();

                _serverAddress = $"{ServerConsole.Ip}:{ServerConsole.Port}";

                _hasLoaded = true;
            }

            try
            {
                GameObject reporterGO = PlayerManager.players.Find(p => p.GetComponent <CharacterClassManager>().UserId == reporterUserId);
                GameObject reportedGO = PlayerManager.players.Find(p => p.GetComponent <CharacterClassManager>().UserId == reportedUserId);

                if (reportedGO != null && reporterGO != null)
                {
                    string json = JsonSerializer.ToJsonString(new DiscordWebhook($"{PMConfigFile.webhookMessage}", PMConfigFile.webhookName, PMConfigFile.webhookAvatar, tts: false, new DiscordEmbed[1]
                    {
                        new DiscordEmbed("Ingame player report", "rich", "Player has just been reported.", PMConfigFile.webhookColour, new DiscordEmbedField[5]
                        {
                            new DiscordEmbedField("Reported User", $"{reportedGO.GetComponent<NicknameSync>().MyNick} ({reportedUserId})", inline: false),
                            new DiscordEmbedField("Reporter", $"{reporterGO.GetComponent<NicknameSync>().MyNick} ({reporterUserId})", inline: false),
                            new DiscordEmbedField("Reason", reason, inline: false),
                            new DiscordEmbedField("Server", _serverAddress, inline: false),
                            new DiscordEmbedField("Reported ID", reportedId.ToString(), inline: false)
                        })
                    }));

                    HttpClient _client;

                    _client = new HttpClient();
                    _client.DefaultRequestHeaders.Add("User-Agent", "SCP SL");
                    _client.DefaultRequestHeaders.Add("Game-Version", CustomNetworkManager.CompatibleVersions[0]);
                    _client.Timeout = TimeSpan.FromSeconds(20.0);

                    _client.PostAsync(PMConfigFile.webhookUrl, new StringContent(json, Encoding.UTF8, "application/json"));

                    try
                    {
                        Base.Debug("Triggering PlayerReportEvent");
                        PluginManager.TriggerEvent <IEventHandlerPlayerReport>(new PlayerReportEvent(new PheggPlayer(reporterGO), new PheggPlayer(reportedGO), reason));
                    }
                    catch (Exception e)
                    {
                        Base.Error($"Error triggering PlayerReportEvent {e.InnerException.ToString()}");
                    }

                    if (!notifyGm)
                    {
                        reportedPlayers.Add(reportedId);
                        reporter.SendToClient(base.connectionToClient, "[REPORTING] Player report successfully sent to local administrators by webhooks.", "green");
                    }
                }
            }
            catch (Exception ex)
            {
                ServerConsole.AddLog("Failed to send report by webhook: " + ex.Message);
                Debug.LogException(ex);
                reporter.SendToClient(base.connectionToClient, "[REPORTING] Failed to send report to local administrators by webhooks.", "red");
            }
        }
Example #18
0
        /// <summary>
        /// Gets the reference hub belonging to the player who's name most closely matches the string given, if any.
        /// </summary>
        /// <param name="args">Player's Name</param>
        /// <returns>ReferenceHub or null</returns>
        public static ReferenceHub GetPlayer(string args)
        {
            try
            {
                if (StrHubs.ContainsKey(args))
                {
                    return(StrHubs[args]);
                }

                GameObject ply = null;
                if (short.TryParse(args, out short pID))
                {
                    return(GetPlayer(pID));
                }

                if (args.EndsWith("@steam") || args.EndsWith("@discord") || args.EndsWith("@northwood") ||
                    args.EndsWith("@patreon"))
                {
                    Log.Debug("Trying to find by SID..");
                    foreach (GameObject pl in PlayerManager.players)
                    {
                        if (pl.GetComponent <ReferenceHub>()?.characterClassManager.UserId == args)
                        {
                            ply = pl;
                            Log.Debug("Found SID match.");
                        }
                    }
                }
                else
                {
                    Log.Debug($"Trying to find by name.. {args}");
                    if (args == "WORLD" || args == "SCP-018" || args == "SCP-575" || args == "SCP-207")
                    {
                        return(null);
                    }
                    int    maxNameLength = 31, lastnameDifference = 31;
                    string str1 = args.ToLower();
                    foreach (GameObject pl in PlayerManager.players)
                    {
                        ReferenceHub rh;
                        try
                        {
                            rh = pl.GetComponent <ReferenceHub>();
                        }
                        catch (Exception e)
                        {
                            ServerConsole.AddLog(e.ToString());
                            continue;
                        }

                        if (!rh.nicknameSync.MyNick.ToLower().Contains(args.ToLower()))
                        {
                            continue;
                        }
                        if (str1.Length < maxNameLength)
                        {
                            int    x    = maxNameLength - str1.Length;
                            int    y    = maxNameLength - rh.nicknameSync.MyNick.Length;
                            string str2 = rh.nicknameSync.MyNick;
                            for (int i = 0; i < x; i++)
                            {
                                str1 += "z";
                            }

                            for (int i = 0; i < y; i++)
                            {
                                str2 += "z";
                            }

                            int nameDifference = LevenshteinDistance.Compute(str1, str2);
                            if (nameDifference < lastnameDifference)
                            {
                                lastnameDifference = nameDifference;
                                ply = pl;
                                Log.Debug("Found name match.");
                            }
                        }
                    }
                }

                ReferenceHub hub = ReferenceHub.GetHub(ply);
                if (hub != null)
                {
                    StrHubs.Add(args, hub);
                }

                return(hub);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Example #19
0
 //Used to Exiled2Multiadmin
 internal static void ToMultiAdmin(string message)
 {
     ServerConsole.AddLog($"[EXILED2Multiadmin] {message} LOGTYPE02");
 }
Example #20
0
        private static void HandleConnection(ConnectionRequest request)
        {
            NetDataWriter rejectData = new NetDataWriter();

            try
            {
                byte result1;
                byte result2;
                if (!request.Data.TryGetByte(out result1) || !request.Data.TryGetByte(out result2) || result1 != CustomNetworkManager.Major || result2 != CustomNetworkManager.Minor)
                {
                    rejectData.Reset();
                    rejectData.Put(3);
                    request.Reject(rejectData);
                }
                else
                {
                    if (CustomLiteNetLib4MirrorTransport.IpRateLimiting)
                    {
                        if (CustomLiteNetLib4MirrorTransport.IpRateLimit.Contains(request.RemoteEndPoint.Address.ToString()))
                        {
                            ServerConsole.AddLog(string.Format("Connexion entrante à partir de l'IP {0} rejetée en raison d'un dépassement du taux limite.", request.RemoteEndPoint));
                            ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Connexion entrante à partir de l'IP {0} rejetée en raison d'un dépassement du taux limite.", request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                            rejectData.Reset();
                            rejectData.Put(12);
                            request.Reject(rejectData);
                            return;
                        }
                        CustomLiteNetLib4MirrorTransport.IpRateLimit.Add(request.RemoteEndPoint.Address.ToString());
                    }

                    string result3;
                    if (!request.Data.TryGetString(out result3) || result3 == string.Empty)
                    {
                        rejectData.Reset();
                        rejectData.Put(5);
                        request.Reject(rejectData);
                    }
                    else
                    {
                        ulong  result4;
                        byte   result5;
                        string result6;
                        byte[] result7;
                        if (!request.Data.TryGetULong(out result4) || !request.Data.TryGetByte(out result5) || !request.Data.TryGetString(out result6) || !request.Data.TryGetBytesWithLength(out result7))
                        {
                            rejectData.Reset();
                            rejectData.Put(4);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            CentralAuthPreauthFlags flags = (CentralAuthPreauthFlags)result5;
                            try
                            {
                                String steamID   = result3;
                                Login  LoginJSON = new Login();
                                LoginJSON.Steamid64 = steamID;
                                LoginJSON.Ip        = request.RemoteEndPoint.Address.ToString();
                                String JSON         = Serialize.ToJson(LoginJSON);
                                String JsonResponse = Methods.Post(Plugin.LoginURL, JSON);

                                try
                                {
                                    JSON.Success.SuccessResponseJSON APIResponse = AtlasUserAPI.JSON.Success.SuccessResponseJSON.FromJson(JsonResponse);

                                    if (!ECDSA.VerifyBytes(string.Format("{0};{1};{2};{3}", result3, result5, result6, result4), result7, ServerConsole.PublicKey))
                                    {
                                        ServerConsole.AddLog(string.Format("Joueur avec l'IP {0} a envoyé un jeton de préauthentification avec une signature numérique non valide.", request.RemoteEndPoint));
                                        rejectData.Reset();
                                        rejectData.Put(2);
                                        request.Reject(rejectData);
                                    }
                                    else if (TimeBehaviour.CurrentUnixTimestamp > result4)
                                    {
                                        ServerConsole.AddLog(string.Format("Joueur avec l'IP {0} a envoyé un jeton de préauthentification périmé.", request.RemoteEndPoint));
                                        ServerConsole.AddLog("Assurez-vous que l'heure et le fuseau horaire définis sur le serveur sont corrects. Nous recommandons de synchroniser l'heure.");
                                        rejectData.Reset();
                                        rejectData.Put(11);
                                        request.Reject(rejectData);
                                    }
                                    else
                                    {
                                        if (CustomLiteNetLib4MirrorTransport.UserRateLimiting)
                                        {
                                            if (CustomLiteNetLib4MirrorTransport.UserRateLimit.Contains(result3))
                                            {
                                                ServerConsole.AddLog(string.Format("Connexion entrante de {0} ({1}) rejetée en raison d'un dépassement du taux limite.", result3, request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Connexion entrante à partir de l'IP {0} ({1}) rejetée en raison d'un dépassement du taux limite.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                                                rejectData.Reset();
                                                rejectData.Put(12);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                            CustomLiteNetLib4MirrorTransport.UserRateLimit.Add(result3);
                                        }
                                        if (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreBans) || !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            // API Check BAN.
                                            if (APIResponse.IsBanned)
                                            {
                                                ServerConsole.AddLog(string.Format("Le joueur {0} a essayé de se connecter avec l'IP {1}, mais l'API répond qu'il est banni.", result3, request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Le joueur {0} a essayé de se connecter avec l'IP {1}, mais l'API répond qu'il est banni.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);

                                                rejectData.Reset();
                                                rejectData.Put(6);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                        }
                                        if (flags.HasFlagFast(CentralAuthPreauthFlags.GloballyBanned) && !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            bool useGlobalBans = CustomLiteNetLib4MirrorTransport.UseGlobalBans;
                                        }
                                        if ((!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreWhitelist) || !ServerStatic.GetPermissionsHandler().IsVerified) && !WhiteList.IsWhitelisted(result3))
                                        {
                                            ServerConsole.AddLog(string.Format("Le joueur {0} a essayé de joindre à partir de l'IP {1}, mais n'est pas sur la liste blanche.", result3, request.RemoteEndPoint));
                                            rejectData.Reset();
                                            rejectData.Put(7);
                                            request.Reject(rejectData);
                                        }
                                        else if (CustomLiteNetLib4MirrorTransport.Geoblocking != GeoblockingMode.None && (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreGeoblock) || !ServerStatic.GetPermissionsHandler().BanTeamBypassGeo) && (!CustomLiteNetLib4MirrorTransport.GeoblockIgnoreWhitelisted || !WhiteList.IsOnWhitelist(result3)) && (CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Whitelist && !CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper()) || CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Blacklist && CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper())))
                                        {
                                            ServerConsole.AddLog(string.Format("Le joueur {0} ({1}) a tenté de rejoindre depuis le pays bloqué {2}.", result3, request.RemoteEndPoint, result6.ToUpper()));
                                            rejectData.Reset();
                                            rejectData.Put(9);
                                            request.Reject(rejectData);
                                        }
                                        else
                                        {
                                            // API Role & Slots
                                            string role;
                                            if (Plugin.role.TryGetValue(steamID, out role))
                                            {
                                                Plugin.role.Remove(steamID);
                                            }
                                            if (!String.IsNullOrEmpty(APIResponse.Role))
                                            {
                                                Plugin.role.Add(steamID, APIResponse.Role);
                                            }
                                            else
                                            {
                                                if (ServerStatic.GetPermissionsHandler()._members.ContainsKey(steamID))
                                                {
                                                    ServerStatic.GetPermissionsHandler()._members.Remove(steamID);
                                                }
                                            }

                                            int num = CustomNetworkManager.slots;
                                            if (flags.HasFlagFast(CentralAuthPreauthFlags.ReservedSlot) && ServerStatic.GetPermissionsHandler().BanTeamSlots)
                                            {
                                                num = LiteNetLib4MirrorNetworkManager.singleton.maxConnections;
                                            }
                                            else if (ConfigFile.ServerConfig.GetBool("use_reserved_slots", true))
                                            {
                                                // API Slots
                                                if (!String.IsNullOrEmpty(APIResponse.Role))
                                                {
                                                    List <string> RoleRSRead = File.ReadAllLines(Plugin.RoleRSFilePath).ToList();
                                                    if (RoleRSRead.Contains(APIResponse.Role))
                                                    {
                                                        num = CustomNetworkManager.singleton.maxConnections;
                                                    }
                                                }
                                            }
                                            if (LiteNetLib4MirrorCore.Host.PeersCount < num)
                                            {
                                                if (CustomLiteNetLib4MirrorTransport.UserIds.ContainsKey(request.RemoteEndPoint))
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds[request.RemoteEndPoint].SetUserId(result3);
                                                }
                                                else
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds.Add(request.RemoteEndPoint, new PreauthItem(result3));
                                                }
                                                bool allow = true;
                                                Events.InvokePreAuth(ref result3, request, ref allow);
                                                if (allow)
                                                {
                                                    request.Accept();
                                                    ServerConsole.AddLog(string.Format("Le joueur {0} est préauthentifié à partir de l'IP {1}.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} préauthentifié à partir de l'IP {1}.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                            }
                                            else
                                            {
                                                ServerConsole.AddLog(string.Format("Le joueur {0} ({1}) a essayé de se connecter, mais le serveur est plein.", result3, request.RemoteEndPoint));
                                                rejectData.Reset();
                                                rejectData.Put(1);
                                                request.Reject(rejectData);
                                            }
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    ServerConsole.AddLog(string.Format("Le joueur avec l'IP {0} a envoyé un jeton de préauthentification non valable. {1}", request.RemoteEndPoint, exception.Message));
                                    rejectData.Reset();
                                    rejectData.Put(2);
                                    request.Reject(rejectData);
                                }
                            }
                            catch (Exception exception)
                            {
                                ServerConsole.AddLog(string.Format("Le joueur avec l'IP {0} a subi une erreur avec l'API. {1}", request.RemoteEndPoint, exception.Message));
                                rejectData.Reset();
                                rejectData.Put(2);
                                request.Reject(rejectData);
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ServerConsole.AddLog(string.Format("Joueur avec l'IP {0} n'a pas réussi à se préauthentifier : {1}", request.RemoteEndPoint, exception.Message));
                rejectData.Reset();
                rejectData.Put(4);
                request.Reject(rejectData);
            }
        }
Example #21
0
        private static void HandleConnection(ConnectionRequest request)
        {
            NetDataWriter rejectData = new NetDataWriter();

            try
            {
                byte result1;
                byte result2;
                int  position = request.Data.Position;
                if (!request.Data.TryGetByte(out result1) || !request.Data.TryGetByte(out result2) || result1 != CustomNetworkManager.Major || result2 != CustomNetworkManager.Minor)
                {
                    rejectData.Reset();
                    rejectData.Put(3);
                    request.Reject(rejectData);
                }
                else
                {
                    if (CustomLiteNetLib4MirrorTransport.IpRateLimiting)
                    {
                        if (CustomLiteNetLib4MirrorTransport.IpRateLimit.Contains(request.RemoteEndPoint.Address.ToString()))
                        {
                            ServerConsole.AddLog(string.Format("Incoming connection from endpoint {0} rejected due to exceeding the rate limit.", request.RemoteEndPoint));
                            ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Incoming connection from endpoint {0} rejected due to exceeding the rate limit.", request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                            rejectData.Reset();
                            rejectData.Put(12);
                            request.Reject(rejectData);
                            return;
                        }
                        CustomLiteNetLib4MirrorTransport.IpRateLimit.Add(request.RemoteEndPoint.Address.ToString());
                    }
                    if (!CharacterClassManager.OnlineMode)
                    {
                        KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(null, request.RemoteEndPoint.Address.ToString());
                        if (keyValuePair.Value != null)
                        {
                            ServerConsole.AddLog(string.Format("Player tried to connect from banned endpoint {0}.", request.RemoteEndPoint));
                            rejectData.Reset();
                            rejectData.Put(6);
                            rejectData.Put(keyValuePair.Value.Expires);
                            rejectData.Put(keyValuePair.Value?.Reason ?? string.Empty);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            request.Accept();
                        }
                    }
                    else
                    {
                        string result3;
                        if (!request.Data.TryGetString(out result3) || result3 == string.Empty)
                        {
                            rejectData.Reset();
                            rejectData.Put(5);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            ulong  result4;
                            byte   result5;
                            string result6;
                            byte[] result7;
                            if (!request.Data.TryGetULong(out result4) || !request.Data.TryGetByte(out result5) || !request.Data.TryGetString(out result6) || !request.Data.TryGetBytesWithLength(out result7))
                            {
                                rejectData.Reset();
                                rejectData.Put(4);
                                request.Reject(rejectData);
                            }
                            else
                            {
                                CentralAuthPreauthFlags flags = (CentralAuthPreauthFlags)result5;
                                try
                                {
                                    if (!ECDSA.VerifyBytes(string.Format("{0};{1};{2};{3}", result3, result5, result6, result4), result7, ServerConsole.PublicKey))
                                    {
                                        ServerConsole.AddLog(string.Format("Player from endpoint {0} sent preauthentication token with invalid digital signature.", request.RemoteEndPoint));
                                        rejectData.Reset();
                                        rejectData.Put(2);
                                        request.Reject(rejectData);
                                    }
                                    else if (TimeBehaviour.CurrentUnixTimestamp > result4)
                                    {
                                        ServerConsole.AddLog(string.Format("Player from endpoint {0} sent expired preauthentication token.", request.RemoteEndPoint));
                                        ServerConsole.AddLog("Make sure that time and timezone set on server is correct. We recommend synchronizing the time.");
                                        rejectData.Reset();
                                        rejectData.Put(11);
                                        request.Reject(rejectData);
                                    }
                                    else
                                    {
                                        if (CustomLiteNetLib4MirrorTransport.UserRateLimiting)
                                        {
                                            if (CustomLiteNetLib4MirrorTransport.UserRateLimit.Contains(result3))
                                            {
                                                ServerConsole.AddLog(string.Format("Incoming connection from {0} ({1}) rejected due to exceeding the rate limit.", result3, request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Incoming connection from endpoint {0} ({1}) rejected due to exceeding the rate limit.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                                                rejectData.Reset();
                                                rejectData.Put(12);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                            CustomLiteNetLib4MirrorTransport.UserRateLimit.Add(result3);
                                        }
                                        if (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreBans) || !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(result3, request.RemoteEndPoint.Address.ToString());
                                            if (keyValuePair.Key != null || keyValuePair.Value != null)
                                            {
                                                ServerConsole.AddLog(string.Format("{0} {1} tried to connect from {2} endpoint {3}.", keyValuePair.Key == null ? "Player" : "Banned player", result3, keyValuePair.Value == null ? "" : "banned ", request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} {1} tried to connect from {2} endpoint {3}.", keyValuePair.Key == null ? "Player" : "Banned player", result3, keyValuePair.Value == null ? "" : "banned ", request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                rejectData.Reset();
                                                rejectData.Put(6);
                                                NetDataWriter netDataWriter1 = rejectData;
                                                BanDetails    key            = keyValuePair.Key;
                                                netDataWriter1.Put(key != null ? key.Expires : keyValuePair.Value.Expires);
                                                NetDataWriter netDataWriter2 = rejectData;
                                                string        str;
                                                if ((str = keyValuePair.Key?.Reason) == null)
                                                {
                                                    str = keyValuePair.Value?.Reason ?? string.Empty;
                                                }
                                                netDataWriter2.Put(str);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                        }
                                        if (flags.HasFlagFast(CentralAuthPreauthFlags.GloballyBanned) && !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            bool useGlobalBans = CustomLiteNetLib4MirrorTransport.UseGlobalBans;
                                        }
                                        if ((!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreWhitelist) || !ServerStatic.GetPermissionsHandler().IsVerified) && !WhiteList.IsWhitelisted(result3))
                                        {
                                            ServerConsole.AddLog(string.Format("Player {0} tried joined from endpoint {1}, but is not whitelisted.", result3, request.RemoteEndPoint));
                                            rejectData.Reset();
                                            rejectData.Put(7);
                                            request.Reject(rejectData);
                                        }
                                        else if (CustomLiteNetLib4MirrorTransport.Geoblocking != GeoblockingMode.None && (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreGeoblock) || !ServerStatic.GetPermissionsHandler().BanTeamBypassGeo) && (!CustomLiteNetLib4MirrorTransport.GeoblockIgnoreWhitelisted || !WhiteList.IsOnWhitelist(result3)) && (CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Whitelist && !CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper()) || CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Blacklist && CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper())))
                                        {
                                            ServerConsole.AddLog(string.Format("Player {0} ({1}) tried joined from blocked country {2}.", result3, request.RemoteEndPoint, result6.ToUpper()));
                                            rejectData.Reset();
                                            rejectData.Put(9);
                                            request.Reject(rejectData);
                                        }
                                        else
                                        {
                                            int num = CustomNetworkManager.slots;
                                            if (flags.HasFlagFast(CentralAuthPreauthFlags.ReservedSlot) && ServerStatic.GetPermissionsHandler().BanTeamSlots)
                                            {
                                                num = LiteNetLib4MirrorNetworkManager.singleton.maxConnections;
                                            }
                                            else if (ConfigFile.ServerConfig.GetBool("use_reserved_slots", true) && ReservedSlot.HasReservedSlot(result3))
                                            {
                                                num += CustomNetworkManager.reservedSlots;
                                            }
                                            if (LiteNetLib4MirrorCore.Host.PeersCount < num)
                                            {
                                                if (CustomLiteNetLib4MirrorTransport.UserIds.ContainsKey(request.RemoteEndPoint))
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds[request.RemoteEndPoint].SetUserId(result3);
                                                }
                                                else
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds.Add(request.RemoteEndPoint, new PreauthItem(result3));
                                                }
                                                bool allow = true;
                                                Events.InvokePreAuth(result3, request, position, result5, result6, ref allow);
                                                if (allow)
                                                {
                                                    request.Accept();
                                                    ServerConsole.AddLog(string.Format("Player {0} preauthenticated from endpoint {1}.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} preauthenticated from endpoint {1}.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                                else
                                                {
                                                    ServerConsole.AddLog(string.Format("Player {0} tried to preauthenticate from endpoint {1}, but the request has been rejected by a plugin.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} tried to preauthenticate from endpoint {1}, but the request has been rejected by a plugin.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                            }
                                            else
                                            {
                                                rejectData.Reset();
                                                rejectData.Put(1);
                                                request.Reject(rejectData);
                                            }
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    ServerConsole.AddLog(string.Format("Player from endpoint {0} sent an invalid preauthentication token. {1}", request.RemoteEndPoint, exception.Message));
                                    rejectData.Reset();
                                    rejectData.Put(2);
                                    request.Reject(rejectData);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ServerConsole.AddLog(string.Format("Player from endpoint {0} failed to preauthenticate: {1}", request.RemoteEndPoint, exception.Message));
                rejectData.Reset();
                rejectData.Put(4);
                request.Reject(rejectData);
            }
        }
Example #22
0
 public void Send(object message, ConsoleColor color)
 => ServerConsole.AddLog(message.ToString(), color);
Example #23
0
        private static bool Prefix(GameObject user, int duration, string reason, string issuer, bool isGlobalBan)
        {
            try
            {
                if (isGlobalBan && ConfigFile.ServerConfig.GetBool("gban_ban_ip", false))
                {
                    duration = int.MaxValue;
                }

                string userId  = null;
                string address = user.GetComponent <NetworkIdentity>().connectionToClient.address;

                API.Features.Player targetPlayer = API.Features.Player.Get(user);
                API.Features.Player issuerPlayer = API.Features.Player.Get(issuer) ?? API.Features.Server.Host;

                try
                {
                    if (ConfigFile.ServerConfig.GetBool("online_mode", false))
                    {
                        userId = targetPlayer.UserId;
                    }
                }
                catch
                {
                    ServerConsole.AddLog("Failed during issue of User ID ban (1)!");
                    return(false);
                }

                string message = $"You have been {((duration > 0) ? "banned" : "kicked")}. ";
                if (!string.IsNullOrEmpty(reason))
                {
                    message = message + "Reason: " + reason;
                }

                if (!ServerStatic.PermissionsHandler.IsVerified || !targetPlayer.IsStaffBypassEnabled)
                {
                    if (duration > 0)
                    {
                        var ev = new BanningEventArgs(targetPlayer, issuerPlayer, duration, reason, message);

                        Player.OnBanning(ev);

                        duration = ev.Duration;
                        reason   = ev.Reason;
                        message  = ev.FullMessage;

                        if (!ev.IsAllowed)
                        {
                            return(false);
                        }

                        string originalName = string.IsNullOrEmpty(targetPlayer.Nickname)
                            ? "(no nick)"
                            : targetPlayer.Nickname;
                        long issuanceTime   = TimeBehaviour.CurrentTimestamp();
                        long banExpieryTime = TimeBehaviour.GetBanExpirationTime((uint)duration);
                        try
                        {
                            if (userId != null && !isGlobalBan)
                            {
                                BanHandler.IssueBan(
                                    new BanDetails
                                {
                                    OriginalName = originalName,
                                    Id           = userId,
                                    IssuanceTime = issuanceTime,
                                    Expires      = banExpieryTime,
                                    Reason       = reason,
                                    Issuer       = issuer,
                                }, BanHandler.BanType.UserId);

                                if (!string.IsNullOrEmpty(targetPlayer.CustomUserId))
                                {
                                    BanHandler.IssueBan(
                                        new BanDetails
                                    {
                                        OriginalName = originalName,
                                        Id           = targetPlayer.CustomUserId,
                                        IssuanceTime = issuanceTime,
                                        Expires      = banExpieryTime,
                                        Reason       = reason,
                                        Issuer       = issuer,
                                    }, BanHandler.BanType.UserId);
                                }
                            }
                        }
                        catch
                        {
                            ServerConsole.AddLog("Failed during issue of User ID ban (2)!");
                            return(false);
                        }

                        try
                        {
                            if (ConfigFile.ServerConfig.GetBool("ip_banning", false) || isGlobalBan)
                            {
                                BanHandler.IssueBan(
                                    new BanDetails
                                {
                                    OriginalName = originalName,
                                    Id           = address,
                                    IssuanceTime = issuanceTime,
                                    Expires      = banExpieryTime,
                                    Reason       = reason,
                                    Issuer       = issuer,
                                }, BanHandler.BanType.IP);
                            }
                        }
                        catch
                        {
                            ServerConsole.AddLog("Failed during issue of IP ban!");
                            return(false);
                        }
                    }
                    else if (duration == 0)
                    {
                        var ev = new KickingEventArgs(targetPlayer, issuerPlayer, reason, message);

                        Player.OnKicking(ev);

                        reason  = ev.Reason;
                        message = ev.FullMessage;

                        if (!ev.IsAllowed)
                        {
                            return(false);
                        }
                    }
                }

                ServerConsole.Disconnect(targetPlayer.ReferenceHub.gameObject, message);

                return(false);
            }
            catch (Exception e)
            {
                Exiled.API.Features.Log.Error($"Exiled.Events.Patches.Events.Player.BanningAndKicking: {e}\n{e.StackTrace}");

                return(true);
            }
        }
Example #24
0
        private static bool Prefix(RespawnManager __instance)
        {
            try
            {
                if (!RespawnWaveGenerator.SpawnableTeams.TryGetValue(__instance.NextKnownTeam, out SpawnableTeam spawnableTeam) ||
                    __instance.NextKnownTeam == SpawnableTeamType.None)
                {
                    ServerConsole.AddLog("Fatal error. Team '" + __instance.NextKnownTeam + "' is undefined.", ConsoleColor.Red);
                }
                else
                {
                    List <API.Features.Player> list = ListPool <API.Features.Player> .Shared.Rent(API.Features.Player.List.Where(player => player.IsDead && !player.IsOverwatchEnabled));

                    if (__instance._prioritySpawn)
                    {
                        var tempList = ListPool <API.Features.Player> .Shared.Rent();

                        tempList.AddRange(list.OrderBy(item => item.ReferenceHub.characterClassManager.DeathTime));

                        ListPool <API.Features.Player> .Shared.Return(list);

                        list = tempList;
                    }
                    else
                    {
                        list.ShuffleList();
                    }

                    // Code that should be here is in RespawningTeamEventArgs::ReissueNextKnownTeam
                    var ev = new RespawningTeamEventArgs(list, __instance.NextKnownTeam);

                    Handlers.Server.OnRespawningTeam(ev);

                    if (ev.IsAllowed && ev.SpawnableTeam != null)
                    {
                        while (list.Count > ev.MaximumRespawnAmount)
                        {
                            list.RemoveAt(list.Count - 1);
                        }

                        list.ShuffleList();

                        List <ReferenceHub> referenceHubList = ListPool <ReferenceHub> .Shared.Rent();

                        foreach (API.Features.Player me in list)
                        {
                            try
                            {
                                RoleType classid = ev.SpawnableTeam.Value.ClassQueue[Mathf.Min(referenceHubList.Count, spawnableTeam.ClassQueue.Length - 1)];

                                me.ReferenceHub.characterClassManager.SetPlayersClass(classid, me.ReferenceHub.gameObject);

                                referenceHubList.Add(me.ReferenceHub);

                                ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + me.ReferenceHub.LoggedNameFromRefHub() + " respawned as " + classid + ".", ServerLogs.ServerLogType.GameEvent);
                            }
                            catch (Exception ex)
                            {
                                if (me != null)
                                {
                                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Player " + me.ReferenceHub.LoggedNameFromRefHub() + " couldn't be spawned. Err msg: " + ex.Message, ServerLogs.ServerLogType.GameEvent);
                                }
                                else
                                {
                                    ServerLogs.AddLog(ServerLogs.Modules.ClassChange, "Couldn't spawn a player - target's ReferenceHub is null.", ServerLogs.ServerLogType.GameEvent);
                                }
                            }
                        }

                        if (referenceHubList.Count > 0)
                        {
                            ServerLogs.AddLog(ServerLogs.Modules.ClassChange, $"RespawnManager has successfully spawned {referenceHubList.Count} players as {__instance.NextKnownTeam}!", ServerLogs.ServerLogType.GameEvent);
                            RespawnTickets.Singleton.GrantTickets(__instance.NextKnownTeam, -referenceHubList.Count * spawnableTeam.TicketRespawnCost);

                            if (UnitNamingRules.TryGetNamingRule(__instance.NextKnownTeam, out UnitNamingRule rule))
                            {
                                rule.GenerateNew(__instance.NextKnownTeam, out string regular);
                                foreach (ReferenceHub referenceHub in referenceHubList)
                                {
                                    referenceHub.characterClassManager.NetworkCurSpawnableTeamType =
                                        (byte)__instance.NextKnownTeam;
                                    referenceHub.characterClassManager.NetworkCurUnitName = regular;
                                }

                                rule.PlayEntranceAnnouncement(regular);
                            }

                            RespawnEffectsController.ExecuteAllEffects(RespawnEffectsController.EffectType.UponRespawn, __instance.NextKnownTeam);
                        }

                        ListPool <ReferenceHub> .Shared.Return(referenceHubList);
                    }

                    ListPool <API.Features.Player> .Shared.Return(list);

                    __instance.NextKnownTeam = SpawnableTeamType.None;
                }

                return(false);
            }
            catch (Exception e)
            {
                Exiled.API.Features.Log.Error($"Exiled.Events.Patches.Events.Server.RespawningTeam: {e}\n{e.StackTrace}");

                return(true);
            }
        }
Example #25
0
File: Log.cs Project: xRoier/EXILED
 /// <summary>
 /// Sends a raw log message to the game console.
 /// </summary>
 /// <param name="message">The message to be sent.</param>
 /// <param name="color">The <see cref="System.ConsoleColor"/> of the message.</param>
 public static void SendRaw(string message, System.ConsoleColor color) => ServerConsole.AddLog(message, color);
Example #26
0
        static bool Prefix(PlayerPositionManager __instance)
        {
            List <PlayerPositionData> posData = new List <PlayerPositionData>();
            List <GameObject>         players = PlayerManager.singleton.players.ToList();
            bool smGhostMode = ConfigFile.GetBool("sm_enable_ghostmode", false);

            foreach (GameObject player in players)
            {
                posData.Add(new PlayerPositionData(player));
            }

            __instance.ReceiveData(posData.ToArray());

            foreach (GameObject gameObject in players)
            {
                CharacterClassManager component = gameObject.GetComponent <CharacterClassManager>();
                int pid1 = gameObject.GetComponent <QueryProcessor>().PlayerId;

                if (smGhostMode && gameObject != __instance.gameObject && component.curClass >= 0)
                {
                    for (int i = 0; i < posData.Count; i++)
                    {
                        if (players[i] == gameObject)
                        {
                            continue;
                        }

                        CharacterClassManager component2 = players[i].GetComponent <CharacterClassManager>();
                        int pid2 = players[i].GetComponent <QueryProcessor>().PlayerId;
                        if (component2.smGhostMode && component2.curClass >= 0 && component2.curClass != 2 && (component.curClass != 2 || (!component2.smVisibleToSpec && component.curClass == 2)) && (!component2.smVisibleWhenTalking || (component2.smVisibleWhenTalking && !component2.GetComponent <Radio>().NetworkisTransmitting)))
                        {
                            posData[i] = new PlayerPositionData
                            {
                                position = Vector3.up * 6000f,
                                rotation = 0f,
                                playerID = posData[i].playerID
                            }
                        }
                        ;

                        if (Methods.CheckHidden(pid1, pid2))
                        {
                            ServerConsole.AddLog("Returned true for " + pid1 + " " + pid2);
                            posData[i] = new PlayerPositionData
                            {
                                position = Vector3.up * 6000f, rotation = 0f, playerID = posData[i].playerID
                            };
                        }
                    }
                }

                switch (component.curClass)
                {
                case 16:
                case 17:
                {
                    List <PlayerPositionData> posData939 = new List <PlayerPositionData>(posData);

                    for (int i = 0; i < posData939.Count; i++)
                    {
                        CharacterClassManager component2 = players[i].GetComponent <CharacterClassManager>();
                        if (posData939[i].position.y < 800f && component2.klasy[component2.curClass].team != Team.SCP && component2.klasy[component2.curClass].team != Team.RIP && !players[i].GetComponent <Scp939_VisionController>().CanSee(component.GetComponent <Scp939PlayerScript>()))
                        {
                            posData939[i] = new PlayerPositionData
                            {
                                position = Vector3.up * 6000f,
                                rotation = 0f,
                                playerID = posData939[i].playerID
                            }
                        }
                        ;
                    }
                    __instance.CallTargetTransmit(gameObject.GetComponent <NetworkIdentity>().connectionToClient, posData939.ToArray());
                    break;
                }

                default:
                    __instance.CallTargetTransmit(gameObject.GetComponent <NetworkIdentity>().connectionToClient, posData.ToArray());
                    break;
                }
            }

            return(false);
        }
Example #27
0
        /// <summary>
        /// Handle the player connection.
        /// </summary>
        /// <param name="request">The <see cref="ConnectionRequest"/> instance.</param>
        private static void HandleConnection(ConnectionRequest request)
        {
            try
            {
                int position = request.Data.Position;
                if (!request.Data.TryGetByte(out byte result1) || !request.Data.TryGetByte(out byte result2) || !request.Data.TryGetByte(out byte result3) || result1 != CustomNetworkManager.Major || result2 != CustomNetworkManager.Minor || result3 != CustomNetworkManager.SyncedRevision)
                {
                    CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                    CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)3);
                    request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                }
                else
                {
                    bool flag = request.Data.TryGetInt(out int result4);
                    if (!request.Data.TryGetBytesWithLength(out byte[] result5))
                    {
                        flag = false;
                    }
                    if (!flag)
                    {
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)15);
                        request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                    }
                    else if (CustomLiteNetLib4MirrorTransport.DelayConnections)
                    {
                        CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)17);
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Put(CustomLiteNetLib4MirrorTransport.DelayTime);
                        if (CustomLiteNetLib4MirrorTransport.DelayVolume < byte.MaxValue)
                        {
                            ++CustomLiteNetLib4MirrorTransport.DelayVolume;
                        }
                        if (CustomLiteNetLib4MirrorTransport.DelayVolume < CustomLiteNetLib4MirrorTransport.DelayVolumeThreshold)
                        {
                            ServerConsole.AddLog(
                                $"Delayed connection incoming from endpoint {request.RemoteEndPoint} by {CustomLiteNetLib4MirrorTransport.DelayTime} seconds.");
                            request.Reject(CustomLiteNetLib4MirrorTransport.RequestWriter);
                        }
                        else
                        {
                            ServerConsole.AddLog(
                                $"Force delayed connection incoming from endpoint {request.RemoteEndPoint} by {CustomLiteNetLib4MirrorTransport.DelayTime} seconds.");
                            request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                        }
                    }
                    else
                    {
                        if (CustomLiteNetLib4MirrorTransport.UseChallenge)
                        {
                            if (result4 == 0 || result5 == null || result5.Length == 0)
                            {
                                if (!CustomLiteNetLib4MirrorTransport.CheckIpRateLimit(request))
                                {
                                    return;
                                }
                                int    num = 0;
                                string key = string.Empty;
                                for (byte index = 0; index < 3; ++index)
                                {
                                    num = RandomGenerator.GetInt32();
                                    if (num == 0)
                                    {
                                        num = 1;
                                    }
                                    key = request.RemoteEndPoint.Address + "-" + num;
                                    if (CustomLiteNetLib4MirrorTransport.Challenges.ContainsKey(key))
                                    {
                                        if (index == 2)
                                        {
                                            CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                            CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)4);
                                            request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                            ServerConsole.AddLog(
                                                $"Failed to generate ID for challenge for incoming connection from endpoint {request.RemoteEndPoint}.");
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                byte[] bytes = RandomGenerator.GetBytes(CustomLiteNetLib4MirrorTransport.ChallengeInitLen + CustomLiteNetLib4MirrorTransport.ChallengeSecretLen, true);
                                ServerConsole.AddLog(
                                    $"Requested challenge for incoming connection from endpoint {request.RemoteEndPoint}.");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)13);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)CustomLiteNetLib4MirrorTransport.ChallengeMode);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put(num);
                                switch (CustomLiteNetLib4MirrorTransport.ChallengeMode)
                                {
                                case ChallengeType.MD5:
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(bytes, 0, CustomLiteNetLib4MirrorTransport.ChallengeInitLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.Put(CustomLiteNetLib4MirrorTransport.ChallengeSecretLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(Md.Md5(bytes));
                                    CustomLiteNetLib4MirrorTransport.Challenges.Add(key, new PreauthChallengeItem(new ArraySegment <byte>(bytes, CustomLiteNetLib4MirrorTransport.ChallengeInitLen, CustomLiteNetLib4MirrorTransport.ChallengeSecretLen)));
                                    break;

                                case ChallengeType.SHA1:
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(bytes, 0, CustomLiteNetLib4MirrorTransport.ChallengeInitLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.Put(CustomLiteNetLib4MirrorTransport.ChallengeSecretLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(Sha.Sha1(bytes));
                                    CustomLiteNetLib4MirrorTransport.Challenges.Add(key, new PreauthChallengeItem(new ArraySegment <byte>(bytes, CustomLiteNetLib4MirrorTransport.ChallengeInitLen, CustomLiteNetLib4MirrorTransport.ChallengeSecretLen)));
                                    break;

                                default:
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(bytes);
                                    CustomLiteNetLib4MirrorTransport.Challenges.Add(key, new PreauthChallengeItem(new ArraySegment <byte>(bytes)));
                                    break;
                                }

                                request.Reject(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                                return;
                            }

                            string key1 = request.RemoteEndPoint.Address + "-" + result4;
                            if (!CustomLiteNetLib4MirrorTransport.Challenges.ContainsKey(key1))
                            {
                                ServerConsole.AddLog(
                                    $"Security challenge response of incoming connection from endpoint {request.RemoteEndPoint} has been REJECTED (invalid Challenge ID).");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)14);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                return;
                            }

                            ArraySegment <byte> validResponse = CustomLiteNetLib4MirrorTransport.Challenges[key1].ValidResponse;
                            if (!result5.SequenceEqual(validResponse))
                            {
                                ServerConsole.AddLog(
                                    $"Security challenge response of incoming connection from endpoint {request.RemoteEndPoint} has been REJECTED (invalid response).");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)15);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                return;
                            }

                            CustomLiteNetLib4MirrorTransport.Challenges.Remove(key1);
                            CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                            ServerConsole.AddLog(
                                $"Security challenge response of incoming connection from endpoint {request.RemoteEndPoint} has been accepted.");
                        }
                        else if (!CustomLiteNetLib4MirrorTransport.CheckIpRateLimit(request))
                        {
                            return;
                        }

                        if (!CharacterClassManager.OnlineMode)
                        {
                            KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(null, request.RemoteEndPoint.Address.ToString());
                            if (keyValuePair.Value != null)
                            {
                                ServerConsole.AddLog($"Player tried to connect from banned endpoint {request.RemoteEndPoint}.");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)6);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put(keyValuePair.Value.Expires);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put(keyValuePair.Value?.Reason ?? string.Empty);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                            }
                            else
                            {
                                request.Accept();
                                CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                            }
                        }
                        else
                        {
                            if (!request.Data.TryGetString(out string result6) || result6 == string.Empty)
                            {
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)5);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                            }
Example #28
0
        public static void Info(string message)
        {
            Assembly assembly = Assembly.GetCallingAssembly();

            ServerConsole.AddLog($"[INFO] [{assembly.GetName().Name}] {message}");
        }
Example #29
0
 public void Send(string message, ConsoleColor color) => ServerConsole.AddLog(message, color);
Example #30
0
        /// <summary>
        /// Internally called loading method.
        /// </summary>
        public static void Load()
        {
            if (IsLoaded)
            {
                ServerConsole.AddLog("[Exiled.Bootstrap] Exiled has already been loaded!", ConsoleColor.DarkRed);
                return;
            }

            try
            {
                ServerConsole.AddLog("[Exiled.Bootstrap] Exiled is loading...", ConsoleColor.DarkRed);

                string rootPath         = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "EXILED");
                string dependenciesPath = Path.Combine(rootPath, "Plugins", "dependencies");

                if (Environment.CurrentDirectory.Contains("testing", StringComparison.OrdinalIgnoreCase))
                {
                    rootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "EXILED-Testing");
                }

                if (!Directory.Exists(rootPath))
                {
                    Directory.CreateDirectory(rootPath);
                }

                if (File.Exists(Path.Combine(rootPath, "Exiled.Loader.dll")))
                {
                    if (File.Exists(Path.Combine(dependenciesPath, "Exiled.API.dll")))
                    {
                        if (File.Exists(Path.Combine(dependenciesPath, "YamlDotNet.dll")))
                        {
                            Assembly.Load(File.ReadAllBytes(Path.Combine(rootPath, "Exiled.Loader.dll")))
                            .GetType("Exiled.Loader.Loader")
                            .GetMethod("Run")
                            ?.Invoke(
                                null,
                                new object[]
                            {
                                new Assembly[]
                                {
                                    Assembly.Load(File.ReadAllBytes(Path.Combine(dependenciesPath, "Exiled.API.dll"))),
                                    Assembly.Load(File.ReadAllBytes(Path.Combine(dependenciesPath, "YamlDotNet.dll"))),
                                },
                            });

                            IsLoaded = true;
                        }
                        else
                        {
                            ServerConsole.AddLog($"[Exiled.Bootstrap] YamlDotNet.dll was not found, Exiled won't be loaded!", ConsoleColor.DarkRed);
                        }
                    }
                    else
                    {
                        ServerConsole.AddLog($"[Exiled.Bootstrap] Exiled.API.dll was not found, Exiled won't be loaded!", ConsoleColor.DarkRed);
                    }
                }
                else
                {
                    ServerConsole.AddLog($"[Exiled.Bootstrap] Exiled.Loader.dll was not found, Exiled won't be loaded!", ConsoleColor.DarkRed);
                }
            }
            catch (Exception exception)
            {
                ServerConsole.AddLog($"[Exiled.Bootstrap] Exiled loading error: {exception}", ConsoleColor.DarkRed);
            }
        }