private int DeliverMailItem(MbxTransportMailItem mailItem, ulong sessionId)
        {
            int result = 0;

            TraceHelper.MessageProbeActivityId = mailItem.SystemProbeId;
            TraceHelper.StoreDriverDeliveryTracer.TracePass <string>(TraceHelper.MessageProbeActivityId, 0L, "Delivery: Processing started for MessageId {0}.", mailItem.InternetMessageId ?? "NULL");
            TimeSpan?retryInterval;

            using (MailItemDeliver mailItemDeliver = new MailItemDeliver(mailItem, sessionId))
            {
                try
                {
                    StoreDriverDeliveryDiagnostics.HangDetector[sessionId] = mailItemDeliver;
                    mailItemDeliver.DeliverToRecipients();
                }
                finally
                {
                    StoreDriverDeliveryDiagnostics.HangDetector.Remove(sessionId);
                }
                result        = mailItemDeliver.DeliveredRecipients;
                retryInterval = mailItemDeliver.RetryInterval;
            }
            AckDetails ackDetails = new AckDetails(StoreDriverDelivery.localHostName);

            ackDetails.AddEventData("MailboxDatabaseName", mailItem.DatabaseName);
            mailItem.AckMailItem(AckStatus.Success, SmtpResponse.NoopOk, ackDetails, retryInterval, StoreDriverDelivery.GenerateSessionSourceContext(sessionId, mailItem.SessionStartTime));
            TraceHelper.StoreDriverDeliveryTracer.TracePass <string>(TraceHelper.MessageProbeActivityId, 0L, "Delivery: Processing complete for MessageID {0}.", mailItem.InternetMessageId ?? "NULL");
            return(result);
        }
 private static void AckMailItemOnRetryException(AckStatus status, MbxTransportMailItem mailItem, RetryException exception, string sourceContext, ulong sessionId, ulong bytesDelivered, ulong recipientCount)
 {
     StoreDriverDeliveryDiagnostics.Diag.TraceDebug <RetryException, AckStatus>(0L, "StoreDriverDelivery encountered an exception {0}. Message Action: {1}.", exception, status);
     if (exception.MessageStatus.Action == MessageAction.RetryQueue)
     {
         mailItem.MessageLevelAction = MessageAction.RetryQueue;
     }
     mailItem.AckMailItem(status, exception.MessageStatus.Response, new AckDetails(StoreDriverDelivery.localHostName), exception.MessageStatus.RetryInterval, sourceContext);
     StoreDriverDelivery.LogRetryExceptionInConnectionLog(exception, mailItem, sourceContext, sessionId, bytesDelivered, recipientCount);
 }
        private bool ResolveMdbParameters(MbxTransportMailItem mbxItem, ulong sessionId)
        {
            bool         flag         = false;
            ProxyAddress proxyAddress = ProxyAddress.Parse("SMTP:" + mbxItem.Recipients[0].ToString());
            Result <TransportMiniRecipient> result;

            if (mbxItem.ADRecipientCache.TryGetValue(proxyAddress, out result) && result.Data != null)
            {
                if (result.Data.Database != null)
                {
                    mbxItem.DatabaseGuid = result.Data.Database.ObjectGuid;
                    mbxItem.DatabaseName = result.Data.Database.Name;
                    flag = true;
                }
                else if (result.Data.RecipientTypeDetails == RecipientTypeDetails.PublicFolder)
                {
                    ADObjectId adobjectId = null;
                    if (mbxItem.Recipients[0].ExtendedProperties.TryGetValue <ADObjectId>("Microsoft.Exchange.Transport.DirectoryData.Database", out adobjectId) && adobjectId != null)
                    {
                        mbxItem.DatabaseGuid = adobjectId.ObjectGuid;
                        mbxItem.DatabaseName = adobjectId.Name;
                        flag = true;
                    }
                }
            }
            if (flag)
            {
                Guid databaseGuid = mbxItem.DatabaseGuid;
                if (mbxItem.DatabaseGuid == Guid.Empty)
                {
                    flag = false;
                    StoreDriverDeliveryDiagnostics.Diag.TraceWarning <long>(0L, "MDB parameters were found but were null or empty for item {0}.", mbxItem.RecordId);
                }
            }
            if (!flag)
            {
                mbxItem.AckMailItem(AckStatus.Fail, AckReason.MissingMdbProperties, null, null, StoreDriverDelivery.GenerateSessionSourceContext(sessionId, mbxItem.SessionStartTime));
                StoreDriverDeliveryDiagnostics.Diag.TraceWarning <long>(0L, "Failed to get MDB parameters for item {0}.", mbxItem.RecordId);
            }
            return(flag);
        }
 public MbxMailItemWrapper(MbxTransportMailItem mbxMailItem)
 {
     this.mailItem   = mbxMailItem;
     this.recipients = new ReadOnlyMailRecipientCollectionWrapper(this.mailItem.GetRecipients(), mbxMailItem);
 }
        public void Submit(MessageTrackingSource messageTrackingSource, MemorySubmissionItem.OnConvertedToTransportMailItemDelegate transportMailItemHandler, MbxTransportMailItem relatedMailItem)
        {
            TransportMailItem transportMailItem;

            if (relatedMailItem == null)
            {
                transportMailItem = TransportMailItem.NewMailItem(this.organizationId, LatencyComponent.StoreDriverSubmit, MailDirectionality.Originating, default(Guid));
            }
            else
            {
                transportMailItem = TransportMailItem.NewSideEffectMailItem(relatedMailItem, this.organizationId, LatencyComponent.StoreDriverSubmit, MailDirectionality.Originating, relatedMailItem.ExternalOrganizationId);
            }
            base.CopyContentTo(transportMailItem);
            base.DecorateMessage(transportMailItem);
            base.ApplySecurityAttributesTo(transportMailItem);
            if (relatedMailItem != null)
            {
                transportMailItem.PrioritizationReason = relatedMailItem.PrioritizationReason;
                transportMailItem.Priority             = relatedMailItem.Priority;
            }
            SubmissionItemUtils.CopySenderTo(this, transportMailItem);
            List <string> invalidRecipients = null;
            List <string> list = null;

            SubmissionItemUtils.CopyRecipientsTo(this, transportMailItem, null, ref invalidRecipients, ref list);
            ClassificationUtils.PromoteStoreClassifications(transportMailItem.RootPart.Headers);
            SubmissionItemUtils.PatchQuarantineSender(transportMailItem, base.QuarantineOriginalSender);
            bool flag = transportMailItem.Recipients.Count > 0;

            if (relatedMailItem != null)
            {
                MimeInternalHelpers.CopyHeaderBetweenList(relatedMailItem.RootPart.Headers, transportMailItem.RootPart.Headers, "X-MS-Exchange-Moderation-Loop");
            }
            bool flag2 = transportMailItemHandler(transportMailItem, flag);

            if (flag && flag2)
            {
                MsgTrackReceiveInfo msgTrackInfo = new MsgTrackReceiveInfo(StoreDriverDelivery.LocalIPAddress, (relatedMailItem != null) ? new long?(relatedMailItem.RecordId) : null, transportMailItem.MessageTrackingSecurityInfo, invalidRecipients);
                MessageTrackingLog.TrackReceive(messageTrackingSource, transportMailItem, msgTrackInfo);
                Utils.SubmitMailItem(transportMailItem, false);
            }
        }
        private static void LogRetryExceptionInConnectionLog(RetryException exception, MbxTransportMailItem mbxItem, string sourceContext, ulong sessionId, ulong bytesDelivered, ulong recipientCount)
        {
            StringBuilder stringBuilder = new StringBuilder(400);

            stringBuilder.Append("Lost connection - scheduling retry. ");
            if (exception.MessageStatus.Exception != null)
            {
                string exceptionTypeString     = StorageExceptionHandler.GetExceptionTypeString(exception.MessageStatus.Exception);
                string exceptionDiagnosticInfo = StorageExceptionHandler.GetExceptionDiagnosticInfo(exception.MessageStatus.Exception);
                if (string.IsNullOrEmpty(exceptionDiagnosticInfo))
                {
                    stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "SmtpResponse: {0}: {1}: {2}.", new object[]
                    {
                        exception.MessageStatus.Response,
                        exception.StoreDriverContext,
                        exceptionTypeString
                    });
                }
                else
                {
                    stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "SmtpResponse: {0}: {1}: {2}: {3}", new object[]
                    {
                        exception.MessageStatus.Response,
                        exception.StoreDriverContext,
                        exceptionTypeString,
                        exceptionDiagnosticInfo
                    });
                }
            }
            ConnectionLog.MapiDeliveryConnectionLost(sessionId, mbxItem.DatabaseName, stringBuilder.ToString(), 1UL, bytesDelivered, recipientCount);
        }
        public SmtpResponse DoLocalDelivery(TransportMailItem item)
        {
            ulong num  = 0UL;
            ulong num2 = 0UL;
            ulong num3 = 0UL;
            MbxTransportMailItem mbxTransportMailItem = null;
            string sourceContext = string.Empty;

            if (StoreDriverDelivery.SilentlyDropProbeMessages(item))
            {
                return(SmtpResponse.ProbeMessageDropped);
            }
            try
            {
                item.CacheTransportSettings();
                ExTraceGlobals.FaultInjectionTracer.TraceTest(2735091005U);
                num3 = SessionId.GetNextSessionId();
                mbxTransportMailItem = new MbxTransportMailItem(item);
                mbxTransportMailItem.SessionStartTime = DateTime.UtcNow;
                sourceContext = StoreDriverDelivery.GenerateSessionSourceContext(num3, mbxTransportMailItem.SessionStartTime);
                StoreDriverDelivery.SetupLatencyTracker(mbxTransportMailItem);
                StoreDriverDelivery.ResolveItemRecipients(item);
                if (!this.ResolveMdbParameters(mbxTransportMailItem, num3))
                {
                    return(mbxTransportMailItem.Response);
                }
                StoreDriverDelivery.ScopeADRecipientCache(item);
                ConnectionLog.MapiDeliveryConnectionStart(num3, mbxTransportMailItem.DatabaseName, string.Format("Delivery;MailboxServer={0};Database={1}", StoreDriverDelivery.MailboxServerFqdn, mbxTransportMailItem.DatabaseName));
                if (this.retired)
                {
                    ConnectionLog.MapiDeliveryConnectionRetired(num3, mbxTransportMailItem.DatabaseName);
                    return(SmtpResponseGenerator.StoreDriverRetireResponse);
                }
                MSExchangeStoreDriver.MessageDeliveryAttempts.Increment();
                MSExchangeStoreDriver.CurrentDeliveryThreads.Increment();
                StoreDriverDeliveryDiagnostics.IncrementDeliveringThreads();
                StoreDriverDeliveryDiagnostics.Diag.TracePfd <int, string>(0L, "PFD ESD {0} Start local delivery to {1}", 21403, mbxTransportMailItem.DatabaseName);
                ConnectionLog.MapiDeliveryConnectionStartingDelivery(num3, mbxTransportMailItem.DatabaseName);
                int num4 = this.DeliverMailItem(mbxTransportMailItem, num3);
                if (0 < num4)
                {
                    num  += (ulong)mbxTransportMailItem.MimeSize;
                    num2 += (ulong)((long)num4);
                }
                ConnectionLog.MapiDeliveryConnectionStop(num3, mbxTransportMailItem.DatabaseName, 1UL, num, num2);
            }
            catch (ADTransientException exception)
            {
                if (mbxTransportMailItem == null)
                {
                    mbxTransportMailItem = new MbxTransportMailItem(item);
                }
                RetryException exception2 = new RetryException(new MessageStatus(MessageAction.Retry, AckReason.RecipientMailboxLocationInfoNotAvailable, exception));
                StoreDriverDelivery.AckMailItemOnRetryException(AckStatus.Retry, mbxTransportMailItem, exception2, sourceContext, num3, num, num2);
                ExTraceGlobals.FaultInjectionTracer.TraceTest(48992U);
            }
            catch (RetryException exception3)
            {
                StoreDriverDelivery.AckMailItemOnRetryException(AckStatus.Retry, mbxTransportMailItem, exception3, sourceContext, num3, num, num2);
            }
            finally
            {
                StoreDriverDeliveryDiagnostics.DecrementDeliveringThreads();
                MSExchangeStoreDriver.CurrentDeliveryThreads.Decrement();
                StoreDriverDeliveryDiagnostics.Diag.TracePfd <int, string>(0L, "PFD ESD {0} Stop local delivery to {1}", 17563, mbxTransportMailItem.DatabaseName);
                StoreDriverDeliveryDiagnostics.TroubleshootingContext.TraceOperationCompletedAndUpdateContext();
            }
            return(mbxTransportMailItem.Response);
        }
 private static void SetupLatencyTracker(MbxTransportMailItem mbxItem)
 {
     mbxItem.TrackSuccessfulConnectLatency(LatencyComponent.SmtpReceive);
 }