public void SmtpResponse()
        {
            SmtpResponse smtpResponse = new SmtpResponse(StandardSmtpResponseCode.ExceededStorageAllocation, "Blah");
            SmtpServerException e = new SmtpServerException(smtpResponse);

            Assert.Same(smtpResponse, e.SmtpResponse);
        }
        public SmtpResponseException(SmtpResponse response, string source) : base(new LocalizedString(response.ToString()))
        {
            MessageAction action;

            switch (response.SmtpResponseType)
            {
            case SmtpResponseType.Success:
                if (string.IsNullOrEmpty(source))
                {
                    throw new ArgumentException("Source must be provided for success smtp response type", "source");
                }
                action = MessageAction.LogProcess;
                goto IL_6E;

            case SmtpResponseType.TransientError:
                action = MessageAction.Retry;
                goto IL_6E;

            case SmtpResponseType.PermanentError:
                action = MessageAction.NDR;
                goto IL_6E;
            }
            throw new ArgumentException("The smtp response type is not supported.", "response");
IL_6E:
            this.status = new MessageStatus(action, response, this, false, source);
        }
Esempio n. 3
0
        /*
         * /// <summary>
         * /// Return true if this is among the supported AUTH
         * /// types.
         * /// </summary>
         * /// <param name="authtypes"></param>
         * /// <returns></returns>
         * public bool IsSupported(SmtpAuthType[] authtypes)
         * {
         *      log.Debug("CHECKING SUPPORTED TYPES");
         *      for (int i=0; i<authtypes.Length; i++)
         *      {
         *              log.Debug("CHECKING IF "+authtypes[i]+"="+SmtpAuthType.Login);
         *              if (authtypes[i]==SmtpAuthType.Login)
         *              {
         *                      return true;
         *              }
         *      }
         *      return false;
         * }
         */

        /// <summary>
        /// Return the 235 response code if valid, otherwise
        /// return the error.
        /// </summary>
        /// <param name="smtpProxy"></param>
        /// <param name="supportedAuthTypes">the supported auth types</param>
        /// <returns></returns>
        public SmtpResponse Negotiate(ISmtpProxy smtpProxy, String[] supportedAuthTypes)
        {
            SmtpResponse response = smtpProxy.Auth("login");

            //log.Debug("RESPONSE WAS "+response.ResponseCode+" "+response.Message);
            if (response.ResponseCode != 334)
            {
                return(response);
            }
            Base64Encoder encoder = Base64Encoder.GetInstance();

            response = smtpProxy.SendString(encoder.EncodeString(this.UserName, this._charEncoding));
            if (response.ResponseCode != 334)
            {
                return(response);
            }
            response = smtpProxy.SendString(encoder.EncodeString(this.Password, this._charEncoding));
            if (response.ResponseCode != 334)
            {
                // here it's an error
                return(response);
            }
            else
            {
                // here it's ok.
                return(response);
            }
        }
        private static SmtpResponse GetExceptionSmtpResponse(IMessageConverter converter, Exception exception, string exceptionName, bool isPermanent)
        {
            SmtpResponse smtpResponse = SmtpResponse.Empty;

            if (exceptionName != null)
            {
                if (!(exceptionName == "MapiExceptionRpcServerTooBusy"))
                {
                    if (!(exceptionName == "MapiExceptionSessionLimit"))
                    {
                        if (exceptionName == "MapiExceptionNotEnoughMemory")
                        {
                            smtpResponse = AckReason.MailboxServerNotEnoughMemory;
                        }
                    }
                    else
                    {
                        smtpResponse = AckReason.MailboxMapiSessionLimit;
                    }
                }
                else
                {
                    smtpResponse = AckReason.MailboxServerTooBusy;
                }
            }
            return(StorageExceptionHandler.GetExceptionSmtpResponse(converter, exception, isPermanent, smtpResponse.StatusCode, smtpResponse.EnhancedStatusCode, smtpResponse.StatusText[0], true));
        }
Esempio n. 5
0
        public async Task ProcessesMultiLineResponseCorrectly()
        {
            string responseLn1 = "250-smtp.com at your service, [123.456.789.101]";
            string responseLn2 = "250-SIZE 35882577";
            string responseLn3 = "250 STARTTLS";

            IStreamReader reader = A.Fake <IStreamReader>();

            A.CallTo(() => reader.ReadLineAsync()).ReturnsNextFromSequence(
                Task.FromResult(responseLn1),
                Task.FromResult(responseLn2),
                Task.FromResult(responseLn3));

            SmtpResponse smtpResponse = await _smtpDeserializer.Deserialize(reader);

            Assert.That(smtpResponse.Responses.Count, Is.EqualTo(3));

            Assert.That(smtpResponse.Responses[0].ResponseCode, Is.EqualTo(ResponseCode.Ok));
            Assert.That(smtpResponse.Responses[0].Value, Is.EqualTo("smtp.com at your service, [123.456.789.101]"));

            Assert.That(smtpResponse.Responses[1].ResponseCode, Is.EqualTo(ResponseCode.Ok));
            Assert.That(smtpResponse.Responses[1].Value, Is.EqualTo("SIZE 35882577"));

            Assert.That(smtpResponse.Responses[2].ResponseCode, Is.EqualTo(ResponseCode.Ok));
            Assert.That(smtpResponse.Responses[2].Value, Is.EqualTo("STARTTLS"));
        }
        private static MessageStatus GetMessageStatus(IMessageConverter converter, ConversionFailedException exception)
        {
            StorageExceptionHandler.LogException(converter, exception);
            SmtpResponse exceptionSmtpResponse = StorageExceptionHandler.GetExceptionSmtpResponse(converter, exception, true, "554", (ConversionFailureReason.ExceedsLimit == exception.ConversionFailureReason) ? "5.3.4" : "5.6.0", StorageExceptionHandler.GetReasonDescription(exception.ConversionFailureReason), true);

            return(new MessageStatus(MessageAction.NDR, exceptionSmtpResponse, exception, true));
        }
        private static MessageStatus GetMessageStatus(IMessageConverter converter, DataValidationException invalidDataException)
        {
            StorageExceptionHandler.LogException(converter, invalidDataException);
            SmtpResponse exceptionSmtpResponse = StorageExceptionHandler.GetExceptionSmtpResponse(converter, invalidDataException, true, converter.IsOutbound ? AckReason.OutboundInvalidDirectoryData : AckReason.InboundInvalidDirectoryData);

            return(new MessageStatus(MessageAction.NDR, exceptionSmtpResponse, invalidDataException));
        }
Esempio n. 8
0
        public async Task <bool> TrySendSingleMailAsync(
            IMailReference mail,
            StreamWriter writer,
            StreamReader reader,
            CancellationToken token)
        {
            _log.Information($"Sending mail {mail.Id}");
            IMailReadReference readMail = await _queue.OpenReadAsync(mail, token);

            _log.Information($"Sender: {readMail.Sender}, Recipients: {string.Join(",", readMail.Recipients)}");
            SmtpResponse response = await ExecuteRemoteCommandAsync(writer, reader, $"MAIL FROM:<{readMail.Sender}>");

            if (response.Code != SmtpReplyCode.Okay)
            {
                _log.Warning("Failed MAIL FROM, aborting");
                return(false);
            }

            foreach (string recipient in readMail.Recipients)
            {
                response = await ExecuteRemoteCommandAsync(writer, reader, $"RCPT TO:<{recipient}>");

                if (response.Code != SmtpReplyCode.Okay)
                {
                    _log.Warning("Failed RCPT TO, aborting");
                    return(false);
                }
            }

            response = await ExecuteRemoteCommandAsync(writer, reader, "DATA");

            if (response.Code != SmtpReplyCode.StartMail)
            {
                _log.Warning("Failed DATA, aborting");
                return(false);
            }

            using (var mailReader = new StreamReader(readMail.BodyStream))
            {
                string line = null;
                while (await mailReader.TryReadLineAsync(l => line = l, token))
                {
                    await writer.WriteLineAsync(line);
                }
            }

            await writer.WriteLineAsync(".");

            response = await ReadResponseAsync(reader);

            if (response.Code != SmtpReplyCode.Okay)
            {
                _log.Warning("Failed RCPT TO, aborting");
                return(false);
            }

            await _queue.DeleteAsync(mail);

            return(true);
        }
Esempio n. 9
0
        public MessageStatus CreateStatus(Exception exception, Exception exceptionAssociatedWithHandler, IMessageConverter converter, TimeSpan fastRetryInterval, TimeSpan quarantineRetryInterval)
        {
            SmtpResponse  exceptionSmtpResponse = StorageExceptionHandler.GetExceptionSmtpResponse(converter, exception, this.Category == Category.Permanent, this.GetEffectiveStatusCode(), this.GetEffectiveEnhancedStatusCode(exceptionAssociatedWithHandler), this.GetEffectivePrimaryStatusText(exceptionAssociatedWithHandler), this.IncludeDiagnosticStatusText);
            MessageStatus messageStatus         = new MessageStatus(this.Action, exceptionSmtpResponse, exception, this.AppliesToAllRecipients);

            if (this.SpecifiedRetryInterval != null)
            {
                messageStatus.RetryInterval = new TimeSpan?(this.SpecifiedRetryInterval.Value);
            }
            else if (this.RetryInterval != RetryInterval.None)
            {
                if (this.RetryInterval == RetryInterval.QuarantinedRetry)
                {
                    messageStatus.RetryInterval = new TimeSpan?(quarantineRetryInterval);
                }
                else
                {
                    messageStatus.RetryInterval = new TimeSpan?(fastRetryInterval);
                }
            }
            if (this.CustomizeStatusCallback != null)
            {
                this.CustomizeStatusCallback(exceptionAssociatedWithHandler, converter, messageStatus);
            }
            return(messageStatus);
        }
Esempio n. 10
0
 void ThrowIfError(SmtpResponse status)
 {
     if (IsError(status))
     {
         throw new SmtpException(status.StatusCode, status.Description);
     }
 }
        private static MessageStatus GetMessageStatus(IMessageConverter converter, ADTransientException unavailableException)
        {
            StorageExceptionHandler.LogException(converter, unavailableException);
            SmtpResponse exceptionSmtpResponse = StorageExceptionHandler.GetExceptionSmtpResponse(converter, unavailableException, false);

            return(new MessageStatus(MessageAction.Retry, exceptionSmtpResponse, unavailableException));
        }
        public void SendNDRForFailedSubmission(IReadOnlyMailItem ndrMailItem, SmtpResponse ndrReason, DsnMailOutHandlerDelegate dsnMailOutHandler)
        {
            List <DsnRecipientInfo> list = new List <DsnRecipientInfo>();

            list.Add(DsnGenerator.CreateDsnRecipientInfo(null, (string)ndrMailItem.From, null, ndrReason));
            Components.DsnGenerator.GenerateNDRForInvalidAddresses(false, ndrMailItem, list, dsnMailOutHandler);
        }
Esempio n. 13
0
        private static bool CheckResponse(Socket socket, SmtpResponse response)
        {
            int byteCount = socket.Receive(m_Buffer, 0, m_Buffer.Length, SocketFlags.None);

            if (byteCount <= 2)
            {
                Shutdown(socket);
                return(false);
            }

            int resp = (int)response;

            byte dig1 = (byte)('0' + ((resp / 100) % 10));
            byte dig2 = (byte)('0' + ((resp / 10) % 10));
            byte dig3 = (byte)('0' + ((resp / 1) % 10));

            bool valid = (m_Buffer[0] == dig1 && m_Buffer[1] == dig2 && m_Buffer[2] == dig3);

            if (!valid)
            {
                Shutdown(socket);
            }

            return(valid);
        }
Esempio n. 14
0
        public void SmtpResponse()
        {
            SmtpResponse        smtpResponse = new SmtpResponse(StandardSmtpResponseCode.ExceededStorageAllocation, "Blah");
            SmtpServerException e            = new SmtpServerException(smtpResponse);

            Assert.AreSame(smtpResponse, e.SmtpResponse);
        }
Esempio n. 15
0
        public static string FlattenStatusText(SmtpResponse response)
        {
            if (response.StatusText == null || response.StatusText.Length == 0)
            {
                return(string.Empty);
            }
            if (response.StatusText.Length == 1)
            {
                return(response.StatusText[0]);
            }
            IEnumerator <string> enumerator = ((IEnumerable <string>)response.StatusText).GetEnumerator();

            if (!enumerator.MoveNext())
            {
                return(string.Empty);
            }
            StringBuilder stringBuilder = new StringBuilder(enumerator.Current);

            while (enumerator.MoveNext())
            {
                stringBuilder.Append("; ");
                stringBuilder.Append(enumerator.Current);
            }
            return(stringBuilder.ToString());
        }
 public override void AckMailItem(AckStatus ackStatus, SmtpResponse smtpResponse, AckDetails details, TimeSpan?retryInterval, MessageTrackingSource source, string messageTrackingSourceContext, LatencyComponent deliveryComponent, string remoteMta, bool shadowed, string primaryServer, bool reportEndToEndLatencies)
 {
     if (this.recipientsPending != 0 && ackStatus == AckStatus.Success)
     {
         throw new InvalidOperationException("Cannot ack message successfully until all pending recipients have been acked");
     }
     if (ackStatus == AckStatus.Pending)
     {
         this.recipientsPending      = this.readyRecipients.Count;
         this.recipientEnumerator    = this.mailItem.Recipients.GetEnumerator();
         this.recipientEnumeratorAck = this.mailItem.Recipients.GetEnumerator();
         this.result = null;
     }
     else
     {
         if (this.result == null)
         {
             this.result = new SmtpMailItemResult();
         }
         this.result.MessageResponse    = new AckStatusAndResponse(ackStatus, smtpResponse);
         this.mailItemSentForProcessing = true;
     }
     if (this.notificationHandler != null)
     {
         this.notificationHandler.AckMessage(ackStatus, smtpResponse);
     }
 }
Esempio n. 17
0
        /// <summary>
        /// Execute the command handler against the specified session context.
        /// </summary>
        /// <param name="context">The session context to execute the command handler against.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task which asynchronously performs the execution.</returns>
        public virtual async Task ExecuteAsync(ISmtpSessionContext context, CancellationToken cancellationToken)
        {
            var retryCount = _maxRetries;

            while (retryCount-- > 0 && context.IsQuitRequested == false && cancellationToken.IsCancellationRequested == false)
            {
                var text = await context.Text.ReadLineAsync(cancellationToken).ConfigureAwait(false);

                SmtpCommand  command;
                SmtpResponse errorResponse;
                if (TryAccept(context, text, out command, out errorResponse) == false)
                {
                    var response = new SmtpResponse(errorResponse.ReplyCode, $"{errorResponse.Message}, {retryCount} retry(ies) remaining.");

                    await context.Text.ReplyAsync(response, cancellationToken);

                    continue;
                }

                // the command was a normal command so we can reset the retry count
                retryCount = _maxRetries;

                await ExecuteAsync(command, context, cancellationToken).ConfigureAwait(false);
            }
        }
Esempio n. 18
0
        private void Authenticate(Socket socket)
        {
            if (this.userName.Length > 0 || this.password.Length > 0)
            {
                SmtpResponse smtpResponse = SendData(socket, string.Format(CultureInfo.InvariantCulture, "EHLO {0}\r\n", Dns.GetHostName()), SmtpReplyCode.GenericSuccess);

                if (smtpResponse.Message.IndexOf("AUTH=LOGIN") >= 0)
                {
                    SendData(socket, "AUTH LOGIN\r\n", SmtpReplyCode.AuthRequest);

                    byte[] bytes = Encoding.UTF8.GetBytes(this.userName);
                    SendData(socket, Convert.ToBase64String(bytes) + Environment.NewLine, SmtpReplyCode.AuthRequest);

                    bytes = Encoding.UTF8.GetBytes(this.password);
                    SendData(socket, Convert.ToBase64String(bytes) + Environment.NewLine, SmtpReplyCode.AuthSuccess);
                }
                else
                {
                    throw new SmtpAuthenticationException(string.Format("Authentication to SMTP-server failed '{0}'. Code: {1} Message: {2}", this.host, smtpResponse.ReplyCode, smtpResponse.Message));
                }
            }
            else
            {
                SendData(socket, string.Format(CultureInfo.InvariantCulture, "HELO {0}\r\n", Dns.GetHostName()), SmtpReplyCode.GenericSuccess);
            }
        }
        public override void AckRecipient(AckStatus ackStatus, SmtpResponse smtpResponse)
        {
            TraceHelper.SmtpSendTracer.TracePass <string, string>(TraceHelper.MessageProbeActivityId, (long)this.GetHashCode(), "InboundProxyNextHopConnection.AckRecipient. Ackstatus  = {0}. SmtpResponse = {1}", ackStatus.ToString(), smtpResponse.ToString());
            if (!this.recipientEnumeratorAck.MoveNext() || this.recipientsPending <= 0)
            {
                throw new InvalidOperationException("AckRecipient called but no recipients left to ack");
            }
            this.recipientsPending--;
            MailRecipient recipient = this.recipientEnumeratorAck.Current;

            switch (ackStatus)
            {
            case AckStatus.Pending:
            case AckStatus.Success:
            case AckStatus.Retry:
            case AckStatus.Fail:
                if (this.result == null)
                {
                    this.result = new SmtpMailItemResult();
                }
                if (this.result.RecipientResponses == null)
                {
                    this.result.RecipientResponses = new Dictionary <MailRecipient, AckStatusAndResponse>();
                }
                this.result.RecipientResponses.Add(recipient, new AckStatusAndResponse(ackStatus, smtpResponse));
                if (this.notificationHandler != null)
                {
                    this.notificationHandler.AckRecipient(ackStatus, smtpResponse, recipient);
                }
                return;

            default:
                throw new InvalidOperationException(string.Format("AckRecipient with status: {0} is invalid", ackStatus));
            }
        }
        public void Clone_should_copy_ReasonText()
        {
            var response = new SmtpResponse(250, "Text");
            var cloned   = response.Clone();

            Assert.Equal(response.ResponseText, cloned.ResponseText);
        }
        public void Clone_should_copy_ReasonCode()
        {
            var response = new SmtpResponse(250, "");
            var cloned   = response.Clone();

            Assert.Equal(response.ResponseCode, cloned.ResponseCode);
        }
Esempio n. 22
0
 void CheckStatus(SmtpResponse status, int i)
 {
     if (((int)status.StatusCode) != i)
     {
         throw new SmtpException(status.StatusCode, status.Description);
     }
 }
Esempio n. 23
0
        private SmtpResponse Read()
        {
            byte [] buffer   = new byte [512];
            int     position = 0;
            bool    lastLine = false;

            do
            {
                CheckCancellation();

                int readLength = stream.Read(buffer, position, buffer.Length - position);
                if (readLength > 0)
                {
                    int available = position + readLength - 1;
                    if (available > 4 && (buffer [available] == '\n' || buffer [available] == '\r'))
                    {
                        for (int index = available - 3; ; index--)
                        {
                            if (index < 0 || buffer [index] == '\n' || buffer [index] == '\r')
                            {
                                lastLine = buffer [index + 4] == ' ';
                                break;
                            }
                        }
                    }

                    // move position
                    position += readLength;

                    // check if buffer is full
                    if (position == buffer.Length)
                    {
                        byte [] newBuffer = new byte [buffer.Length * 2];
                        Array.Copy(buffer, 0, newBuffer, 0, buffer.Length);
                        buffer = newBuffer;
                    }
                }
                else
                {
                    break;
                }
            } while (!lastLine);

            if (position > 0)
            {
                Encoding encoding = new ASCIIEncoding();

                string line = encoding.GetString(buffer, 0, position - 1);

                // parse the line to the lastResponse object
                SmtpResponse response = SmtpResponse.Parse(line);

                return(response);
            }
            else
            {
                throw new System.IO.IOException("Connection closed");
            }
        }
 public SmtpResponseException(SmtpResponse response, MessageAction action) : base(new LocalizedString(response.ToString()))
 {
     if (action == MessageAction.Throw)
     {
         throw new ArgumentException("MessageAction.Throw is not supported.", "action");
     }
     this.status = new MessageStatus(action, response, this);
 }
Esempio n. 25
0
 internal MessageStatus(MessageAction action, SmtpResponse smtpResponse, Exception exception, bool forAllRecipients, string source)
 {
     this.action           = action;
     this.smtpResponse     = smtpResponse;
     this.exception        = exception;
     this.forAllRecipients = forAllRecipients;
     this.source           = source;
 }
        public void Equals_is_false_Additional_different_in_other_response()
        {
            var response1 = new SmtpResponse(250, "", new[] { "line" });
            var response2 = new SmtpResponse(250, "", new[] { "different line" });

            Assert.False(response1.Equals(response2));
            Assert.False(response1.Equals((object)response2));
        }
Esempio n. 27
0
        public void SmtpMultiLineTest()
        {
            var expected = "250-This is a\r\n250 Multi-line response\r\n";
            var result   = new SmtpResponse(ToStream(expected));

            Assert.AreEqual(SmtpStatusCode.Ok, result.Status);
            Assert.AreEqual(expected, result.Message);
        }
Esempio n. 28
0
        public void SmtpSingleLineTest()
        {
            var expected = "220 Single-line response\r\n";
            var result   = new SmtpResponse(ToStream(expected));

            Assert.AreEqual(SmtpStatusCode.ServiceReady, result.Status);
            Assert.AreEqual(expected, result.Message);
        }
        public void Clone_should_deep_copy_Additional()
        {
            var response = new SmtpResponse(250, "", new[] { "additional" });

            var cloned = response.Clone();
            Assert.NotSame(response.AdditionalLines, cloned.AdditionalLines);
            Assert.Equal(response.AdditionalLines, cloned.AdditionalLines);
        }
        public void Equals_is_false_ResponseText_doesnt_match()
        {
            var response1 = new SmtpResponse(250, "text");
            var response2 = new SmtpResponse(250, "different text");

            Assert.False(response1.Equals(response2));
            Assert.False(response1.Equals((object)response2));
            Assert.NotEqual(response1.GetHashCode(), response2.GetHashCode());
        }
        public void Clone_should_deep_copy_Additional()
        {
            var response = new SmtpResponse(250, "", new[] { "additional" });

            var cloned = response.Clone();

            Assert.NotSame(response.AdditionalLines, cloned.AdditionalLines);
            Assert.Equal(response.AdditionalLines, cloned.AdditionalLines);
        }
        public void Equals_is_true_when_everything_matches()
        {
            var response1 = new SmtpResponse(250, "same", new[] { "line" });
            var response2 = new SmtpResponse(250, "same", new[] { "line" });

            Assert.True(response1.Equals(response2));
            Assert.True(response1.Equals((object)response2));
            Assert.Equal(response1.GetHashCode(), response2.GetHashCode());
        }
Esempio n. 33
0
 public void ToString_MultiLineMessage()
 {
     SmtpResponse r = new SmtpResponse(200, "Multi line message line 1\r\n" +
     "Multi line message line 2\r\n" +
     "Multi line message line 3");
     Assert.Equal("200-Multi line message line 1\r\n" +
     "200-Multi line message line 2\r\n" +
     "200 Multi line message line 3\r\n", r.ToString());
 }
        public void Equals_is_false_ResponseCode_doesnt_match()
        {
            var response1 = new SmtpResponse(250, "");
            var response2 = new SmtpResponse(251, "");

            Assert.False(response1.Equals(response2));
            Assert.False(response1.Equals((object)response2));
            Assert.NotEqual(response1.GetHashCode(), response2.GetHashCode());
        }
        public void CloneAndChange_with_ResponseText_should_change_response_text()
        {
            var response = new SmtpResponse(250, "old text", new[] { "additional" });
            var cloned = response.CloneAndChange("new text");

            Assert.Equal("new text", cloned.ResponseText);
            
            var clonedBack = cloned.CloneAndChange("old text");
            Assert.Equal(response, clonedBack);
        }
        private SmtpResponse VerifyEhlo()
        {
            var smtpCapabilities = _getSmtpCapabilities.GetCapabilities().ToList();

            if (!smtpCapabilities.Any())
                return SmtpResponses.OK;

            var additionalLines = smtpCapabilities.Skip(1).Select(capability => "250-" + capability).ToList();

            var response = new SmtpResponse(250, smtpCapabilities.First().ToString(), additionalLines);
            return response;
        }
        public void RunCommand(string command, SmtpResponse expectedSmtpResponse)
        {
            _writer.WriteLine(command);

            var line = _reader.ReadLine();

            if (line == null)
                throw new InvalidOperationException("Stream has unexpectedly closed");

            if (line != expectedSmtpResponse.ToString())
                throw new InvalidOperationException(String.Format("After command '{0}' received '{1}' but expected '{2}'", command, line, expectedSmtpResponse));
        }
        private static bool IsLineTooLong(byte[] lineBuf, out SmtpResponse smtpResponse)
        {
            if (lineBuf.Length > 2040)
            {
                smtpResponse = SmtpResponses.LineTooLong;
                return true;
            }

            smtpResponse = SmtpResponses.None;
            return false;
        }
        private static SmtpSessionInfoResponder CreateParseResponderWithMockedIRespondToSmtpData(SmtpResponse testResponse)
        {
            var respondToSmtpData = MockIRespondToSmtpDataToReturnResponse(testResponse);

            var factory = new DefaultSmtpResponderFactory<ISmtpServerConfiguration>(new SmtpServerConfiguration()) { DataResponder = respondToSmtpData };
            var parseResponder = RecipientMailFromIdentifiedParseResponder(factory);
            return parseResponder;
        }
Esempio n. 40
0
        // I was seeing my SMTP server hang waiting for a response to the QUIT, so I added
        // this timeout. Pass -1 to wait forever. Timeout is in milliseconds.
        private bool Check_Response(Socket s, SmtpResponse response_expected, int timeout)
        {
            string sResponse;
            int response;
            byte[] bytes = new byte[1024];

            int start = Environment.TickCount;
            while (s.Available == 0)
            {
                System.Threading.Thread.Sleep(101);

                if (timeout != -1)
                {
                    if ((Environment.TickCount - start) > timeout)
                    {
                        // We timed out
                        return false;
                    }
                }
            }

            s.Receive(bytes, 0, s.Available, SocketFlags.None);
            sResponse = Encoding.ASCII.GetString(bytes);
            if (sw != null)
                sw.WriteLine(">>{0}", sResponse);
            response = Convert.ToInt32(sResponse.Substring(0, 3));
            if (response != (int)response_expected)
                return false;
            return true;
        }
Esempio n. 41
0
        private static void LogResponse(SmtpResponse response)
        {
            var logger = MailServerLogger.Instance;
            if (logger.LogLevel < MailServerLogLevel.Debug) return;

            var logMessage = new StringBuilder();
            foreach (var additionalLine in response.AdditionalLines)
            {
                logMessage.AppendLine(">>> " + additionalLine);
            }

            logMessage.AppendLine(">>> " + response.ResponseCode + " " + response.ResponseText);
            logger.Debug(logMessage.ToString());
        }
 public void Equals_is_true_when_everything_matches()
 {
     var response1 = new SmtpResponse(250, "same", new[] { "line" });
     var response2 = new SmtpResponse(250, "same", new[] { "line" });
     
     Assert.True(response1.Equals(response2));
     Assert.True(response1.Equals((object)response2));
     Assert.Equal(response1.GetHashCode(), response2.GetHashCode());
 }
 private static IRespondToSmtpRecipientTo MockIRespondToRecipientToToReturnResponse(SmtpResponse testResponse)
 {
     var mockedInterface = new Mock<IRespondToSmtpRecipientTo>();
     mockedInterface
         .Setup(x => x.VerifyRecipientTo(It.IsAny<SmtpSessionInfo>(), It.IsAny<MailAddressWithParameters>()))
         .Returns<SmtpSessionInfo, MailAddressWithParameters>((sessionInfo, mailAddressWithParameters) => testResponse);
     return mockedInterface.Object;
 }
Esempio n. 44
0
		private bool IsError (SmtpResponse status)
		{
			return ((int) status.StatusCode) >= 400;
		}
Esempio n. 45
0
		void ThrowIfError (SmtpResponse status)
		{
			if (IsError (status))
				throw new SmtpException (status.StatusCode, status.Description);
		}
Esempio n. 46
0
        private static async Task SendResponseAsync(SmtpConnection connection, SmtpResponse response)
        {
            LogResponse(response);

            try
            {
                foreach (var additional in response.AdditionalLines)
                    await connection.WriteLineAsyncAndFireEvents(additional);

                await connection.WriteLineAsyncAndFireEvents(response.ResponseCode + " " + response.ResponseText);

            } catch(Exception ex)
            {
                MailServerLogger.Instance.Error(ex);
            }
        }
 public void Clone_should_copy_ReasonText()
 {
     var response = new SmtpResponse(250, "Text");
     var cloned = response.Clone();
     Assert.Equal(response.ResponseText, cloned.ResponseText);
 }
 public void Clone_should_copy_ReasonCode()
 {
     var response = new SmtpResponse(250, "");
     var cloned = response.Clone();
     Assert.Equal(response.ResponseCode, cloned.ResponseCode);
 }
 public void AdditionalLines_should_never_be_null()
 {
     var response = new SmtpResponse(250, "");
     Assert.NotNull(response.AdditionalLines);
 }
 private bool ProcessRawLineHasResponse(string line, out SmtpResponse smtpResponse)
 {
     smtpResponse = ProcessRawLine(line);
     return (smtpResponse != SmtpResponses.None);
 }
 private static IRespondToSmtpData MockIRespondToSmtpDataToReturnResponse(SmtpResponse testResponse)
 {
     var mockedInterface = new Mock<IRespondToSmtpData>();
     mockedInterface
         .Setup(x => x.DataLine(It.IsAny<SmtpSessionInfo>(), It.IsAny<byte[]>()))
         .Returns<SmtpSessionInfo, byte[]>((sessionInfo, line) => testResponse);
     mockedInterface
         .Setup(x => x.DataStart(It.IsAny<SmtpSessionInfo>()))
         .Returns<SmtpSessionInfo>(sessionInfo => testResponse);
     mockedInterface
         .Setup(x => x.DataEnd(It.IsAny<SmtpSessionInfo>()))
         .Returns<SmtpSessionInfo>(sessionInfo => testResponse);
     return mockedInterface.Object;
 }
 private static IRespondToSmtpIdentification MockIRespondToSmtpIdentificationToReturnResponse(SmtpResponse testResponse)
 {
     var mockedInterface = new Mock<IRespondToSmtpIdentification>();
     mockedInterface
         .Setup(x => x.VerifyIdentification(It.IsAny<SmtpSessionInfo>(), It.IsAny<SmtpIdentification>()))
         .Returns<SmtpSessionInfo, SmtpIdentification>((sessionInfo, identification) => testResponse);
     return mockedInterface.Object;
 }
 private static IRespondToSmtpVerify MockIRespondToVerifyToReturnResponse(SmtpResponse testResponse)
 {
     var mockedInterface = new Mock<IRespondToSmtpVerify>();
     mockedInterface
         .Setup(x => x.Verify(It.IsAny<SmtpSessionInfo>(), It.IsAny<string>()))
         .Returns<SmtpSessionInfo, string>((sessionInfo, args) => testResponse);
     return mockedInterface.Object;
 }
Esempio n. 54
0
		/// <summary> 
		/// Execute the SMTP request returning a response. This method models the state transition table for the SMTP server.
		/// </summary>
		/// <returns>Reponse to the request</returns>
		public virtual SmtpResponse Execute()
		{
			SmtpResponse response = null;
			if (action.Stateless)
			{
				if (SmtpActionType.EXPN == action || SmtpActionType.VRFY == action)
				{
					response = new SmtpResponse(252, "Not supported", this.state);
				}
				else if (SmtpActionType.HELP == action)
				{
					response = new SmtpResponse(211, "No help available", this.state);
				}
				else if (SmtpActionType.NOOP == action)
				{
					response = new SmtpResponse(250, "OK", this.state);
				}
				else if (SmtpActionType.VRFY == action)
				{
					response = new SmtpResponse(252, "Not supported", this.state);
				}
				else if (SmtpActionType.RSET == action)
				{
					response = new SmtpResponse(250, "OK", SmtpState.GREET);
				}
				else
				{
					response = new SmtpResponse(500, "Command not recognized", this.state);
				}
			}
			else
			{
				// Stateful commands
				if (SmtpActionType.CONNECT == action)
				{
					if (SmtpState.CONNECT == state)
					{
						response = new SmtpResponse(220, "localhost nDumbster SMTP service ready", SmtpState.GREET);
					}
					else
					{
						response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
					}
				}
				else if (SmtpActionType.EHLO == action)
				{
					if (SmtpState.GREET == state)
					{
						response = new SmtpResponse(250, "OK", SmtpState.MAIL);
					}
					else
					{
						response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
					}
				}
				else if (SmtpActionType.MAIL == action)
				{
					if (SmtpState.MAIL == state || SmtpState.QUIT == state)
					{
						response = new SmtpResponse(250, "OK", SmtpState.RCPT);
					}
					else
					{
						response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
					}
				}
				else if (SmtpActionType.RCPT == action)
				{
					if (SmtpState.RCPT == state)
					{
						response = new SmtpResponse(250, "OK", this.state);
					}
					else
					{
						response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
					}
				}
				else if (SmtpActionType.DATA == action)
				{
					if (SmtpState.RCPT == state)
					{
						response = new SmtpResponse(354, "Start mail input; end with <CRLF>.<CRLF>", SmtpState.DATA_HDR);
					}
					else
					{
						response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
					}
				}
				else if (SmtpActionType.UNRECOG == action)
				{
					if (SmtpState.DATA_HDR == state || SmtpState.DATA_BODY == state)
					{
						response = new SmtpResponse(-1, "", this.state);
					}
					else
					{
						response = new SmtpResponse(500, "Command not recognized", this.state);
					}
				}
				else if (SmtpActionType.DATA_END == action)
				{
					if (SmtpState.DATA_HDR == state || SmtpState.DATA_BODY == state)
					{
						response = new SmtpResponse(250, "OK", SmtpState.QUIT);
					}
					else
					{
						response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
					}
				}
				else if (SmtpActionType.BLANK_LINE == action)
				{
					if (SmtpState.DATA_HDR == state)
					{
						response = new SmtpResponse(-1, "", SmtpState.DATA_BODY);
					}
					else if (SmtpState.DATA_BODY == state)
					{
						response = new SmtpResponse(-1, "", this.state);
					}
					else
					{
						response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
					}
				}
				else if (SmtpActionType.QUIT == action)
				{
					if (SmtpState.QUIT == state)
					{
						response = new SmtpResponse(221, "localhost nDumbster service closing transmission channel", SmtpState.CONNECT);
					}
					else
					{
						response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
					}
				}
				else
				{
					response = new SmtpResponse(500, "Command not recognized", this.state);
				}
			}
			return response;
		}
Esempio n. 55
0
		void CheckStatus (SmtpResponse status, int i)
		{
			if (((int) status.StatusCode) != i)
				throw new SmtpException (status.StatusCode, status.Description);
		}
Esempio n. 56
0
        private static async Task SendResponseAsync(SmtpConnection connection, SmtpResponse response)
        {
            LogResponse(response);

            foreach (var additional in response.AdditionalLines)
                await connection.WriteLineAsyncAndFireEvents(additional);

            await connection.WriteLineAsyncAndFireEvents(response.ResponseCode + " " + response.ResponseText);
        }
Esempio n. 57
0
			public static SmtpResponse Parse (string line) {
				SmtpResponse response = new SmtpResponse ();

				if (line.Length < 4)
					throw new SmtpException ("Response is to short " +
								 line.Length + ".");

				if ((line [3] != ' ') && (line [3] != '-'))
					throw new SmtpException ("Response format is wrong.(" +
								 line + ")");

				// parse the response code
				response.StatusCode = (SmtpStatusCode) Int32.Parse (line.Substring (0, 3));

				// set the raw response
				response.Description = line;

				return response;
			}
        public void Equals_is_false_Additional_missing_in_other_response()
        {
            var response1 = new SmtpResponse(250, "", new[] { "line" });
            var response2 = new SmtpResponse(250, "");

            Assert.False(response1.Equals(response2));
            Assert.False(response1.Equals((object)response2));
        }
        private static SmtpSessionInfoResponder CreateParseResponderWithMockedIRespondToVerify(SmtpResponse testResponse)
        {
            var respondToVerify = MockIRespondToVerifyToReturnResponse(testResponse);

            var factory = new DefaultSmtpResponderFactory<ISmtpServerConfiguration>(new SmtpServerConfiguration()) { VerifyResponder = respondToVerify };
            var parseResponder = MailFromIdentifiedParseResponder(factory);
            return parseResponder;
        }
        private static SmtpSessionInfoResponder CreateParseResponderWithMockedIRespondToSmtpIdentification(SmtpResponse testResponse)
        {
            var respondToSmtpIdentification = MockIRespondToSmtpIdentificationToReturnResponse(testResponse);

            var factory = new DefaultSmtpResponderFactory<ISmtpServerConfiguration>(new SmtpServerConfiguration()) { IdentificationResponder = respondToSmtpIdentification };
            var parseResponder = DefaultResponder(factory);
            return parseResponder;
        }