Example #1
0
 public void Initialize(bool loadSave = true, string saveFile = "", bool allowOutOfDateSaves = false, bool skipInitialSpawn = false)
 {
     this.persistance = new UserPersistance(ConVar.Server.rootFolder);
     this.SpawnMapEntities();
     if (SingletonComponent <SpawnHandler> .Instance)
     {
         using (TimeWarning timeWarning = TimeWarning.New("SpawnHandler.UpdateDistributions", 0.1f))
         {
             SingletonComponent <SpawnHandler> .Instance.UpdateDistributions();
         }
     }
     if (loadSave)
     {
         skipInitialSpawn = SaveRestore.Load(saveFile, allowOutOfDateSaves);
     }
     if (SingletonComponent <SpawnHandler> .Instance)
     {
         if (!skipInitialSpawn)
         {
             using (timeWarning = TimeWarning.New("SpawnHandler.InitialSpawn", (long)200))
             {
                 SingletonComponent <SpawnHandler> .Instance.InitialSpawn();
             }
         }
         using (timeWarning = TimeWarning.New("SpawnHandler.StartSpawnTick", (long)200))
         {
             SingletonComponent <SpawnHandler> .Instance.StartSpawnTick();
         }
     }
     this.CreateImportantEntities();
     this.auth = base.GetComponent <ConnectionAuth>();
 }
Example #2
0
        private object OnUserApprove(Network.Connection connection)
        {
            // Call out and see if we should reject
            object canlogin = Interface.CallHook("CanClientLogin", new object[] { connection });

            if (canlogin != null)
            {
                // If it's a bool and it's true, let them in
                if (canlogin is bool && (bool)canlogin)
                {
                    return(null);
                }

                // If it's a string, reject them with a message
                if (canlogin is string)
                {
                    ConnectionAuth.Reject(connection, (string)canlogin);
                    return(true);
                }

                // We don't know what type it is, reject them with it anyway
                ConnectionAuth.Reject(connection, canlogin.ToString());
                return(true);
            }
            return(null);
        }
Example #3
0
 public void Initialize(
     bool loadSave            = true,
     string saveFile          = "",
     bool allowOutOfDateSaves = false,
     bool skipInitialSpawn    = false)
 {
     if (!ConVar.Server.official)
     {
         ExceptionReporter.set_Disabled(true);
     }
     this.persistance = new UserPersistance(ConVar.Server.rootFolder);
     this.SpawnMapEntities();
     if (Object.op_Implicit((Object)SingletonComponent <SpawnHandler> .Instance))
     {
         using (TimeWarning.New("SpawnHandler.UpdateDistributions", 0.1f))
             ((SpawnHandler)SingletonComponent <SpawnHandler> .Instance).UpdateDistributions();
     }
     if (loadSave)
     {
         skipInitialSpawn = SaveRestore.Load(saveFile, allowOutOfDateSaves);
     }
     if (Object.op_Implicit((Object)SingletonComponent <SpawnHandler> .Instance))
     {
         if (!skipInitialSpawn)
         {
             using (TimeWarning.New("SpawnHandler.InitialSpawn", 200L))
                 ((SpawnHandler)SingletonComponent <SpawnHandler> .Instance).InitialSpawn();
         }
         using (TimeWarning.New("SpawnHandler.StartSpawnTick", 200L))
             ((SpawnHandler)SingletonComponent <SpawnHandler> .Instance).StartSpawnTick();
     }
     this.CreateImportantEntities();
     this.auth = (ConnectionAuth)((Component)this).GetComponent <ConnectionAuth>();
 }
 public void OnNewConnection(Connection connection)
 {
     connection.connected = false;
     if (connection.token == null || (int)connection.token.Length < 32)
     {
         ConnectionAuth.Reject(connection, "Invalid Token");
         return;
     }
     if (connection.userid == 0)
     {
         ConnectionAuth.Reject(connection, "Invalid SteamID");
         return;
     }
     if (connection.protocol != 2177)
     {
         if (!DeveloperList.Contains(connection.userid))
         {
             ConnectionAuth.Reject(connection, "Incompatible Version");
             return;
         }
         DebugEx.Log(string.Concat("Not kicking ", connection.userid, " for incompatible protocol (is a developer)"), StackTraceLogType.None);
     }
     if (ServerUsers.Is(connection.userid, ServerUsers.UserGroup.Banned))
     {
         ConnectionAuth.Reject(connection, "You are banned from this server");
         return;
     }
     if (ServerUsers.Is(connection.userid, ServerUsers.UserGroup.Moderator))
     {
         DebugEx.Log(string.Concat(connection.ToString(), " has auth level 1"), StackTraceLogType.None);
         connection.authLevel = 1;
     }
     if (ServerUsers.Is(connection.userid, ServerUsers.UserGroup.Owner))
     {
         DebugEx.Log(string.Concat(connection.ToString(), " has auth level 2"), StackTraceLogType.None);
         connection.authLevel = 2;
     }
     if (DeveloperList.Contains(connection.userid))
     {
         DebugEx.Log(string.Concat(connection.ToString(), " is a developer"), StackTraceLogType.None);
         connection.authLevel = 3;
     }
     if (this.IsConnected(connection.userid))
     {
         ConnectionAuth.Reject(connection, "You are already connected!");
         return;
     }
     if (Interface.CallHook("IOnUserApprove", connection) != null)
     {
         return;
     }
     ConnectionAuth.m_AuthConnection.Add(connection);
     base.StartCoroutine(this.AuthorisationRoutine(connection));
 }
Example #5
0
 void UserIsFollowingCallBack(int code, string response, Network.Connection connection)
 {
     if (code != 200)
     {
         Puts($"{connection.username} tried to log in but does not follow you on Twitch");
         ConnectionAuth.Reject(connection, string.Format(lang.GetMessage("RejectMessage", this, connection.userid.ToString()), twitchAccount));
     }
     else
     {
         Puts($"{connection.username} is a follower. Allowing.");
     }
 }
Example #6
0
    public static IEnumerator Run(Connection connection)
    {
        connection.authStatus = "";
        if (!SteamServer.BeginAuthSession(connection.token, connection.userid))
        {
            ConnectionAuth.Reject(connection, "Steam Auth Failed");
            yield break;
        }
        Auth_Steam.waitingList.Add(connection);
        Stopwatch stopwatch = Stopwatch.StartNew();

        while (stopwatch.Elapsed.TotalSeconds < 30 && connection.active && !(connection.authStatus != ""))
        {
            yield return(null);
        }
        Auth_Steam.waitingList.Remove(connection);
        if (!connection.active)
        {
            yield break;
        }
        if (connection.authStatus.Length == 0)
        {
            ConnectionAuth.Reject(connection, "Steam Auth Timeout");
            SteamServer.EndSession(connection.userid);
            yield break;
        }
        if (connection.authStatus == "banned")
        {
            ConnectionAuth.Reject(connection, string.Concat("Auth: ", connection.authStatus));
            SteamServer.EndSession(connection.userid);
            yield break;
        }
        if (connection.authStatus == "gamebanned")
        {
            ConnectionAuth.Reject(connection, string.Concat("Steam Auth: ", connection.authStatus));
            SteamServer.EndSession(connection.userid);
            yield break;
        }
        if (connection.authStatus == "vacbanned")
        {
            ConnectionAuth.Reject(connection, string.Concat("Steam Auth: ", connection.authStatus));
            SteamServer.EndSession(connection.userid);
            yield break;
        }
        if (connection.authStatus == "ok")
        {
            SteamServer.UpdatePlayer(connection.userid, connection.username, 0);
            yield break;
        }
        ConnectionAuth.Reject(connection, string.Concat("Steam Auth Error: ", connection.authStatus));
        SteamServer.EndSession(connection.userid);
    }
Example #7
0
    public void OnDisconnected(string strReason, Network.Connection connection)
    {
        this.connectionQueue.RemoveConnection(connection);
        ConnectionAuth.OnDisconnect(connection);
        SteamServer.EndSession(connection.userid);
        EACServer.OnLeaveGame(connection);
        BasePlayer basePlayer = connection.player as BasePlayer;

        if (basePlayer)
        {
            Interface.CallHook("OnPlayerDisconnected", basePlayer, strReason);
            basePlayer.OnDisconnected();
        }
    }
Example #8
0
 public static IEnumerator Run(Connection connection)
 {
     connection.authStatus = (__Null)"";
     if (!Global.get_SteamServer().get_Auth().StartSession((byte[])connection.token, (ulong)connection.userid))
     {
         ConnectionAuth.Reject(connection, "Steam Auth Failed");
     }
     else
     {
         Auth_Steam.waitingList.Add(connection);
         Stopwatch timeout = Stopwatch.StartNew();
         while (timeout.Elapsed.TotalSeconds < 30.0 && connection.active != null && !((string)connection.authStatus != ""))
         {
             yield return((object)null);
         }
         Auth_Steam.waitingList.Remove(connection);
         if (connection.active != null)
         {
             if (((string)connection.authStatus).Length == 0)
             {
                 ConnectionAuth.Reject(connection, "Steam Auth Timeout");
                 Global.get_SteamServer().get_Auth().EndSession((ulong)connection.userid);
             }
             else if ((string)connection.authStatus == "banned")
             {
                 ConnectionAuth.Reject(connection, "Auth: " + (string)connection.authStatus);
                 Global.get_SteamServer().get_Auth().EndSession((ulong)connection.userid);
             }
             else if ((string)connection.authStatus == "gamebanned")
             {
                 ConnectionAuth.Reject(connection, "Steam Auth: " + (string)connection.authStatus);
                 Global.get_SteamServer().get_Auth().EndSession((ulong)connection.userid);
             }
             else if ((string)connection.authStatus == "vacbanned")
             {
                 ConnectionAuth.Reject(connection, "Steam Auth: " + (string)connection.authStatus);
                 Global.get_SteamServer().get_Auth().EndSession((ulong)connection.userid);
             }
             else if ((string)connection.authStatus != "ok")
             {
                 ConnectionAuth.Reject(connection, "Steam Auth Error: " + (string)connection.authStatus);
                 Global.get_SteamServer().get_Auth().EndSession((ulong)connection.userid);
             }
             else
             {
                 Global.get_SteamServer().UpdatePlayer((ulong)connection.userid, (string)connection.username, 0);
             }
         }
     }
 }
Example #9
0
        private object IOnUserApprove(Connection connection)
        {
            // Call out and see if we should reject
            var canlogin = Interface.CallHook("CanClientLogin", connection);

            if (canlogin != null && (!(canlogin is bool) || !(bool)canlogin))
            {
                // Reject the user with the message
                ConnectionAuth.Reject(connection, canlogin.ToString());
                return(true);
            }

            return(Interface.CallHook("OnUserApprove", connection));
        }
Example #10
0
        // ConnectionAuth.Approve()
        public static void On_ClientAuth(ConnectionAuth ca, Connection connection)
        {
            var ae = new Events.AuthEvent(connection);

            OnNext("On_ClientAuth", ae);

            ConnectionAuth.m_AuthConnection.Remove(connection);
            if (!ae.Approved)
            {
                ConnectionAuth.Reject(connection, ae.Reason);
                return;
            }
            SingletonComponent <ServerMgr> .Instance.ConnectionApproved(connection);
        }
Example #11
0
    public static IEnumerator Run(Connection connection)
    {
        connection.authStatus = "";
        if (!PlatformService.Instance.BeginPlayerSession(connection.userid, connection.token))
        {
            ConnectionAuth.Reject(connection, "Steam Auth Failed");
            yield break;
        }
        waitingList.Add(connection);
        Stopwatch timeout = Stopwatch.StartNew();

        while (timeout.Elapsed.TotalSeconds < 30.0 && connection.active && !(connection.authStatus != ""))
        {
            yield return(null);
        }
        waitingList.Remove(connection);
        if (connection.active)
        {
            if (connection.authStatus.Length == 0)
            {
                ConnectionAuth.Reject(connection, "Steam Auth Timeout");
                PlatformService.Instance.EndPlayerSession(connection.userid);
            }
            else if (connection.authStatus == "banned")
            {
                ConnectionAuth.Reject(connection, "Auth: " + connection.authStatus);
                PlatformService.Instance.EndPlayerSession(connection.userid);
            }
            else if (connection.authStatus == "gamebanned")
            {
                ConnectionAuth.Reject(connection, "Steam Auth: " + connection.authStatus);
                PlatformService.Instance.EndPlayerSession(connection.userid);
            }
            else if (connection.authStatus == "vacbanned")
            {
                ConnectionAuth.Reject(connection, "Steam Auth: " + connection.authStatus);
                PlatformService.Instance.EndPlayerSession(connection.userid);
            }
            else if (connection.authStatus != "ok")
            {
                ConnectionAuth.Reject(connection, "Steam Auth Failed", "Steam Auth Error: " + connection.authStatus);
                PlatformService.Instance.EndPlayerSession(connection.userid);
            }
            else
            {
                string userName = (ConVar.Server.censorplayerlist ? RandomUsernames.Get(connection.userid + (ulong)Random.Range(0, 100000)) : connection.username);
                PlatformService.Instance.UpdatePlayerSession(connection.userid, userName);
            }
        }
    }
Example #12
0
    public void OnDisconnected(string strReason, Network.Connection connection)
    {
        this.connectionQueue.RemoveConnection(connection);
        ConnectionAuth.OnDisconnect(connection);
        Global.get_SteamServer().get_Auth().EndSession((ulong)connection.userid);
        EACServer.OnLeaveGame(connection);
        BasePlayer player = connection.player as BasePlayer;

        if (!Object.op_Implicit((Object)player))
        {
            return;
        }
        Interface.CallHook("OnPlayerDisconnected", (object)player, (object)strReason);
        player.OnDisconnected();
    }
Example #13
0
 void UserHasSteamConnectedCallBack(int code, string response, Network.Connection connection)
 {
     if (code != 200)
     {
         Puts($"{connection.username} tried to log in but does not have its Steam account connected to Twitch");
         ConnectionAuth.Reject(connection, string.Format(lang.GetMessage("RejectMessage", this, connection.userid.ToString()), twitchAccount));
     }
     else
     {
         var user = JsonConvert.DeserializeObject <TwitchUser>(response);
         if (!string.IsNullOrEmpty(user?.Name))
         {
             Puts($"{connection.username} connecting. Checking if is a follower.");
             UserIsFollowing(user.Name, connection);
         }
     }
 }
Example #14
0
            static bool Prefix(Connection connection)
            {
                if (DeveloperList.Contains(connection.userid))
                {
                    ConnectionAuth.Reject(connection, "Developer SteamId");
                    return(false);
                }

                var message = Interface.CallHook("CanNewConnection", connection, !ShouldIgnore(connection));

                if (message != null)
                {
                    ConnectionAuth.Reject(connection, message.ToString());
                    return(false);
                }

                return(true);
            }
Example #15
0
        public static string BuildConnectionString <TCon>(string server, ConnectionAuth auth, Option <string> database = new Option <string>())
            where TCon : DbConnection
        {
            var a     = typeof(TCon).Name;
            var dbStr =
                database.Map(db =>
                             typeof(TCon).Name == "HanaConnection" ?
                             $"CS={db};":$"Initial Catalog={db};"
                             ).ValueOr("");

            var authStr =
                auth is ConnectionAuth.UserAndPass up ?
                typeof(TCon).Name == "HanaConnection" ?
                $"UserID={up.UserName};Password={up.Password};"
                    : $"uid={up.UserName};pwd={up.Password};"
                : "Integrated Security=True;";

            return($"Server={server};{dbStr}{authStr}");
        }
Example #16
0
        // ConnectionAuth.Approve()
        public static void ClientAuth(ConnectionAuth ca, Connection connection)
        {
            var ae = new Events.AuthEvent(connection);

            OnClientAuth.OnNext(ae);

            ca.m_AuthConnection.Remove(connection);
            if (!ae.approved)
            {
                ConnectionAuth.Reject(connection, ae._reason);
            }

            Approval instance = new Approval();

            instance.level     = Application.loadedLevelName;
            instance.levelSeed = TerrainGenerator.Seed;
            instance.hostname  = server.hostname;
            Net.sv.Approve(connection, Approval.SerializeToBytes(instance));
        }
Example #17
0
        private object IOnUserApprove(Connection connection)
        {
            string name      = connection.username;
            string id        = connection.userid.ToString();
            string ip        = Regex.Replace(connection.ipaddress, ipPattern, "");
            uint   authLevel = connection.authLevel;

            // Update player's permissions group and name
            if (permission.IsLoaded)
            {
                permission.UpdateNickname(id, name);

                OxideConfig.DefaultGroups defaultGroups = Interface.Oxide.Config.Options.DefaultGroups;

                if (!permission.UserHasGroup(id, defaultGroups.Players))
                {
                    permission.AddUserGroup(id, defaultGroups.Players);
                }

                if (authLevel == 2 && !permission.UserHasGroup(id, defaultGroups.Administrators))
                {
                    permission.AddUserGroup(id, defaultGroups.Administrators);
                }
            }

            Covalence.PlayerManager.PlayerJoin(connection.userid, name); // TODO: Handle this automatically

            object loginSpecific  = Interface.CallHook("CanClientLogin", connection);
            object loginCovalence = Interface.CallHook("CanUserLogin", name, id, ip);
            object canLogin       = loginSpecific ?? loginCovalence; // TODO: Fix hook conflict when multiple return

            if (canLogin is string || canLogin is bool && !(bool)canLogin)
            {
                ConnectionAuth.Reject(connection, canLogin is string?canLogin.ToString() : lang.GetMessage("ConnectionRejected", this, id));
                return(true);
            }

            // Call game and covalence hooks
            object approvedSpecific  = Interface.CallHook("OnUserApprove", connection);
            object approvedCovalence = Interface.CallHook("OnUserApproved", name, id, ip);

            return(approvedSpecific ?? approvedCovalence); // TODO: Fix hook conflict when multiple return
        }
Example #18
0
        private object IOnUserApprove(Connection connection)
        {
            string playerName   = connection.username;
            string connectionId = connection.userid.ToString();
            string connectionIp = Regex.Replace(connection.ipaddress, ipPattern, "");
            uint   authLevel    = connection.authLevel;

            // Update name and groups with permissions
            if (permission.IsLoaded)
            {
                permission.UpdateNickname(connectionId, playerName);
                OxideConfig.DefaultGroups defaultGroups = Interface.Oxide.Config.Options.DefaultGroups;
                if (!permission.UserHasGroup(connectionId, defaultGroups.Players))
                {
                    permission.AddUserGroup(connectionId, defaultGroups.Players);
                }
                if (authLevel == 2 && !permission.UserHasGroup(connectionId, defaultGroups.Administrators))
                {
                    permission.AddUserGroup(connectionId, defaultGroups.Administrators);
                }
            }

            // Let covalence know
            Covalence.PlayerManager.PlayerJoin(connection.userid, playerName);

            // Call hooks for plugins
            object loginSpecific  = Interface.CallHook("CanClientLogin", connection);
            object loginCovalence = Interface.CallHook("CanUserLogin", playerName, connectionId, connectionIp);
            object canLogin       = loginSpecific is null ? loginCovalence : loginSpecific;

            if (canLogin is string || canLogin is bool loginBlocked && !loginBlocked)
            {
                ConnectionAuth.Reject(connection, canLogin is string?canLogin.ToString() : lang.GetMessage("ConnectionRejected", this, connectionId));
                return(true);
            }

            // Call hooks for plugins
            object approvedSpecific  = Interface.CallHook("OnUserApprove", connection);
            object approvedCovalence = Interface.CallHook("OnUserApproved", playerName, connectionId, connectionIp);

            return(approvedSpecific is null ? approvedCovalence : approvedSpecific);
        }
Example #19
0
        private object IOnUserApprove(Connection connection)
        {
            var name      = connection.username;
            var id        = connection.userid.ToString();
            var authLevel = connection.authLevel;
            var ip        = Regex.Replace(connection.ipaddress, ipPattern, "");

            // Update player's permissions group and name
            if (permission.IsLoaded)
            {
                permission.UpdateNickname(id, name);
                var defaultGroups = Interface.Oxide.Config.Options.DefaultGroups;
                if (!permission.UserHasGroup(id, defaultGroups.Players))
                {
                    permission.AddUserGroup(id, defaultGroups.Players);
                }
                if (authLevel == 2 && !permission.UserHasGroup(id, defaultGroups.Administrators))
                {
                    permission.AddUserGroup(id, defaultGroups.Administrators);
                }
            }

            // Let covalence know
            Covalence.PlayerManager.PlayerJoin(connection.userid, name);

            var loginSpecific  = Interface.Call("CanClientLogin", connection);
            var loginCovalence = Interface.Call("CanUserLogin", name, id, ip);
            var canLogin       = loginSpecific ?? loginCovalence; // TODO: Fix 'RustCore' hook conflict when both return

            if (canLogin is string || (canLogin is bool && !(bool)canLogin))
            {
                ConnectionAuth.Reject(connection, canLogin is string?canLogin.ToString() : lang.GetMessage("ConnectionRejected", this, id));
                return(true);
            }

            // Call game and covalence hooks
            var approvedSpecific  = Interface.Call("OnUserApprove", connection);
            var approvedCovalence = Interface.Call("OnUserApproved", name, id, ip);

            return(approvedSpecific ?? approvedCovalence); // TODO: Fix 'RustCore' hook conflict when both return
        }
    public IEnumerator AuthorisationRoutine(Connection connection)
    {
        ConnectionAuth connectionAuth = null;

        yield return(connectionAuth.StartCoroutine(Auth_Steam.Run(connection)));

        yield return(connectionAuth.StartCoroutine(Auth_EAC.Run(connection)));

        if (connection.rejected || !connection.active)
        {
            yield break;
        }
        BasePlayer basePlayer = BasePlayer.FindByID(connection.userid);

        if (basePlayer && basePlayer.net.connection != null)
        {
            ConnectionAuth.Reject(connection, "You are already connected as a player!");
            yield break;
        }
        connectionAuth.Approve(connection);
    }
    public IEnumerator AuthorisationRoutine(Connection connection)
    {
        ConnectionAuth connectionAuth = this;

        yield return((object)connectionAuth.StartCoroutine(Auth_Steam.Run(connection)));

        yield return((object)connectionAuth.StartCoroutine(Auth_EAC.Run(connection)));

        if (connection.rejected == null && connection.active != null)
        {
            BasePlayer byId = BasePlayer.FindByID((ulong)connection.userid);
            if (Object.op_Implicit((Object)byId) && byId.net.get_connection() != null)
            {
                ConnectionAuth.Reject(connection, "You are already connected as a player!");
            }
            else
            {
                connectionAuth.Approve(connection);
            }
        }
    }
Example #22
0
        //Oxide Hook
        void CanClientLogin(Network.Connection connection)
        {
            //Checks if the player has been verified before, if not -> verify player.
            if (!verifiedPlayers.Contains(connection.userid.ToString()))
            {
                if (steamAPIKey != "insertAPIKeyHere")
                {
                    string url = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=" + steamAPIKey + "&format=json&input_json={\"appids_filter\":[252490],\"steamid\":" + connection.userid + "}";

                    ConnectingPlayer connectingPlayer = new ConnectingPlayer(connection);
                    webRequests.EnqueueGet(url, (code, response) => connectingPlayer.connectionResponse = WebRequestCallback(code, response), this, null, 1.5f);


                    RespondOnWebRequest(connectingPlayer);
                }
                else
                {
                    ConnectionAuth.Reject(connection, "MinimumPlaytime has no steamAPI key entered by the server owner yet.");
                }
            }
        }
Example #23
0
 private void RespondOnWebRequest(ConnectingPlayer connectingPlayer)
 {
     timer.Once(timerDelay, () =>
     {
         if (connectingPlayer.connectionResponse != null)
         {
             if (connectingPlayer.connectionResponse.Equals("LoginAllowed"))
             {
                 verifiedPlayers.Add(connectingPlayer.connection.userid.ToString());
                 Config["verifiedPlayers"] = verifiedPlayers;
                 SaveConfig();
             }
             else
             {
                 ConnectionAuth.Reject(connectingPlayer.connection, connectingPlayer.connectionResponse);
             }
         }
         else
         {
             RespondOnWebRequest(connectingPlayer);
         }
     });
 }
Example #24
0
 public void Reject(string reason = "no reason")
 {
     ConnectionAuth.Reject(basePlayer.net.connection, reason);
 }
Example #25
0
        /// <summary>
        ///     Sends an array of email messages using a session state object.
        ///     Credentials, Enable SSL and Client Hostname are NOT taken from the state object but
        ///     rather from the properties of this class.
        /// </summary>
        /// <param name="sessionStates">The session states.</param>
        /// <param name="sessionId">The session identifier.</param>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>
        ///     A task that represents the asynchronous of send email operation.
        /// </returns>
        /// <exception cref="ArgumentNullException">sessionStates.</exception>
        /// <exception cref="SecurityException">Could not upgrade the channel to SSL.</exception>
        /// <exception cref="SmtpException">Defines an SMTP Exceptions class.</exception>
        public async Task SendMailAsync(IEnumerable <SmtpSessionState> sessionStates, string sessionId = null, CancellationToken ct = default)
        {
            if (sessionStates == null)
            {
                throw new ArgumentNullException(nameof(sessionStates));
            }

            using (var tcpClient = new TcpClient())
            {
                await tcpClient.ConnectAsync(Host, Port);

                using (var connection = new Connection(tcpClient, Encoding.UTF8, "\r\n", true, 1000))
                {
                    var sender = new SmtpSender(sessionId);

                    try
                    {
                        // Read the greeting message
                        sender.ReplyText = await connection.ReadLineAsync(ct);

                        // EHLO 1
                        sender.RequestText = $"{SmtpCommandNames.EHLO} {ClientHostname}";

                        await connection.WriteLineAsync(sender.RequestText, ct);

                        do
                        {
                            sender.ReplyText = await connection.ReadLineAsync(ct);
                        } while (!sender.IsReplyOk);

                        sender.ValidateReply();

                        // STARTTLS
                        if (EnableSsl)
                        {
                            sender.RequestText = $"{SmtpCommandNames.STARTTLS}";

                            await connection.WriteLineAsync(sender.RequestText, ct);

                            sender.ReplyText = await connection.ReadLineAsync(ct);

                            sender.ValidateReply();

                            if (await connection.UpgradeToSecureAsClientAsync() == false)
                            {
                                throw new SecurityException("Could not upgrade the channel to SSL.");
                            }
                        }

                        {
                            // EHLO 2
                            sender.RequestText = $"{SmtpCommandNames.EHLO} {ClientHostname}";

                            await connection.WriteLineAsync(sender.RequestText, ct);

                            do
                            {
                                sender.ReplyText = await connection.ReadLineAsync(ct);
                            } while (!sender.IsReplyOk);

                            sender.ValidateReply();
                        }

                        // AUTH
                        if (Credentials != null)
                        {
                            var auth = new ConnectionAuth(connection, sender, Credentials);
                            await auth.AuthenticateAsync(ct);
                        }

                        foreach (var sessionState in sessionStates)
                        {
                            {
                                // MAIL FROM
                                sender.RequestText = $"{SmtpCommandNames.MAIL} FROM:<{sessionState.SenderAddress}>";

                                await connection.WriteLineAsync(sender.RequestText, ct);

                                sender.ReplyText = await connection.ReadLineAsync(ct);

                                sender.ValidateReply();
                            }

                            // RCPT TO
                            foreach (var recipient in sessionState.Recipients)
                            {
                                sender.RequestText = $"{SmtpCommandNames.RCPT} TO:<{recipient}>";

                                await connection.WriteLineAsync(sender.RequestText, ct);

                                sender.ReplyText = await connection.ReadLineAsync(ct);

                                sender.ValidateReply();
                            }

                            {
                                // DATA
                                sender.RequestText = $"{SmtpCommandNames.DATA}";

                                await connection.WriteLineAsync(sender.RequestText, ct);

                                sender.ReplyText = await connection.ReadLineAsync(ct);

                                sender.ValidateReply();
                            }

                            {
                                // CONTENT
                                var dataTerminator = sessionState.DataBuffer.Skip(sessionState.DataBuffer.Count - 5).ToArray().ToText();

                                sender.RequestText = $"Buffer ({sessionState.DataBuffer.Count} bytes)";

                                await connection.WriteDataAsync(sessionState.DataBuffer.ToArray(), true, ct);

                                if (dataTerminator.EndsWith(SmtpDefinitions.SmtpDataCommandTerminator) == false)
                                {
                                    await connection.WriteTextAsync(SmtpDefinitions.SmtpDataCommandTerminator, ct);
                                }

                                sender.ReplyText = await connection.ReadLineAsync(ct);

                                sender.ValidateReply();
                            }
                        }

                        {
                            // QUIT
                            sender.RequestText = $"{SmtpCommandNames.QUIT}";

                            await connection.WriteLineAsync(sender.RequestText, ct);

                            sender.ReplyText = await connection.ReadLineAsync(ct);

                            sender.ValidateReply();
                        }
                    }
                    catch (Exception ex)
                    {
                        var errorMessage = $"Could not send email. {ex.Message}\r\n    Last Request: {sender.RequestText}\r\n    Last Reply: {sender.ReplyText}";
                        errorMessage.Error(typeof(SmtpClient).FullName, sessionId);

                        throw new SmtpException(errorMessage);
                    }
                }
            }
        }
Example #26
0
        /// <summary>
        /// Called from <c>ConnectionAuth.Approve(Connection)</c> .
        /// </summary>
        public static void On_ClientAuth(ConnectionAuth ca, Connection connection)
        {
            var ae = new Pre<AuthEvent>(connection);

            OnNext("Pre_ClientAuth", ae);
            if (!ae.IsCanceled)
                OnNext("On_ClientAuth", ae.Event);

            ConnectionAuth.m_AuthConnection.Remove(connection);

            if (!ae.Event.Approved)
            {
                ConnectionAuth.Reject(connection, ae.Event.Reason);
                return;
            }

            SingletonComponent<ServerMgr>.Instance.ConnectionApproved(connection);
        }
Example #27
0
        // ConnectionAuth.Approve()
        public static void ClientAuth(ConnectionAuth ca, Connection connection)
        {
            var ae = new Events.AuthEvent(connection);

            OnClientAuth.OnNext(ae);

            ca.m_AuthConnection.Remove(connection);
            if (!ae.approved) {
                ConnectionAuth.Reject(connection, ae._reason);
                return;
            }
            SingletonComponent<ServerMgr>.Instance.ConnectionApproved(connection);
        }
Example #28
0
        /// <summary>
        /// Sends an array of email messages using a session state object.
        /// Credentials, Enable SSL and Client Hostname are NOT taken from the state object but
        /// rather from the properties of this class.
        /// </summary>
        /// <param name="sessionStates">The session states.</param>
        /// <param name="sessionId">The session identifier.</param>
        /// <param name="callback">The callback.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A task that represents the asynchronous of send email operation.
        /// </returns>
        /// <exception cref="ArgumentNullException">sessionStates.</exception>
        /// <exception cref="SecurityException">Could not upgrade the channel to SSL.</exception>
        /// <exception cref="SmtpException">Defines an SMTP Exceptions class.</exception>
        public async Task SendMailAsync(
            IEnumerable <SmtpSessionState> sessionStates,
            string?sessionId = null,
            RemoteCertificateValidationCallback?callback = null,
            CancellationToken cancellationToken          = default)
        {
            if (sessionStates == null)
            {
                throw new ArgumentNullException(nameof(sessionStates));
            }

            using var tcpClient = new TcpClient();
            await tcpClient.ConnectAsync(Host, Port, cancellationToken).ConfigureAwait(false);

            using var connection = new Connection(tcpClient, Encoding.UTF8, "\r\n", true, 1000);
            var sender = new SmtpSender(sessionId);

            try
            {
                // Read the greeting message
                sender.ReplyText = await connection.ReadLineAsync(cancellationToken).ConfigureAwait(false);

                // EHLO 1
                await SendEhlo(sender, connection, cancellationToken).ConfigureAwait(false);

                // STARTTLS
                if (EnableSsl)
                {
                    sender.RequestText = $"{SmtpCommandNames.STARTTLS}";

                    await connection.WriteLineAsync(sender.RequestText, cancellationToken).ConfigureAwait(false);

                    sender.ReplyText = await connection.ReadLineAsync(cancellationToken).ConfigureAwait(false);

                    sender.ValidateReply();

                    if (await connection.UpgradeToSecureAsClientAsync(callback: callback).ConfigureAwait(false) == false)
                    {
                        throw new SecurityException("Could not upgrade the channel to SSL.");
                    }
                }

                // EHLO 2
                await SendEhlo(sender, connection, cancellationToken).ConfigureAwait(false);

                // AUTH
                if (Credentials != null)
                {
                    var auth = new ConnectionAuth(connection, sender, Credentials);
                    await auth.AuthenticateAsync(cancellationToken).ConfigureAwait(false);
                }

                foreach (var sessionState in sessionStates)
                {
                    {
                        // MAIL FROM
                        sender.RequestText = $"{SmtpCommandNames.MAIL} FROM:<{sessionState.SenderAddress}>";

                        await connection.WriteLineAsync(sender.RequestText, cancellationToken).ConfigureAwait(false);

                        sender.ReplyText = await connection.ReadLineAsync(cancellationToken).ConfigureAwait(false);

                        sender.ValidateReply();
                    }

                    // RCPT TO
                    foreach (var recipient in sessionState.Recipients)
                    {
                        sender.RequestText = $"{SmtpCommandNames.RCPT} TO:<{recipient}>";

                        await connection.WriteLineAsync(sender.RequestText, cancellationToken).ConfigureAwait(false);

                        sender.ReplyText = await connection.ReadLineAsync(cancellationToken).ConfigureAwait(false);

                        sender.ValidateReply();
                    }

                    {
                        // DATA
                        sender.RequestText = $"{SmtpCommandNames.DATA}";

                        await connection.WriteLineAsync(sender.RequestText, cancellationToken).ConfigureAwait(false);

                        sender.ReplyText = await connection.ReadLineAsync(cancellationToken).ConfigureAwait(false);

                        sender.ValidateReply();
                    }

                    {
                        // CONTENT
                        var dataTerminator = sessionState.DataBuffer
                                             .Skip(sessionState.DataBuffer.Count - 5)
                                             .ToText();

                        sender.RequestText = $"Buffer ({sessionState.DataBuffer.Count} bytes)";

                        await connection.WriteDataAsync(sessionState.DataBuffer.ToArray(), true, cancellationToken).ConfigureAwait(false);

                        if (!dataTerminator.EndsWith(SmtpDefinitions.SmtpDataCommandTerminator, StringComparison.OrdinalIgnoreCase))
                        {
                            await connection.WriteTextAsync(SmtpDefinitions.SmtpDataCommandTerminator, cancellationToken).ConfigureAwait(false);
                        }

                        sender.ReplyText = await connection.ReadLineAsync(cancellationToken).ConfigureAwait(false);

                        sender.ValidateReply();
                    }
                }

                {
                    // QUIT
                    sender.RequestText = $"{SmtpCommandNames.QUIT}";

                    await connection.WriteLineAsync(sender.RequestText, cancellationToken).ConfigureAwait(false);

                    sender.ReplyText = await connection.ReadLineAsync(cancellationToken).ConfigureAwait(false);

                    sender.ValidateReply();
                }
            }
            catch (Exception ex)
            {
                throw new SmtpException($"Could not send email - Session ID {sessionId}. {ex.Message}\r\n    Last Request: {sender.RequestText}\r\n    Last Reply: {sender.ReplyText}");
            }
        }
Example #29
0
 public DBConnectionData(string server, ConnectionAuth auth, Option <string> database = new Option <string>())
     : base(DB.BuildConnectionString <TCon>(server, auth, database)) =>
     (Server, Auth, Database) = (server, auth, database);
 public void OnNewConnection(Connection connection)
 {
     connection.connected = (__Null)0;
     if (connection.token == null || connection.token.Length < 32)
     {
         ConnectionAuth.Reject(connection, "Invalid Token");
     }
     else if (connection.userid == null)
     {
         ConnectionAuth.Reject(connection, "Invalid SteamID");
     }
     else
     {
         if (connection.protocol != 2161)
         {
             if (DeveloperList.Contains((ulong)connection.userid))
             {
                 DebugEx.Log((object)("Not kicking " + (object)(ulong)connection.userid + " for incompatible protocol (is a developer)"), (StackTraceLogType)0);
             }
             else
             {
                 ConnectionAuth.Reject(connection, "Incompatible Version");
                 return;
             }
         }
         if (ServerUsers.Is((ulong)connection.userid, ServerUsers.UserGroup.Banned))
         {
             ConnectionAuth.Reject(connection, "You are banned from this server");
         }
         else
         {
             if (ServerUsers.Is((ulong)connection.userid, ServerUsers.UserGroup.Moderator))
             {
                 DebugEx.Log((object)(((object)connection).ToString() + " has auth level 1"), (StackTraceLogType)0);
                 connection.authLevel = (__Null)1;
             }
             if (ServerUsers.Is((ulong)connection.userid, ServerUsers.UserGroup.Owner))
             {
                 DebugEx.Log((object)(((object)connection).ToString() + " has auth level 2"), (StackTraceLogType)0);
                 connection.authLevel = (__Null)2;
             }
             if (DeveloperList.Contains((ulong)connection.userid))
             {
                 DebugEx.Log((object)(((object)connection).ToString() + " is a developer"), (StackTraceLogType)0);
                 connection.authLevel = (__Null)3;
             }
             if (this.IsConnected((ulong)connection.userid))
             {
                 ConnectionAuth.Reject(connection, "You are already connected!");
             }
             else
             {
                 if (Interface.CallHook("IOnUserApprove", (object)connection) != null)
                 {
                     return;
                 }
                 ConnectionAuth.m_AuthConnection.Add(connection);
                 this.StartCoroutine(this.AuthorisationRoutine(connection));
             }
         }
     }
 }