private void Authenticate(IConnection connection)
 {
     if (!connection.IsAuthenticated)
     {
         if (SaslMechanism != null)
         {
             var result = SaslMechanism.Authenticate(connection);
             if (result)
             {
                 Log.Debug(
                     m =>
                     m("Authenticated {0} using {1} - {2} [{3}].", SaslMechanism.Username, SaslMechanism.GetType(),
                       _identity, EndPoint));
                 connection.IsAuthenticated = true;
             }
             else
             {
                 Log.Debug(
                     m =>
                     m("Could not authenticate {0} using {1} - {2} [{3}].", SaslMechanism.Username,
                       SaslMechanism.GetType(), _identity, EndPoint));
                 throw new AuthenticationException(ExceptionUtil.FailedBucketAuthenticationMsg.WithParams(SaslMechanism.Username));
             }
         }
     }
 }
        public KafkaSink(
            string bootstrapServers,
            SecurityProtocol securityProtocol,
            SaslMechanism saslMechanism,
            string saslUsername,
            string saslPassword,
            string sslCaLocation,
            string topic = null,
            Func <LogEvent, string> topicDecider = null,
            ITextFormatter formatter             = null)
        {
            ConfigureKafkaConnection(
                bootstrapServers,
                securityProtocol,
                saslMechanism,
                saslUsername,
                saslPassword,
                sslCaLocation);

            _formatter = formatter ?? new Formatting.Json.JsonFormatter(renderMessage: true);

            if (topic != null)
            {
                _globalTopicPartition = new TopicPartition(topic, Partition.Any);
            }

            if (topicDecider != null)
            {
                _topicDecider = topicDecider;
            }
        }
        public static LoggerConfiguration Kafka(
            this LoggerSinkConfiguration loggerConfiguration,
            Func <LogEvent, string> topicDecider,
            string bootstrapServers = "localhost:9092",
            int batchSizeLimit      = 50,
            int period = 5,
            SecurityProtocol securityProtocol = SecurityProtocol.Plaintext,
            SaslMechanism saslMechanism       = SaslMechanism.Plain,
            string saslUsername                = null,
            string saslPassword                = null,
            string sslCaLocation               = null,
            ITextFormatter formatter           = null,
            LogEventLevel restrictedToMinLevel = LogEventLevel.Verbose,
            LoggingLevelSwitch levelSwitch     = null)
        {
            var sink = new KafkaSink(
                bootstrapServers,
                batchSizeLimit,
                period,
                securityProtocol,
                saslMechanism,
                topicDecider,
                saslUsername,
                saslPassword,
                sslCaLocation,
                formatter);

            return(loggerConfiguration.Sink(sink, restrictedToMinLevel, levelSwitch));
        }
 public static LoggerConfiguration Kafka(
     this LoggerSinkConfiguration loggerConfiguration,
     Func <LogEvent, string> topicDecider,
     string bootstrapServers = "localhost:9092",
     int batchSizeLimit      = 50,
     int period = 5,
     SecurityProtocol securityProtocol = SecurityProtocol.Plaintext,
     SaslMechanism saslMechanism       = SaslMechanism.Plain,
     string saslUsername      = null,
     string saslPassword      = null,
     string sslCaLocation     = null,
     ITextFormatter formatter = null)
 {
     return(loggerConfiguration.Kafka(
                bootstrapServers,
                batchSizeLimit,
                period,
                securityProtocol,
                saslMechanism,
                saslUsername,
                saslPassword,
                sslCaLocation,
                topic: null,
                topicDecider,
                formatter));
 }
示例#5
0
        /// <summary>
        /// Adds a sink that writes log events to a Kafka topic in the broker endpoints.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="batchSizeLimit">The maximum number of events to include in a single batch.</param>
        /// <param name="period">The time in seconds to wait between checking for event batches.</param>
        /// <param name="bootstrapServers">The list of bootstrapServers separated by comma.</param>
        /// <param name="topic">The topic name.</param>
        /// <returns></returns>
        public static LoggerConfiguration Kafka(
            this LoggerSinkConfiguration loggerConfiguration,
            string bootstrapServers = "localhost:9092",
            int batchSizeLimit      = 50,
            int period = 5,
            SecurityProtocol securityProtocol = SecurityProtocol.Plaintext,
            SaslMechanism saslMechanism       = SaslMechanism.Plain,
            string topic         = "logs",
            string saslUsername  = null,
            string saslPassword  = null,
            string sslCaLocation = null)
        {
            var sink = new KafkaSink(
                bootstrapServers,
                batchSizeLimit,
                period,
                securityProtocol,
                saslMechanism,
                topic,
                saslUsername,
                saslPassword,
                sslCaLocation);

            return(loggerConfiguration.Sink(sink));
        }
示例#6
0
        public KafkaSink(
            string bootstrapServers,
            int batchSizeLimit,
            int period,
            SecurityProtocol securityProtocol,
            SaslMechanism saslMechanism,
            string topic,
            string saslUsername,
            string saslPassword,
            string sslCaLocation) : base(batchSizeLimit, TimeSpan.FromSeconds(period))
        {
            var config = new ProducerConfig()
                         .SetValue("ApiVersionFallbackMs", 0)
                         .SetValue("EnableDeliveryReports", false)
                         .LoadFromEnvironmentVariables()
                         .SetValue("BootstrapServers", bootstrapServers)
                         .SetValue("SecurityProtocol", securityProtocol)
                         .SetValue("SaslMechanism", saslMechanism)
                         .SetValue("SslCaLocation", string.IsNullOrEmpty(sslCaLocation) ? null : Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), sslCaLocation))
                         .SetValue("SaslUsername", saslUsername)
                         .SetValue("SaslPassword", saslPassword);

            producer = new ProducerBuilder <Null, byte[]>(config)
                       .Build();

            formatter  = new Formatting.Json.JsonFormatter(renderMessage: true);
            this.topic = new TopicPartition(topic, Partition.Any);
        }
示例#7
0
 public void TestSaslPrep()
 {
     // The following examples are from rfc4013, Section 3.
     // #  Input            Output     Comments
     // -  -----            ------     --------
     // 1  I<U+00AD>X       IX         SOFT HYPHEN mapped to nothing
     Assert.AreEqual("IX", SaslMechanism.SaslPrep("I\u00ADX"), "1");
     // 2  user             user       no transformation
     Assert.AreEqual("user", SaslMechanism.SaslPrep("user"), "2");
     // 3  USER             USER       case preserved, will not match #2
     Assert.AreEqual("USER", SaslMechanism.SaslPrep("USER"), "3");
     // 4  <U+00AA>         a          output is NFKC, input in ISO 8859-1
     Assert.AreEqual("a", SaslMechanism.SaslPrep("\u00AA"), "4");
     // 5  <U+2168>         IX         output is NFKC, will match #1
     Assert.AreEqual("IX", SaslMechanism.SaslPrep("\u2168"), "5");
     // 6  <U+0007>                    Error - prohibited character
     try {
         SaslMechanism.SaslPrep("\u0007");
         Assert.Fail("6");
     } catch (ArgumentException) {
     }
     // 7  <U+0627><U+0031>            Error - bidirectional check
     //try {
     //	SaslMechanism.SaslPrep ("\u0627\u0031");
     //	Assert.Fail ("7");
     //} catch (ArgumentException) {
     //}
 }
示例#8
0
 public override void Authenticate(SaslMechanism mechanism, CancellationToken cancellationToken = new CancellationToken())
 {
     if (AuthenticateException != null)
     {
         throw AuthenticateException;
     }
 }
        private void ConfigureKafkaConnection(
            string bootstrapServers,
            SecurityProtocol securityProtocol,
            SaslMechanism saslMechanism,
            string saslUsername,
            string saslPassword,
            string sslCaLocation)
        {
            var config = new ProducerConfig()
                         .SetValue("ApiVersionFallbackMs", 0)
                         .SetValue("EnableDeliveryReports", false)
                         .LoadFromEnvironmentVariables()
                         .SetValue("BootstrapServers", bootstrapServers)
                         .SetValue("SecurityProtocol", securityProtocol)
                         .SetValue("SaslMechanism", saslMechanism)
                         .SetValue("SslCaLocation",
                                   string.IsNullOrEmpty(sslCaLocation)
                        ? null
                        : Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), sslCaLocation))
                         .SetValue("SaslUsername", saslUsername)
                         .SetValue("SaslPassword", saslPassword);

            _producer = new ProducerBuilder <Null, byte[]>(config)
                        .Build();
        }
        public string Authenticate(string username, string password, SaslMechanism mechanism, int millisecondsTimeout)
        {
            var func = new Func <string>(() => Authenticate(username, password, mechanism));

            var result = RunMethodWithTimeout(func, millisecondsTimeout);

            return(result);
        }
示例#11
0
        public void SendSsl(string host, int port, string username, string password, SaslMechanism mechanism)
        {
            //CheckBuiltMimePartTree();
#if !PocketPC
            SmtpClient.SendSsl(this, host, port, username, password, mechanism);
#else
            SmtpClient.Send(this, host, port, username, password, mechanism);
#endif
        }
示例#12
0
        public override Task AuthenticateAsync(SaslMechanism mechanism, CancellationToken cancellationToken = new CancellationToken())
        {
            if (AuthenticateException != null)
            {
                throw AuthenticateException;
            }

            return(Task.CompletedTask);
        }
示例#13
0
        public byte[] Start(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint)
        {
            m = SaslFactory.Create("DIGEST-MD5");

            m.Properties.Add("Username", Username);
            m.Properties.Add("Password", Password);
            m.Properties.Add("Protocol", "zookeeper");

            // Client start is empty.
            return(null);
        }
示例#14
0
        public static KafkaStreamOptions WithSaslOptions(
            this KafkaStreamOptions options,
            Credentials credentials,
            SaslMechanism saslMechanism = SaslMechanism.Plain
            )
        {
            options.SaslMechanism    = saslMechanism;
            options.SecurityProtocol = SecurityProtocol.SaslSsl;
            options.SaslUserName     = credentials.UserName;
            options.SaslPassword     = credentials.Password;
            options.SslCaLocation    = credentials.SslCaLocation;

            return(options);
        }
        protected void Authenticate(IConnection connection)
        {
            if (Configuration.ClientConfiguration?.EnableCertificateAuthentication ?? false)
            {
                Log.Trace("Ignoring authentication using x509 cert.");
                //ignore auth if cert auth is being used
                return;
            }
            Log.Trace("1. Checking authentication [{0}|{1}]: {2} - {3}", connection.IsAuthenticated,
                      connection.IsDead, EndPoint, connection.Identity);

            if (connection.IsAuthenticated || connection.IsDead)
            {
                return;
            }

            Log.Trace("2. Checking authentication [{0}|{1}]: {2} - {3}", connection.IsAuthenticated,
                      connection.IsDead, EndPoint, connection.Identity);

            if (SaslMechanism != null)
            {
                Log.Trace("3. Checking authentication [{0}]: {1} - {2}", connection.IsAuthenticated, EndPoint,
                          connection.Identity);
                var result = SaslMechanism.Authenticate(connection);
                if (result)
                {
                    Log.Info(
                        "4. Authenticated {0} using {1} - {2} - {3} [{4}].", User(SaslMechanism.Username),
                        SaslMechanism.GetType(),
                        Identity, connection.Identity, EndPoint);
                    connection.IsAuthenticated = true;
                }
                else
                {
                    Log.Info(
                        "4. Could not authenticate {0} using {1} - {2} [{3}].", User(SaslMechanism.Username),
                        SaslMechanism.GetType(), Identity, EndPoint);

                    connection.IsDead = true;
                    connection.Dispose();

                    var message = SupportsEnhancedAuthentication
                        ? ExceptionUtil.FailedUserAuthenticationMsg.WithParams(User(SaslMechanism.Username))
                        : ExceptionUtil.FailedBucketAuthenticationMsg.WithParams(Configuration.BucketName);

                    throw new AuthenticationException(message);
                }
            }
        }
示例#16
0
        public void TestArgumentExceptions()
        {
            var credentials = new NetworkCredential("username", "password");

            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create(null, Encoding.UTF8, credentials));
            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", null, credentials));
            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", Encoding.UTF8, null));

            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create(null, credentials));
            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", null));

            Assert.Throws <ArgumentNullException> (() => SaslMechanism.IsSupported(null));

            Assert.Throws <ArgumentNullException> (() => SaslMechanism.SaslPrep(null));
        }
示例#17
0
 public Options()
 {
     this.broker        = "127.0.0.1";
     this.port          = 5672;
     this.messageCount  = 500000;
     this.messageSize   = 1024;
     this.type          = ClientType.InteropDemo; // default: once as pub and once as sub
     this.baseName      = "qpid-perftest";
     this.pubTxSize     = 0;
     this.subTxSize     = 0;
     this.durable       = false;
     this.ssl           = false;
     this.username      = null;
     this.password      = null;
     this.saslMechanism = SaslMechanism.None;
 }
示例#18
0
        public void TestArgumentExceptions()
        {
            var credentials = new NetworkCredential("username", "password");
            var uri         = new Uri("smtp://localhost");

            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create(null, uri, Encoding.UTF8, credentials));
            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", null, Encoding.UTF8, credentials));
            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", uri, null, credentials));
            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", uri, Encoding.UTF8, null));

            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create(null, uri, credentials));
            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", null, credentials));
            Assert.Throws <ArgumentNullException> (() => SaslMechanism.Create("PLAIN", uri, null));

            Assert.Throws <ArgumentNullException> (() => SaslMechanism.SaslPrep(null));
        }
示例#19
0
        public static string ToNameString(this SaslMechanism saslType)
        {
            switch (saslType)
            {
            case SaslMechanism.Login:
                return("");

            case SaslMechanism.None:
                return("none");

            case SaslMechanism.CramMd5:
                return("password-encrypted");

            default:
                throw new ArgumentException("Unknown mail server SaslMechanism: " + Enum.GetName(typeof(SaslMechanism), saslType));
            }
        }
示例#20
0
        public static string ToNameString(this SaslMechanism saslType)
        {
            switch (saslType)
            {
            case SaslMechanism.Login:
                return("");

            case SaslMechanism.None:
                return(Defines.NONE);

            case SaslMechanism.CramMd5:
                return(Defines.PASSWORD_ENCRYPTED);

            default:
                throw new ArgumentException("Unknown mail server SaslMechanism: " + Enum.GetName(typeof(SaslMechanism), saslType));
            }
        }
示例#21
0
        public KafkaSink(
            string bootstrapServers,
            int batchSizeLimit,
            int period,
            SecurityProtocol securityProtocol,
            SaslMechanism saslMechanism,
            Func <LogEvent, string> topicDecider,
            string saslUsername,
            string saslPassword,
            string sslCaLocation,
            ITextFormatter formatter = null) : base(batchSizeLimit, TimeSpan.FromSeconds(period))
        {
            ConfigureKafkaConnection(bootstrapServers, securityProtocol, saslMechanism, saslUsername,
                                     saslPassword, sslCaLocation);

            this.formatter = formatter ?? new Formatting.Json.JsonFormatter(renderMessage: true);

            this._topicDecider = topicDecider;
        }
示例#22
0
        public void TestSaslPrep()
        {
            // The following examples are from rfc4013, Section 3.
            // #  Input            Output     Comments
            // -  -----            ------     --------
            // 1  I<U+00AD>X       IX         SOFT HYPHEN mapped to nothing
            Assert.AreEqual("IX", SaslMechanism.SaslPrep("I\u00ADX"), "1");
            // 2  user             user       no transformation
            Assert.AreEqual("user", SaslMechanism.SaslPrep("user"), "2");
            // 3  USER             USER       case preserved, will not match #2
            Assert.AreEqual("USER", SaslMechanism.SaslPrep("USER"), "3");
            // 4  <U+00AA>         a          output is NFKC, input in ISO 8859-1
            Assert.AreEqual("a", SaslMechanism.SaslPrep("\u00AA"), "4");
            // 5  <U+2168>         IX         output is NFKC, will match #1
            Assert.AreEqual("IX", SaslMechanism.SaslPrep("\u2168"), "5");
            // 6  <U+0007>                    Error - prohibited character
            try {
                SaslMechanism.SaslPrep("\u0007");
                Assert.Fail("6");
            } catch (ArgumentException) {
            }
            // 7  <U+0627><U+0031>            Error - bidirectional check
            //try {
            //	SaslMechanism.SaslPrep ("\u0627\u0031");
            //	Assert.Fail ("7");
            //} catch (ArgumentException) {
            //}

            var prohibited = new char [] { '\uF8FF', '\uDFFF', '\uFFFD', '\u2FFB', '\u200E' };

            foreach (var c in prohibited)
            {
                try {
                    SaslMechanism.SaslPrep(c.ToString());
                    Assert.Fail("prohibited: '\\u{0:X}'", c);
                } catch (ArgumentException) {
                }
            }

            Assert.AreEqual(string.Empty, SaslMechanism.SaslPrep(string.Empty));
            Assert.AreEqual("a b", SaslMechanism.SaslPrep("a\u00A0b"));
        }
        public void TestIsSupported()
        {
            var supported   = new [] { "PLAIN", "LOGIN", "CRAM-MD5", "DIGEST-MD5", "SCRAM-SHA-1", "SCRAM-SHA-256", "NTLM", "XOAUTH2" };
            var unsupported = new [] { "ANONYMOUS", "GSSAPI", "KERBEROS_V4" };
            var credentials = new NetworkCredential("username", "password");
            var uri         = new Uri("smtp://localhost");

            foreach (var mechanism in supported)
            {
                Assert.IsTrue(SaslMechanism.IsSupported(mechanism), mechanism);
                var sasl = SaslMechanism.Create(mechanism, uri, credentials);
                Assert.IsNotNull(sasl, mechanism);
                Assert.AreEqual(mechanism, sasl.MechanismName, "MechanismName");
            }

            foreach (var mechanism in unsupported)
            {
                Assert.IsFalse(SaslMechanism.IsSupported(mechanism), mechanism);
            }
        }
        protected void Authenticate(IConnection connection)
        {
            Log.Trace("1. Checking authentication [{0}|{1}]: {2} - {3}", connection.IsAuthenticated,
                      connection.IsDead, EndPoint, connection.Identity);

            if (connection.IsAuthenticated || connection.IsDead)
            {
                return;
            }

            Log.Trace("2. Checking authentication [{0}|{1}]: {2} - {3}", connection.IsAuthenticated,
                      connection.IsDead, EndPoint, connection.Identity);

            if (SaslMechanism != null)
            {
                Log.Trace("3. Checking authentication [{0}]: {1} - {2}", connection.IsAuthenticated, EndPoint,
                          connection.Identity);
                var result = SaslMechanism.Authenticate(connection);
                if (result)
                {
                    Log.Info(
                        "4. Authenticated {0} using {1} - {2} - {3} [{4}].", SaslMechanism.Username,
                        SaslMechanism.GetType(),
                        Identity, connection.Identity, EndPoint);
                    connection.IsAuthenticated = true;
                }
                else
                {
                    Log.Info(
                        "4. Could not authenticate {0} using {1} - {2} [{3}].", SaslMechanism.Username,
                        SaslMechanism.GetType(), Identity, EndPoint);

                    var message = SupportsEnhancedAuthentication
                        ? ExceptionUtil.FailedUserAuthenticationMsg.WithParams(SaslMechanism.Username)
                        : ExceptionUtil.FailedBucketAuthenticationMsg.WithParams(Configuration.BucketName);

                    throw new AuthenticationException(message);
                }
            }
        }
示例#25
0
        public void TestIsSupported()
        {
            var supported   = new [] { "PLAIN", "LOGIN", "CRAM-MD5", "DIGEST-MD5", "SCRAM-SHA-1", "SCRAM-SHA-1-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS", "SCRAM-SHA-512", "SCRAM-SHA-512-PLUS", "NTLM", "OAUTHBEARER", "XOAUTH2", "ANONYMOUS" };
            var unsupported = new [] { "EXTERNAL", "GSSAPI", "KERBEROS_V4" };
            var credentials = new NetworkCredential("username", "password");

            foreach (var mechanism in supported)
            {
                Assert.IsTrue(SaslMechanism.IsSupported(mechanism), mechanism);

                var sasl = SaslMechanism.Create(mechanism, credentials);
                Assert.IsNotNull(sasl, mechanism);
                Assert.AreEqual(mechanism, sasl.MechanismName, "MechanismName");

                sasl.Reset();
            }

            foreach (var mechanism in unsupported)
            {
                Assert.IsFalse(SaslMechanism.IsSupported(mechanism), mechanism);
            }
        }
        private static LoggerConfiguration Kafka(
            this LoggerSinkConfiguration loggerConfiguration,
            string bootstrapServers,
            int batchSizeLimit,
            int period,
            SecurityProtocol securityProtocol,
            SaslMechanism saslMechanism,
            string saslUsername,
            string saslPassword,
            string sslCaLocation,
            string topic,
            Func <LogEvent, string> topicDecider,
            ITextFormatter formatter)
        {
            var kafkaSink = new KafkaSink(
                bootstrapServers,
                securityProtocol,
                saslMechanism,
                saslUsername,
                saslPassword,
                sslCaLocation,
                topic,
                topicDecider,
                formatter);

            var batchingOptions = new PeriodicBatchingSinkOptions
            {
                BatchSizeLimit = batchSizeLimit,
                Period         = TimeSpan.FromSeconds(period)
            };

            var batchingSink = new PeriodicBatchingSink(
                kafkaSink,
                batchingOptions);

            return(loggerConfiguration
                   .Sink(batchingSink));
        }
示例#27
0
        internal override void SetProtocolOp(Asn1ProtocolOp op)
        {
            var bindRequest = op.BindRequest = new Asn1BindRequest
            {
                Version        = Version,
                Name           = Name.GetBytes(),
                Authentication = new Asn1AuthenticationChoice()
            };

            if (Simple.HasValue)
            {
                bindRequest.Authentication.Simple = Simple.Value;
            }
            else if (SaslMechanism != null)
            {
                var sasl = new Asn1SaslCredentials
                {
                    Mechanism   = SaslMechanism.LdapString(),
                    Credentials = SaslCredentials
                };
                bindRequest.Authentication.Sasl = sasl;
            }
        }
示例#28
0
        private XmlElement Authenticate(IEnumerable <string> mechanisms, string username, string password, string hostname)
        {
            string        name      = this.SelectMechanism(mechanisms);
            SaslMechanism mechanism = SaslFactory.Create(name);

            mechanism.Properties.Add("Username", username);
            mechanism.Properties.Add("Password", password);
            XmlElement element = Xml.Element("auth", "urn:ietf:params:xml:ns:xmpp-sasl").Attr("mechanism", name).Text(mechanism.HasInitial ? mechanism.GetResponse(string.Empty) : string.Empty);

            this.Send(element);
            while (true)
            {
                XmlElement element2 = this.parser.NextElement(new string[] { "challenge", "success", "failure" });
                if (element2.Name == "failure")
                {
                    throw new SaslException("SASL authentication failed.");
                }
                if ((element2.Name == "success") && mechanism.IsCompleted)
                {
                    break;
                }
                string response = mechanism.GetResponse(element2.InnerText);
                if (element2.Name == "success")
                {
                    if (!(response == string.Empty))
                    {
                        throw new SaslException("Could not verify server's signature.");
                    }
                    break;
                }
                element = Xml.Element("response", "urn:ietf:params:xml:ns:xmpp-sasl").Text(response);
                this.Send(element);
            }
            this.Authenticated = true;
            return(this.InitiateStream(hostname));
        }
示例#29
0
                    /// <summary>
                    /// Sends the message using the specified host on the specified port. Secure SASL Authentication is performed according to the requested mechanism.
                    /// </summary>
                    /// <param name="message">The message to be sent.</param>
                    /// <param name="host">The host to be used.</param>
                    /// <param name="username">The username to be used for authentication.</param>
                    /// <param name="password">The password to be used for authentication.</param>
                    /// <param name="mechanism">SASL Mechanism to be used for authentication.</param>
                    /// <param name="port">The port to be used.</param>
                    /// <example>
                    /// <code>
                    /// C#
                    /// 
                    /// Message message = new Message();
                    /// message.Subject = "Test";
                    /// message.From = new Address("*****@*****.**","John Doe");
                    /// message.To.Add("*****@*****.**","Mike Johns");
                    /// message.BodyText.Text = "Hello this is a test!";
                    /// 
                    /// SmtpClient.Send(message,"mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504);
                    /// 
                    /// VB.NET
                    /// 
                    /// Dim message As New Message
                    /// message.Subject = "Test"
                    /// message.From = New Address("*****@*****.**","John Doe")
                    /// message.To.Add("*****@*****.**","Mike Johns")
                    /// message.BodyText.Text = "Hello this is a test!"
                    /// 
                    /// SmtpClient.Send(message,"mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504)
                    /// 
                    /// JScript.NET
                    /// 
                    /// var message:Message = new Message();
                    /// message.Subject = "Test";
                    /// message.From = new Address("*****@*****.**","John Doe");
                    /// message.To.Add("*****@*****.**","Mike Johns");
                    /// message.BodyText.Text = "Hello this is a test!";
                    /// 
                    /// SmtpClient.Send(message,"mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504);
                    /// </code>
                    /// </example>
                    public static bool Send(Message message, string host, int port, string username, string password, SaslMechanism mechanism)
                    {
                        // Ensure that the mime part tree is built
                        message.CheckBuiltMimePartTree();

                        var smtp = new SmtpClient();
                        smtp.Connect(host,port);
                        smtp.SendEhloHelo();
                        smtp.Authenticate(username, password, mechanism);
                        if(message.From.Email!=string.Empty) smtp.MailFrom(message.From);
                        else smtp.MailFrom(message.Sender);
                        smtp.RcptTo(message.To);
                        smtp.RcptTo(message.Cc);
                        smtp.RcptTo(message.Bcc);
                        smtp.Data(message.ToMimeString());
                        smtp.Disconnect();
                        return true;
                    }
示例#30
0
        /// <summary>
        /// Sends the message using the specified host on the specified port. Secure SASL Authentication is performed according to the requested mechanism.
        /// </summary>
        /// <param name="message">The message to be sent.</param>
        /// <param name="host">The host to be used.</param>
        /// <param name="username">The username to be used for authentication.</param>
        /// <param name="password">The password to be used for authentication.</param>
        /// <param name="mechanism">SASL Mechanism to be used for authentication.</param>
        /// <param name="port">The port to be used.</param>
        /// <example>
        /// <code>
        /// C#
        /// 
        /// Message message = new Message();
        /// message.Subject = "Test";
        /// message.From = new Address("*****@*****.**","John Doe");
        /// message.To.Add("*****@*****.**","Mike Johns");
        /// message.BodyText.Text = "Hello this is a test!";
        /// 
        /// SmtpClient.Send(message,"mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504);
        /// 
        /// VB.NET
        /// 
        /// Dim message As New Message
        /// message.Subject = "Test"
        /// message.From = New Address("*****@*****.**","John Doe")
        /// message.To.Add("*****@*****.**","Mike Johns")
        /// message.BodyText.Text = "Hello this is a test!"
        /// 
        /// SmtpClient.Send(message,"mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504)
        /// 
        /// JScript.NET
        /// 
        /// var message:Message = new Message();
        /// message.Subject = "Test";
        /// message.From = new Address("*****@*****.**","John Doe");
        /// message.To.Add("*****@*****.**","Mike Johns");
        /// message.BodyText.Text = "Hello this is a test!";
        /// 
        /// SmtpClient.Send(message,"mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504);
        /// </code>
        /// </example>
        public bool Send(Message message, string host, int port, string username, string password,
                                SaslMechanism mechanism)
        {
            // Ensure that the mime part tree is built
            message.CheckBuiltMimePartTree();

            ConnectPlain(host, port);
            SendEhloHelo();
            Authenticate(username, password, mechanism);
            if (message.From.Email != string.Empty) MailFrom(message.From);
            else MailFrom(message.Sender);
            RcptTo(message.To);
            RcptTo(message.Cc);
            RcptTo(message.Bcc);
            Data(message.ToMimeString());
            Disconnect();
            return true;
        }
示例#31
0
        public MailAccountData CreateAccount(string name,
            string email,
            string account,
            string password,
            int port,
            string server,
            string smtp_account,
            string smtp_password,
            int smtp_port,
            string smtp_server,
            bool smtp_auth,
            bool imap,
            bool restrict,
            EncryptionType incoming_encryption_type,
            EncryptionType outcoming_encryption_type,
            SaslMechanism auth_type_in,
            SaslMechanism auth_type_smtp)
        {
            string errorText = null;
            var mbox = new MailBox
                {
                    Name = name,
                    EMail = new MailAddress(email),
                    Account = account,
                    Password = password,
                    Port = port,
                    Server = server,
                    SmtpAccount = smtp_account,
                    SmtpPassword = smtp_password,
                    SmtpPort = smtp_port,
                    SmtpServer = smtp_server,
                    SmtpAuth = smtp_auth,
                    Imap = imap,
                    Restrict = restrict,
                    TenantId = TenantId,
                    UserId = Username,
                    BeginDate = restrict ? 
                        DateTime.Now.Subtract(new TimeSpan(MailBox.DefaultMailLimitedTimeDelta)) : 
                        new DateTime(MailBox.DefaultMailBeginTimestamp),
                    IncomingEncryptionType = incoming_encryption_type,
                    OutcomingEncryptionType = outcoming_encryption_type,
                    AuthenticationTypeIn = auth_type_in,
                    AuthenticationTypeSmtp = auth_type_smtp
                };

            try
            {
                MailServerHelper.Test(mbox);
            }
            catch (ImapConnectionException exImap)
            {
                errorText = GetFormattedTextError(exImap, ServerType.Imap, exImap is ImapConnectionTimeoutException);
            }
            catch (Pop3ConnectionException exPop3)
            {
                errorText = GetFormattedTextError(exPop3, ServerType.Pop3, exPop3 is Pop3ConnectionTimeoutException);
            }
            catch (SmtpConnectionException exSmtp)
            {
                errorText = GetFormattedTextError(exSmtp, ServerType.Smtp, exSmtp is SmtpConnectionTimeoutException);
            }
            catch (Exception ex)
            {
                errorText = GetFormattedTextError(ex);
            }

            if(!string.IsNullOrEmpty(errorText))
                throw new Exception(errorText);

            try
            {
                mbox.InServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                        new MailServerSettings
                                                                            {
                                                                                AccountName = mbox.Account,
                                                                                AccountPass = mbox.Password,
                                                                                AuthenticationType =
                                                                                    mbox.AuthenticationTypeIn,
                                                                                EncryptionType =
                                                                                    mbox.IncomingEncryptionType,
                                                                                Port = mbox.Port,
                                                                                Url = mbox.Server
                                                                            },
                                                                        imap ? "imap" : "pop3",
                                                                        AuthorizationServiceType.Unknown);
                mbox.SmtpServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                          new MailServerSettings
                                                                              {
                                                                                  AccountName = mbox.SmtpAccount,
                                                                                  AccountPass = mbox.SmtpPassword,
                                                                                  AuthenticationType =
                                                                                      mbox.AuthenticationTypeSmtp,
                                                                                  EncryptionType =
                                                                                      mbox.OutcomingEncryptionType,
                                                                                  Port = mbox.SmtpPort,
                                                                                  Url = mbox.SmtpServer
                                                                              },
                                                                          "smtp", AuthorizationServiceType.Unknown);

                MailBoxManager.SaveMailBox(mbox);
                var accountInfo = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                               MailBox.AuthProblemType.NoProblems, new SignatureDto(mbox.MailBoxId, TenantId, "", false), 
                                               false, mbox.EMailInFolder, false, false);

                return accountInfo.ToAddressData().FirstOrDefault();
            }
            catch (Exception ex)
            {
                //TODO: change AttachmentsUnknownError to common unknown error text
                errorText = GetFormattedTextError(ex, MailApiResource.AttachmentsUnknownError);
            }

            throw new Exception(errorText);

        }
示例#32
0
 public static IAsyncResult BeginSendCollection(MessageCollection messages, string host, int port, string username, string password, SaslMechanism mechanism, ref SmtpExceptionCollection errors, AsyncCallback callback)
 {
     SmtpClient._delegateSendMessageCollectionStringIntStringStringSaslMechanismSmtpExceptionCollection = SmtpClient.SendCollection;
     return SmtpClient._delegateSendMessageCollectionStringIntStringStringSaslMechanismSmtpExceptionCollection.BeginInvoke(messages, host, port, username, password, mechanism, ref errors, callback, SmtpClient._delegateSendMessageCollectionStringIntStringStringSaslMechanismSmtpExceptionCollection);
 }
示例#33
0
 /// <summary>
 /// Sends the message using the specified host as mail exchange and the specified port.
 /// A simple Login authentication is performed.
 /// </summary>
 /// <param name="host">Host to be used to send the message.</param>
 /// <param name="username">Username to be used for the authentication process.</param>
 /// <param name="password">Password to be used for the authentication process.</param>
 /// <param name="port">Port to be used to connect to the specified host.</param>
 /// <example>
 /// <code>
 /// C#
 /// 
 ///SmtpMessage message = new SmtpMessage();
 ///message.From = new Address("*****@*****.**","John Doe");
 ///message.To.Add("*****@*****.**","Mike Johns");
 ///message.Subject = "hey!";
 ///message.Attachments.Add("C:\\myfile.doc");
 ///message.BodyHtml.Text = "As promised, the requested document.&lt;br />&lt;br />Regards,&lt;br>John.";
 ///message.Send("mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504);
 /// 
 /// VB.NET
 /// 
 ///Dim message As New SmtpMessage
 ///message.From = new Address("*****@*****.**","John Doe")
 ///message.To.Add("*****@*****.**","Mike Johns")
 ///message.Subject = "hey!"
 ///message.Attachments.Add("C:\myfile.doc")
 ///message.BodyHtml.Text = "As promised, the requested document.&lt;br />&lt;br />Regards,&lt;br>John."
 ///message.Send("mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504)
 ///  
 /// JScript.NET
 /// 
 ///var message:SmtpMessage = new SmtpMessage();
 ///message.From = new Address("*****@*****.**","John Doe")
 ///message.To.Add("*****@*****.**","Mike Johns");
 ///message.Subject = "hey!";
 ///message.Attachments.Add("C:\\myfile.doc");
 ///message.BodyHtml.Text = "As promised, the requested document.&lt;br />&lt;br />Regards,&lt;br>John."
 ///message.Send("mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504);
 /// </code>
 /// </example>
 public void Send(string host, int port, string username, string password, SaslMechanism mechanism)
 {
     //CheckBuiltMimePartTree();
     SmtpClient.Send(this, host, port, username, password, mechanism);
 }
示例#34
0
 public IAsyncResult BeginSend(string host, int port, string username, string password, SaslMechanism mechanism, AsyncCallback callback)
 {
     return SmtpClient.BeginSend(this, host, port, username, password, mechanism, callback);
 }
示例#35
0
        private static async Task Run_Producer <TKey, TValue>(string brokerList, string topicName,
                                                              SecurityProtocol securityProtocol, SaslMechanism saslMechanism, string saslUsername, string saslPassword,
                                                              string schemaRegistryUrl, string basicAuthUserInfo, Message <Ignore, TValue> consumerMessage)
            where TKey : class, IMessage <TKey>, new()
            where TValue : class, IMessage <TValue>, new()
        {
            var message = CreateMessage <TKey, TValue>(consumerMessage.Value);
            var config  = new ProducerConfig
            {
                BootstrapServers = brokerList,
            };
            var schemaRegistryConfig = new SchemaRegistryConfig
            {
                Url = schemaRegistryUrl,
            };

            using (var schemaRegistry = new CachedSchemaRegistryClient(schemaRegistryConfig))
                using (var producer = new ProducerBuilder <TKey, TValue>(config)
                                      .SetKeySerializer(new ProtobufSerializer <TKey>(schemaRegistry))
                                      .SetValueSerializer(new ProtobufSerializer <TValue>(schemaRegistry))
                                      .Build())
                {
                    try
                    {
                        var deliveryReport = await producer.ProduceAsync(topicName, message);

                        Console.WriteLine($"delivered to: {deliveryReport.TopicPartitionOffset} for producer: {producer.Name}");
                    }
                    catch (ProduceException <int, TValue> e)
                    {
                        Console.WriteLine($"failed to deliver message: {e.Message} [{e.Error.Code}]");
                    }
                }
        }
示例#36
0
		/// <summary>
		/// Authenticates the given user and SASL mechanism.
		/// </summary>
		/// <param name="username">Username to log in.</param>
		/// <param name="password">Password.</param>
		/// <param name="mechanism">SASL Mechanism to be used.</param>
		/// <returns>True if authentication succeded.</returns>
		/// <example>
		/// <code>
		/// C#
		/// 
		/// NntpClient nttp = new NntpClient();
		/// nntp.Connect("news.myhost.com");
		/// nntp.Authenticate("admin","password",SaslMechanism.CramMd5);
		/// 
		/// VB.NET
		/// 
		/// Dim nttp as New NntpClient()
		/// nntp.Connect("news.myhost.com") 
		/// nntp.Authenticate("admin","password",SaslMechanism.CramMd5)
		/// 
		/// JScript.NET
		/// 
		/// var nntp:NntpClient = new NntpClient();
		/// nntp.Connect("news.myhost.com");
		/// nntp.Authenticate("admin","password",SaslMechanism.CramMd5);
		/// </code>
		/// </example>
		public string Authenticate(string username, string password, SaslMechanism mechanism)
		{
			switch(mechanism)
			{
				case ActiveUp.Net.Mail.SaslMechanism.CramMd5 : return this._CramMd5(username,password);
                case ActiveUp.Net.Mail.SaslMechanism.Login: throw new ActiveUp.Net.Mail.NntpException("LOGIN mechanism cannot be used for NNTP authentication. If your server accepts it, please perform the commands yourself.");
			}
            return "";
		}
 private static string ConvertFromSaslMechanism(SaslMechanism saslType)
 {
     switch (saslType)
     {
         case SaslMechanism.Login:
             return "";
         case SaslMechanism.None:
             return "none";
         case SaslMechanism.CramMd5:
             return "password-encrypted";
         default:
             throw new ArgumentException("Unknown mail server SaslMechanism: " + Enum.GetName(typeof(SaslMechanism), saslType));
     }
 }
        public MailBox CreateAccount(string name,
            string email,
            string account,
            string password,
            int port,
            string server,
            string smtp_account,
            string smtp_password,
            int smtp_port,
            string smtp_server,
            bool smtp_auth,
            bool imap,
            bool restrict,
            EncryptionType incoming_encryption_type,
            EncryptionType outcoming_encryption_type,
            SaslMechanism auth_type_in,
            SaslMechanism auth_type_smtp)
        {

            string error_text;
            var mbox = new MailBox
                {
                    Name = name,
                    EMail = new MailAddress(email),
                    Account = account,
                    Password = password,
                    Port = port,
                    Server = server,
                    SmtpAccount = smtp_account,
                    SmtpPassword = smtp_password,
                    SmtpPort = smtp_port,
                    SmtpServer = smtp_server,
                    SmtpAuth = smtp_auth,
                    Imap = imap,
                    Restrict = restrict,
                    TenantId = TenantId,
                    UserId = Username,
                    BeginDate = restrict ? 
                        DateTime.Now.Subtract(new TimeSpan(MailBox.DefaultMailLimitedTimeDelta)) : 
                        new DateTime(MailBox.DefaultMailBeginTimestamp),
                    IncomingEncryptionType = incoming_encryption_type,
                    OutcomingEncryptionType = outcoming_encryption_type,
                    AuthenticationTypeIn = auth_type_in,
                    AuthenticationTypeSmtp = auth_type_smtp
                };

            try
            {
                MailServerHelper.Test(mbox);

                mbox.InServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                        new MailServerSettings
                                        {
                                            AccountName = mbox.Account,
                                            AccountPass = mbox.Password,
                                            AuthenticationType = mbox.AuthenticationTypeIn,
                                            EncryptionType = mbox.IncomingEncryptionType,
                                            Port = mbox.Port,
                                            Url = mbox.Server
                                        },
                                        imap ? "imap" : "pop3", AuthorizationServiceType.Unknown);
                mbox.SmtpServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                        new MailServerSettings
                                        {
                                        AccountName = mbox.SmtpAccount,
                                        AccountPass = mbox.SmtpPassword,
                                        AuthenticationType = mbox.AuthenticationTypeSmtp,
                                        EncryptionType = mbox.OutcomingEncryptionType,
                                        Port = mbox.SmtpPort,
                                        Url = mbox.SmtpServer
                                        },
                                        "smtp", AuthorizationServiceType.Unknown);

                MailBoxManager.SaveMailBox(mbox);
                return mbox;
            }
            catch (ImapConnectionException ex_imap)
            {
                error_text = GetFormattedTextError(ex_imap, ServerType.Imap, ex_imap is ImapConnectionTimeoutException);
            }
            catch (Pop3ConnectionException ex_pop3)
            {
                error_text = GetFormattedTextError(ex_pop3, ServerType.Pop3, ex_pop3 is Pop3ConnectionTimeoutException);
            }
            catch (SmtpConnectionException ex_smtp)
            {
                error_text = GetFormattedTextError(ex_smtp, ServerType.Smtp, ex_smtp is SmtpConnectionTimeoutException);
            }
            catch (Exception ex)
            {
                error_text = GetFormattedTextError(ex, imap ? ServerType.Imap : ServerType.Pop3);
            }

            throw new Exception(error_text);

        }
示例#39
0
        public MailAccountData UpdateAccount(string name,
            string email,
            string account,
            string password,
            int port,
            string server,
            string smtp_account,
            string smtp_password,
            int smtp_port,
            string smtp_server,
            bool smtp_auth,
            bool restrict,
            EncryptionType incoming_encryption_type,
            EncryptionType outcoming_encryption_type,
            SaslMechanism auth_type_in,
            SaslMechanism auth_type_smtp)
        {
            if (string.IsNullOrEmpty(email))
                throw new ArgumentException();

            var mbox = MailBoxManager.GetMailBox(TenantId, Username, new MailAddress(email));

            if (null == mbox)
                throw new ArgumentException("Mailbox with specified email doesn't exist.");

            if (mbox.IsTeamlab)
                throw new ArgumentException("Mailbox with specified email can't be updated");

            if (string.IsNullOrEmpty(password))
                password = mbox.Password;
            if (string.IsNullOrEmpty(smtp_password))
                smtp_password = mbox.SmtpPassword;

            string errorText;

            mbox.Account = account;
            mbox.Name = name;
            mbox.Password = password;
            mbox.SmtpAccount = smtp_account;
            mbox.SmtpPassword = smtp_password;
            mbox.Port = port;
            mbox.Server = server;
            mbox.SmtpPort = smtp_port;
            mbox.SmtpServer = smtp_server;
            mbox.SmtpAuth = smtp_auth;
            mbox.Restrict = restrict;
            mbox.BeginDate = mbox.Restrict ? 
                DateTime.Now.Subtract(new TimeSpan(mbox.MailLimitedTimeDelta)) : 
                mbox.MailBeginTimestamp;
            mbox.IncomingEncryptionType = incoming_encryption_type;
            mbox.OutcomingEncryptionType = outcoming_encryption_type;
            mbox.AuthenticationTypeIn = auth_type_in;
            mbox.AuthenticationTypeSmtp = auth_type_smtp;

            mbox.InServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                        new MailServerSettings
                        {
                            AccountName = mbox.Account,
                            AccountPass = mbox.Password,
                            AuthenticationType = mbox.AuthenticationTypeIn,
                            EncryptionType = mbox.IncomingEncryptionType,
                            Port = mbox.Port,
                            Url = mbox.Server
                        },
                        mbox.Imap ? "imap" : "pop3", AuthorizationServiceType.Unknown);
            mbox.SmtpServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                    new MailServerSettings
                                    {
                                        AccountName = mbox.SmtpAccount,
                                        AccountPass = mbox.SmtpPassword,
                                        AuthenticationType = mbox.AuthenticationTypeSmtp,
                                        EncryptionType = mbox.OutcomingEncryptionType,
                                        Port = mbox.SmtpPort,
                                        Url = mbox.SmtpServer
                                    },
                                    "smtp", AuthorizationServiceType.Unknown);

            try
            {
                if (!string.IsNullOrEmpty(mbox.RefreshToken) || MailServerHelper.Test(mbox))
                {
                    if (!MailBoxManager.SaveMailBox(mbox))
                        throw new Exception("Failed to_addresses update account");
                }

                var accountInfo = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                               MailBox.AuthProblemType.NoProblems, new SignatureDto(mbox.MailBoxId, TenantId, "", false),
                                               false, mbox.EMailInFolder, false, false);

                return accountInfo.ToAddressData().FirstOrDefault();
            }
            catch (ImapConnectionException exImap)
            {
                errorText = GetFormattedTextError(exImap, ServerType.Imap, exImap is ImapConnectionTimeoutException);
            }
            catch (Pop3ConnectionException exPop3)
            {
                errorText = GetFormattedTextError(exPop3, ServerType.Pop3, exPop3 is Pop3ConnectionTimeoutException);
            }
            catch (SmtpConnectionException exSmtp)
            {
                errorText = GetFormattedTextError(exSmtp, ServerType.Smtp, exSmtp is SmtpConnectionTimeoutException);
            }
            catch (Exception ex)
            {
                errorText = GetFormattedTextError(ex);
            }

            throw new Exception(errorText);
        }
示例#40
0
文件: WcfPerftest.cs 项目: ncdc/qpid
 public Options()
 {
     this.broker = "127.0.0.1";
     this.port = 5672;
     this.messageCount = 500000;
     this.messageSize = 1024;
     this.type = ClientType.InteropDemo;  // default: once as pub and once as sub
     this.baseName = "qpid-perftest";
     this.pubTxSize = 0;
     this.subTxSize = 0;
     this.durable = false;
     this.ssl = false;
     this.username = null;
     this.password = null;
     this.saslMechanism = SaslMechanism.None;
 }
示例#41
0
文件: WcfPerftest.cs 项目: ncdc/qpid
        public void Parse(string[] args)
        {
            int argCount = args.Length;
            int current = 0;
            bool typeSelected = false;

            while (current < argCount)
            {
                string arg = args[current];
                if (arg == "--publish")
                {
                    if (typeSelected)
                        throw new ArgumentException("too many roles");

                    this.type = ClientType.Publisher;
                    typeSelected = true;
                }
                else if (arg == "--subscribe")
                {
                    if (typeSelected)
                        throw new ArgumentException("too many roles");

                    this.type = ClientType.Subscriber;
                    typeSelected = true;
                }
                else if (arg == "--size")
                {
                    arg = args[++current];
                    int i = int.Parse(arg);
                    if (i > 0)
                    {
                        this.messageSize = i;
                    }
                }
                else if (arg == "--count")
                {
                    arg = args[++current];
                    UInt64 i = UInt64.Parse(arg);
                    if (i > 0)
                    {
                        this.messageCount = i;
                    }
                }
                else if (arg == "--broker")
                {
                    this.broker = args[++current];
                }
                else if (arg == "--port")
                {
                    arg = args[++current];
                    int i = int.Parse(arg);
                    if (i > 0)
                    {
                        this.port = i;
                    }
                }
                else if (arg == "--base-name")
                {
                    this.baseName = args[++current];
                }

                else if (arg == "--tx")
                {
                    arg = args[++current];
                    int i = int.Parse(arg);
                    if (i > 0)
                    {
                        this.subTxSize = i;
                        this.pubTxSize = i;
                    }
                }

                else if (arg == "--durable")
                {
                    arg = args[++current];
                    if (arg.Equals("yes"))
                    {
                        this.durable = true;
                    }
                }

                else if (arg == "--protocol")
                {
                    arg = args[++current];
                    if (arg.Equals("ssl"))
                    {
                        this.ssl = true;
                    }
                }

                else if (arg == "--username")
                {
                    this.username = args[++current];
                }

                else if (arg == "--password")
                {
                    this.password = args[++current];
                }

                else if (arg == "--mechanism")
                {
                    arg = args[++current];
                    if (arg.Equals("PLAIN", StringComparison.OrdinalIgnoreCase))
                    {
                        this.saslMechanism = SaslMechanism.Plain;
                    }
                }

                else
                {
                    throw new ArgumentException(String.Format("unknown argument \"{0}\"", arg));
                }

                current++;
            }

            if (this.saslMechanism == SaslMechanism.Plain)
            {
                // use guest/guest as defaults if neither is specified
                if ((this.username == null) && (this.password == null))
                {
                    this.username = "******";
                    this.password = "******";
                }
                else
                {
                    if (this.username == null)
                    {
                        this.username = "";
                    }
                    if (this.password == null)
                    {
                        this.password = "";
                    }
                }
            }
        }
示例#42
0
 private void SendMessageWithAuthentication(string username, string password,
                                                   SaslMechanism mechanism, Message message)
 {
     Authenticate(username, password, mechanism);
     if (message.From.Email != string.Empty) MailFrom(message.From);
     else MailFrom(message.Sender);
     RcptTo(message.To);
     RcptTo(message.Cc);
     RcptTo(message.Bcc);
     Data(message.ToMimeString());
     Disconnect();
 }
示例#43
0
 private static void SendMessageWithAuthentication(SmtpClient smtp, string username, string password,
                                                   SaslMechanism mechanism, Message message)
 {
     smtp.Authenticate(username, password, mechanism);
     if (message.From.Email != string.Empty) smtp.MailFrom(message.From);
     else smtp.MailFrom(message.Sender);
     smtp.RcptTo(message.To);
     smtp.RcptTo(message.Cc);
     smtp.RcptTo(message.Bcc);
     smtp.Data(message.ToMimeString());
     smtp.Disconnect();
 }
示例#44
0
 /// <summary>
 /// Authenticates using the given SASL mechanism.
 /// </summary>
 /// <param name="username">Username to authenticate as.</param>
 /// <param name="password">Password.</param>
 /// <param name="mechanism">SASL mechanism to be used.</param>
 /// <returns>The server's response.</returns>
 /// <example>
 /// <code>
 /// C#
 /// 
 /// Pop3Client pop = new Pop3Client();
 /// pop.Connect("mail.myhost.com");
 /// pop.Authenticate("user","pass",SASLMechanism.CramMd5);
 /// pop.Disconnect();
 /// 
 /// VB.NET
 /// 
 /// Dim pop As New Pop3Client
 /// pop.Connect("mail.myhost.com")
 /// pop.Authenticate("user","pass",SASLMechanism.CramMd5)
 /// pop.Disconnect()
 /// 
 /// JScript.NET
 /// 
 /// var pop:Pop3Client = new Pop3Client();
 /// pop.Connect("mail.myhost.com");
 /// pop.Authenticate("user","pass",SASLMechanism.CramMd5);
 /// pop.Disconnect();
 /// </code>
 /// </example>
 public override string Authenticate(string username, string password, SaslMechanism mechanism)
 {
     switch (mechanism)
     {
         case ActiveUp.Net.Mail.SaslMechanism.CramMd5:
             return this._CramMd5(username, password);
         case ActiveUp.Net.Mail.SaslMechanism.Login:
             return this._Login(username, password);
     }
     return string.Empty;
 }
示例#45
0
                    public static bool SendSsl(Message message, string host, int port, string username, string password, SaslMechanism mechanism)
                    {
                        // Ensure that the mime part tree is built
                        message.CheckBuiltMimePartTree();

                        ActiveUp.Net.Mail.SmtpClient smtp = new ActiveUp.Net.Mail.SmtpClient();
                        smtp.ConnectSsl(host, port);
                        smtp.SendEhloHelo();
                        SendMessageWithAuthentication(smtp, username, password, mechanism, message);
                        return true;
                    }
示例#46
0
 public override IAsyncResult BeginAuthenticate(string username, string password, SaslMechanism mechanism,
                                                AsyncCallback callback)
 {
     this._delegateAuthenticate = this.Authenticate;
     return this._delegateAuthenticate.BeginInvoke(username, password, mechanism, callback, null);
 }
示例#47
0
        public bool SendSsl(Message message, string host, int port, string username, string password,
                                   SaslMechanism mechanism, EncryptionType enc_type)
        {
            // Ensure that the mime part tree is built
            message.CheckBuiltMimePartTree();

            switch (enc_type)
            {
                case EncryptionType.SSL:
                    ConnectSsl(host, port);
                    break;
                case EncryptionType.StartTLS:
                    ConnectPlain(host, port);
                    break;
                default:
                    throw new ArgumentException("Incompatible EncriptionType with SendSSL: " + enc_type);
            }

            SendEhloHelo();

            if (enc_type == EncryptionType.StartTLS)
            {
                StartTLS(host);
            }

            SendMessageWithAuthentication(username, password, mechanism, message);
            return true;
        }
示例#48
0
        public void SendSsl(string host, int port, string username, string password, SaslMechanism mechanism)
        {
            //CheckBuiltMimePartTree();
#if !PocketPC
            SmtpClient.SendSsl(this, host, port, username, password, mechanism);
#else
            SmtpClient.Send(this, host, port, username, password, mechanism);
#endif
        }
示例#49
0
                    /// <summary>
		            /// Sends the message using the specified host and port after authentication.
		            /// </summary>
		            /// <param name="messages">The message collection to be sent.</param>
		            /// <param name="host">Host to be used to send the message.</param>
		            /// <param name="username">Username to be used for the authentication process.</param>
		            /// <param name="password">Password to be used for the authentication process.</param>
		            /// <param name="mechanism">SASL mechanism to be used.</param>
		            /// <param name="port">Port to be used to connect to the specified host.</param>
		            /// <param name="errors">Reference to SmtpException object collection where errors occuring during the process will be stored.</param>
		            /// <returns>Amount of messages successfully sent.</returns>
                    public static int SendCollection(MessageCollection messages, string host, int port, string username, string password, SaslMechanism mechanism, ref SmtpExceptionCollection errors)
		            {
			            ActiveUp.Net.Mail.SmtpClient smtp = new ActiveUp.Net.Mail.SmtpClient();
			            smtp.Connect(host,port);
			            try
			            {
				            smtp.Ehlo(System.Net.Dns.GetHostName());
			            }
			            catch
			            {
				            smtp.Helo(System.Net.Dns.GetHostName());
			            }
			            smtp.Authenticate(username,password,mechanism);
			            int sent = 0;
			            foreach(Message message in messages)
			            {
				            try
				            {
                                // Ensure that the mime part tree is built
                                message.CheckBuiltMimePartTree();

					            if(message.From.Email!=string.Empty) smtp.MailFrom(message.From);
					            else smtp.MailFrom(message.Sender);
					            smtp.RcptTo(message.To);
					            smtp.RcptTo(message.Cc);
					            smtp.RcptTo(message.Bcc);
					            smtp.Data(message.ToMimeString());
					            sent++;
				            }
				            catch(ActiveUp.Net.Mail.SmtpException ex) { errors.Add(ex); }
			            }
			            smtp.Disconnect();
			            return sent;
                    }
 public abstract IAsyncResult BeginAuthenticate(string username, string password, SaslMechanism mechanism, AsyncCallback callback);
 internal bool TryGetMechanism(Symbol name, out SaslMechanism mechanism)
 {
     return this.mechanisms.TryGetValue(name, out mechanism);
 }
示例#52
0
        public static async Task Run_Consumer <TKey, TValue>(string brokerList, List <string> consumerTopics, string producerTopic,
                                                             SecurityProtocol securityProtocol, SaslMechanism saslMechanism, string saslUsername, string saslPassword,
                                                             string schemaRegistryUrl, string basicAuthUserInfo, CancellationToken cancellationToken)
            where TKey : class, IMessage <TKey>, new()
            where TValue : class, IMessage <TValue>, new()
        {
            var config = new ConsumerConfig
            {
                BootstrapServers     = brokerList,
                GroupId              = "csharp-consumer",
                EnableAutoCommit     = false,
                StatisticsIntervalMs = 5000,
                SessionTimeoutMs     = 6000,
                AutoOffsetReset      = AutoOffsetReset.Earliest,
                EnablePartitionEof   = true,
            };

            const int commitPeriod = 5;

            using (var consumer = new ConsumerBuilder <Ignore, TValue>(config)
                                  .SetErrorHandler((_, e) => Console.WriteLine($"Error: {e.Reason}"))
                                  .SetPartitionsAssignedHandler((c, partitions) =>
            {
                Console.WriteLine($"Assigned partitions: [{string.Join(", ", partitions)}]\n");
            })
                                  .SetPartitionsRevokedHandler((c, partitions) =>
            {
                Console.WriteLine($"Revoking assignment: [{string.Join(", ", partitions)}]");
            })
                                  // Set value Protobuf deserializer
                                  .SetValueDeserializer(new ProtobufDeserializer <TValue>().AsSyncOverAsync())
                                  .Build())
            {
                consumer.Subscribe(consumerTopics);

                try
                {
                    while (true)
                    {
                        try
                        {
                            var consumeResult = consumer.Consume(cancellationToken);

                            if (consumeResult.IsPartitionEOF)
                            {
                                Console.WriteLine(
                                    $"Reached end of topic {consumeResult.Topic}, partition {consumeResult.Partition}, offset {consumeResult.Offset}.");

                                continue;
                            }

                            PrintConsumeResult(consumeResult);

                            if (consumeResult.Offset % commitPeriod == 0)
                            {
                                try
                                {
                                    consumer.Commit(consumeResult);
                                }
                                catch (KafkaException e)
                                {
                                    Console.WriteLine($"Commit error: {e.Error.Reason}");
                                }
                            }

                            await Run_Producer <TKey, TValue>(brokerList, producerTopic, securityProtocol, saslMechanism,
                                                              saslUsername, saslPassword, schemaRegistryUrl, basicAuthUserInfo, consumeResult.Message);
                        }
                        catch (ConsumeException e)
                        {
                            Console.WriteLine($"Consume error: {e.Error.Reason}");
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("Closing consumer.");
                    consumer.Close();
                }
            }
        }
示例#53
0
		            /// <summary>
		            /// Sends the message using the specified host on the specified port. Secure SASL Authentication is performed according to the requested mechanism.
		            /// </summary>
		            /// <param name="message">The message to be sent.</param>
		            /// <param name="host">The host to be used.</param>
		            /// <param name="username">The username to be used for authentication.</param>
		            /// <param name="password">The password to be used for authentication.</param>
		            /// <param name="mechanism">SASL Mechanism to be used for authentication.</param>
		            /// <param name="port">The port to be used.</param>
		            /// <example>
		            /// <code>
		            /// C#
		            /// 
		            /// Message message = new Message();
		            /// message.Subject = "Test";
		            /// message.From = new Address("*****@*****.**","John Doe");
		            /// message.To.Add("*****@*****.**","Mike Johns");
		            /// message.BodyText.Text = "Hello this is a test!";
		            /// 
		            /// SmtpClient.Send(message,"mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504);
		            /// 
		            /// VB.NET
		            /// 
		            /// Dim message As New Message
		            /// message.Subject = "Test"
		            /// message.From = New Address("*****@*****.**","John Doe")
		            /// message.To.Add("*****@*****.**","Mike Johns")
		            /// message.BodyText.Text = "Hello this is a test!"
		            /// 
		            /// SmtpClient.Send(message,"mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504)
		            /// 
		            /// JScript.NET
		            /// 
		            /// var message:Message = new Message();
		            /// message.Subject = "Test";
		            /// message.From = new Address("*****@*****.**","John Doe");
		            /// message.To.Add("*****@*****.**","Mike Johns");
		            /// message.BodyText.Text = "Hello this is a test!";
		            /// 
		            /// SmtpClient.Send(message,"mail.myhost.com","jdoe1234","tanstaaf",SaslMechanism.CramMd5,8504);
		            /// </code>
		            /// </example>
		            public static bool Send(Message message, string host, int port, string username, string password, SaslMechanism mechanism)
		            {
                        // Ensure that the mime part tree is built
                        message.CheckBuiltMimePartTree();

			            ActiveUp.Net.Mail.SmtpClient smtp = new ActiveUp.Net.Mail.SmtpClient();
			            smtp.Connect(host,port);
			            try
			            {
				            smtp.Ehlo(System.Net.Dns.GetHostName());
			            }
			            catch
			            {
				            smtp.Helo(System.Net.Dns.GetHostName());
			            }
			            smtp.Authenticate(username,password,mechanism);
			            if(message.From.Email!=string.Empty) smtp.MailFrom(message.From);
			            else smtp.MailFrom(message.Sender);
			            smtp.RcptTo(message.To);
			            smtp.RcptTo(message.Cc);
			            smtp.RcptTo(message.Bcc);
			            smtp.Data(message.ToMimeString());
			            smtp.Disconnect();
                        return true;
		            }
示例#54
0
 public static IAsyncResult BeginSend(Message message, string host, int port, string username, string password, SaslMechanism mechanism, AsyncCallback callback)
 {
     SmtpClient._delegateSendMessageStringIntStringStringSaslMechanism = SmtpClient.Send;
     return SmtpClient._delegateSendMessageStringIntStringStringSaslMechanism.BeginInvoke(message, host, port, username, password, mechanism, callback, SmtpClient._delegateSendMessageStringIntStringStringSaslMechanism);
 }
示例#55
0
 public static IAsyncResult BeginSendCollection(MessageCollection messages, string host, string username, string password, SaslMechanism mechanism, AsyncCallback callback)
 {
     SmtpClient._delegateSendMessageCollectionStringStringStringSaslMechanism = SmtpClient.SendCollection;
     return SmtpClient._delegateSendMessageCollectionStringStringStringSaslMechanism.BeginInvoke(messages, host, username, password, mechanism, callback, SmtpClient._delegateSendMessageCollectionStringStringStringSaslMechanism);
 }
        public MailBox UpdateAccount(string name,
            string email,
            string account,
            string password,
            int port,
            string server,
            string smtp_account,
            string smtp_password,
            int smtp_port,
            string smtp_server,
            bool smtp_auth,
            bool imap,
            bool restrict,
            EncryptionType incoming_encryption_type,
            EncryptionType outcoming_encryption_type,
            SaslMechanism auth_type_in,
            SaslMechanism auth_type_smtp)
        {
            if (string.IsNullOrEmpty(email))
                throw new ArgumentException();

            var mbox = mailBoxManager.GetMailBox(TenantId, Username, new MailAddress(email));

            if (null == mbox)
                throw new ArgumentException("Mailbox with specified email doesn't exist.");

            if (string.IsNullOrEmpty(password))
                password = mbox.Password;
            if (string.IsNullOrEmpty(smtp_password))
                smtp_password = mbox.SmtpPassword;

            string error_text;

            mbox.Account = account;
            mbox.Name = name;
            mbox.Password = password;
            mbox.SmtpAccount = smtp_account;
            mbox.SmtpPassword = smtp_password;
            mbox.Port = port;
            mbox.Server = server;
            mbox.SmtpPort = smtp_port;
            mbox.SmtpServer = smtp_server;
            mbox.SmtpAuth = smtp_auth;
            mbox.Imap = imap;
            mbox.Restrict = restrict;
            mbox.BeginDate = mbox.Restrict ? 
                DateTime.Now.Subtract(new TimeSpan(mbox.MailLimitedTimeDelta)) : 
                mbox.MailBeginTimestamp;
            mbox.IncomingEncryptionType = incoming_encryption_type;
            mbox.OutcomingEncryptionType = outcoming_encryption_type;
            mbox.AuthenticationTypeIn = auth_type_in;
            mbox.AuthenticationTypeSmtp = auth_type_smtp;

            mbox.InServerId = mailBoxManager.SaveMailServerSettings(mbox.EMail,
                        new MailServerSettings
                        {
                            AccountName = mbox.Account,
                            AccountPass = mbox.Password,
                            AuthenticationType = mbox.AuthenticationTypeIn,
                            EncryptionType = mbox.IncomingEncryptionType,
                            Port = mbox.Port,
                            Url = mbox.Server
                        },
                        imap ? "imap" : "pop3", AuthorizationServiceType.Unknown);
            mbox.SmtpServerId = mailBoxManager.SaveMailServerSettings(mbox.EMail,
                                    new MailServerSettings
                                    {
                                        AccountName = mbox.SmtpAccount,
                                        AccountPass = mbox.SmtpPassword,
                                        AuthenticationType = mbox.AuthenticationTypeSmtp,
                                        EncryptionType = mbox.OutcomingEncryptionType,
                                        Port = mbox.SmtpPort,
                                        Url = mbox.SmtpServer
                                    },
                                    "smtp", AuthorizationServiceType.Unknown);

            try
            {
                if (!string.IsNullOrEmpty(mbox.RefreshToken) || mbox.Test())
                {
                    if (!mailBoxManager.SaveMailBox(mbox))
                        throw new Exception("Failed to_addresses update account");
                }

                return mbox;
            }
            catch (ImapConnectionException ex_imap)
            {
                error_text = GetFormattedTextError(ex_imap, ServerType.Imap);
            }
            catch (Pop3ConnectionException ex_pop3)
            {
                error_text = GetFormattedTextError(ex_pop3, ServerType.Pop3);
            }
            catch (SmtpConnectionException ex_smtp)
            {
                error_text = GetFormattedTextError(ex_smtp, ServerType.Smtp);
            }
            catch (Exception ex)
            {
                error_text = GetFormattedTextError(ex, imap ? ServerType.Imap : ServerType.Pop3);
            }

            throw new Exception(error_text);
        }
示例#57
0
        public bool SendSsl(Message message, string host, int port, string username, string password,
                                   SaslMechanism mechanism)
        {
            // Ensure that the mime part tree is built
            message.CheckBuiltMimePartTree();

            ConnectSsl(host, port);
            SendEhloHelo();
            SendMessageWithAuthentication(username, password, mechanism, message);
            return true;
        }