Example #1
0
        public static bool IsMessageOpaqueSigned(Item item)
        {
            Util.ThrowOnNullArgument(item, "item");
            ICoreItem coreItem       = item.CoreItem;
            string    valueOrDefault = coreItem.PropertyBag.GetValueOrDefault <string>(InternalSchema.ItemClass, string.Empty);

            if (!ObjectClass.IsSmime(valueOrDefault))
            {
                return(false);
            }
            if (coreItem.AttachmentCollection.Count != 1)
            {
                return(false);
            }
            IList <AttachmentHandle> allHandles = coreItem.AttachmentCollection.GetAllHandles();
            bool result;

            using (CoreAttachment coreAttachment = coreItem.AttachmentCollection.Open(allHandles[0]))
            {
                using (StreamAttachment streamAttachment = (StreamAttachment)AttachmentCollection.CreateTypedAttachment(coreAttachment, new AttachmentType?(AttachmentType.Stream)))
                {
                    if (streamAttachment == null)
                    {
                        result = false;
                    }
                    else
                    {
                        result = ConvertUtils.IsMessageOpaqueSigned(coreItem, streamAttachment);
                    }
                }
            }
            return(result);
        }
        internal static SharingMessage GetSharingMessage(MessageItem item)
        {
            StreamAttachment sharingMessageAttachment = SharingMessageAttachment.GetSharingMessageAttachment(item);

            if (sharingMessageAttachment != null)
            {
                using (sharingMessageAttachment)
                {
                    using (Stream stream = sharingMessageAttachment.TryGetContentStream(PropertyOpenMode.ReadOnly))
                    {
                        SharingMessage sharingMessage = null;
                        try
                        {
                            sharingMessage = SharingMessage.DeserializeFromStream(stream);
                        }
                        catch (InvalidOperationException)
                        {
                        }
                        if (sharingMessage != null)
                        {
                            ValidationResults validationResults = sharingMessage.Validate();
                            if (validationResults.Result == ValidationResult.Success)
                            {
                                return(sharingMessage);
                            }
                        }
                    }
                }
            }
            return(null);
        }
Example #3
0
        private long WriteAttachment(Item item, Attachment attachment)
        {
            this.limitsTracker.CountMessageAttachment();
            this.WriteAttachmentAttributes(attachment);
            long             result           = 0L;
            StreamAttachment streamAttachment = attachment as StreamAttachment;

            if (streamAttachment != null)
            {
                using (Stream stream = this.tnefWriter.OpenAttributeStream(TnefAttributeTag.AttachData, TnefAttributeLevel.Attachment))
                {
                    object        obj           = attachment.TryGetProperty(InternalSchema.AttachDataBin);
                    PropertyError propertyError = obj as PropertyError;
                    if (propertyError != null)
                    {
                        using (Stream stream2 = streamAttachment.TryGetRawContentStream(PropertyOpenMode.ReadOnly))
                        {
                            if (stream2 != null)
                            {
                                result = Util.StreamHandler.CopyStreamData(stream2, stream);
                            }
                            goto IL_88;
                        }
                    }
                    byte[] array = (byte[])obj;
                    result = (long)array.Length;
                    stream.Write(array, 0, array.Length);
                    IL_88 :;
                }
            }
            this.WriteAttachmentProperties(attachment);
            return(result);
        }
Example #4
0
 private void UnprotectAllAttachments()
 {
     if (!(this.decodedItem.TryGetProperty(MessageItemSchema.DRMServerLicense) is string))
     {
         return;
     }
     foreach (AttachmentHandle handle in this.decodedItem.AttachmentCollection)
     {
         using (Attachment attachment = this.decodedItem.AttachmentCollection.Open(handle))
         {
             Stream           stream           = null;
             StreamAttachment streamAttachment = attachment as StreamAttachment;
             if (StreamAttachment.TryOpenRestrictedContent(streamAttachment, this.orgId, out stream))
             {
                 using (stream)
                 {
                     using (Stream contentStream = streamAttachment.GetContentStream(PropertyOpenMode.Create))
                     {
                         Util.StreamHandler.CopyStreamData(stream, contentStream);
                     }
                 }
                 attachment.Save();
             }
         }
     }
 }
        private static StreamAttachment GetOrCreateSharingMessageAttachment(MessageItem item)
        {
            StreamAttachment streamAttachment = SharingMessageAttachment.GetSharingMessageAttachment(item);

            if (streamAttachment == null)
            {
                streamAttachment = (StreamAttachment)item.AttachmentCollection.Create(AttachmentType.Stream);
            }
            return(streamAttachment);
        }
Example #6
0
        private static bool IsMessageMultipartSigned(ICoreItem coreItem, StreamAttachment attachment)
        {
            string valueOrDefault = coreItem.PropertyBag.GetValueOrDefault <string>(InternalSchema.ItemClass, string.Empty);

            if (!ObjectClass.IsSmimeClearSigned(valueOrDefault))
            {
                return(false);
            }
            string contentType = attachment.ContentType;

            return(string.Equals(attachment.ContentType, "multipart/signed", StringComparison.OrdinalIgnoreCase));
        }
Example #7
0
 internal AttachmentInfo(StoreObjectId messageId, Attachment attachment)
 {
     this.fileName      = attachment.FileName;
     this.fileExtension = attachment.FileExtension;
     this.displayName   = attachment.DisplayName;
     this.contentType   = attachment.ContentType;
     if (string.IsNullOrEmpty(this.contentType))
     {
         this.contentType = attachment.CalculatedContentType;
     }
     this.isInline         = attachment.IsInline;
     this.size             = attachment.Size;
     this.attachmentType   = attachment.AttachmentType;
     this.messageId        = messageId;
     this.attachmentId     = attachment.Id;
     this.contentId        = attachment.ContentId;
     this.lastModifiedTime = attachment.LastModifiedTime;
     this.contentLocation  = attachment.ContentLocation;
     if (attachment.AttachmentType == AttachmentType.Stream)
     {
         StreamAttachment streamAttachment = attachment as StreamAttachment;
         if (streamAttachment != null)
         {
             this.imageThumbnail       = streamAttachment.LoadAttachmentThumbnail();
             this.imageThumbnailHeight = streamAttachment.ImageThumbnailHeight;
             this.imageThumbnailWidth  = streamAttachment.ImageThumbnailWidth;
             if (this.imageThumbnail != null)
             {
                 this.salientRegions = streamAttachment.LoadAttachmentThumbnailSalientRegions();
             }
         }
     }
     if (attachment.AttachmentType == AttachmentType.EmbeddedMessage)
     {
         ItemAttachment itemAttachment = attachment as ItemAttachment;
         if (itemAttachment != null)
         {
             using (Item item = itemAttachment.GetItem())
             {
                 this.embeddedItemClass = item.ClassName;
             }
         }
     }
     if (attachment.AttachmentType == AttachmentType.Reference)
     {
         ReferenceAttachment referenceAttachment = attachment as ReferenceAttachment;
         if (referenceAttachment != null)
         {
             this.attachLongPathName = referenceAttachment.AttachLongPathName;
             this.providerType       = referenceAttachment.ProviderType;
         }
     }
 }
Example #8
0
        private static bool IsMessageOpaqueSigned(ICoreItem coreItem, StreamAttachment attachment)
        {
            Util.ThrowOnNullArgument(coreItem, "coreItem");
            string valueOrDefault = coreItem.PropertyBag.GetValueOrDefault <string>(InternalSchema.ItemClass, string.Empty);

            if (!ObjectClass.IsSmime(valueOrDefault))
            {
                return(false);
            }
            coreItem.PropertyBag.Load(new PropertyDefinition[]
            {
                InternalSchema.NamedContentType
            });
            string valueOrDefault2 = coreItem.PropertyBag.GetValueOrDefault <string>(InternalSchema.NamedContentType);

            if (valueOrDefault2 != null)
            {
                byte[]            bytes  = CTSGlobals.AsciiEncoding.GetBytes(valueOrDefault2);
                ContentTypeHeader header = (ContentTypeHeader)Header.Create(HeaderId.ContentType);
                MimeInternalHelpers.SetHeaderRawValue(header, bytes);
                string headerParameter = MimeHelpers.GetHeaderParameter(header, "smime-type", 100);
                if (headerParameter == null || (!ConvertUtils.MimeStringEquals(headerParameter, "signed-data") && !ConvertUtils.MimeStringEquals(headerParameter, "certs-only")))
                {
                    return(false);
                }
            }
            string contentType = attachment.ContentType;

            if (string.Compare(contentType, "application/pkcs7-mime", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(contentType, "application/x-pkcs7-mime", StringComparison.OrdinalIgnoreCase) == 0)
            {
                return(true);
            }
            if (string.Compare(contentType, "application/octet-stream", StringComparison.OrdinalIgnoreCase) == 0)
            {
                string fileName = attachment.FileName;
                string strA     = string.Empty;
                if (fileName != null)
                {
                    string[] array = fileName.Split(new char[]
                    {
                        '.'
                    });
                    if (array.Length > 0)
                    {
                        strA = array[array.Length - 1];
                    }
                }
                return(string.Compare(strA, "p7m", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(strA, "p7c", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(strA, "p7s", StringComparison.OrdinalIgnoreCase) == 0);
            }
            return(false);
        }
 private static void AttachICalToItem(Stream iCalStream, Item item)
 {
     iCalStream.Seek(0L, SeekOrigin.Begin);
     using (StreamAttachment streamAttachment = (StreamAttachment)item.AttachmentCollection.Create(AttachmentType.Stream))
     {
         streamAttachment.FileName = CalendarUtil.NotSupportedInboundIcal;
         streamAttachment[AttachmentSchema.FailedInboundICalAsAttachment] = true;
         using (Stream contentStream = streamAttachment.GetContentStream(PropertyOpenMode.Create))
         {
             Util.StreamHandler.CopyStreamData(iCalStream, contentStream);
         }
         streamAttachment.Save();
     }
 }
 internal static void SetSharingMessage(MessageItem item, SharingMessage sharingMessage)
 {
     using (StreamAttachment orCreateSharingMessageAttachment = SharingMessageAttachment.GetOrCreateSharingMessageAttachment(item))
     {
         orCreateSharingMessageAttachment.PropertyBag[AttachmentSchema.AttachMimeTag]      = "application/x-sharing-metadata-xml";
         orCreateSharingMessageAttachment.PropertyBag[AttachmentSchema.AttachLongFileName] = "sharing_metadata.xml";
         using (Stream contentStream = orCreateSharingMessageAttachment.GetContentStream(PropertyOpenMode.Create))
         {
             sharingMessage.SerializeToStream(contentStream);
             contentStream.Flush();
         }
         orCreateSharingMessageAttachment.Save();
     }
 }
Example #11
0
        internal static bool IsSmimeMessage(ICoreItem coreItem, out bool isMultipartSigned, out bool isOpaqueSigned, out StreamAttachment attachment)
        {
            isMultipartSigned = false;
            isOpaqueSigned    = false;
            attachment        = null;
            string valueOrDefault = coreItem.PropertyBag.GetValueOrDefault <string>(InternalSchema.ItemClass, string.Empty);

            if (!ObjectClass.IsSmime(valueOrDefault))
            {
                return(false);
            }
            IList <AttachmentHandle> allHandles = coreItem.AttachmentCollection.GetAllHandles();

            if (allHandles.Count != 1)
            {
                return(false);
            }
            using (DisposeGuard disposeGuard = default(DisposeGuard))
            {
                CoreAttachment coreAttachment = coreItem.AttachmentCollection.Open(allHandles[0]);
                disposeGuard.Add <CoreAttachment>(coreAttachment);
                StreamAttachment streamAttachment = (StreamAttachment)AttachmentCollection.CreateTypedAttachment(coreAttachment, new AttachmentType?(AttachmentType.Stream));
                if (streamAttachment == null)
                {
                    return(false);
                }
                disposeGuard.Add <StreamAttachment>(streamAttachment);
                if (ObjectClass.IsSmimeClearSigned(valueOrDefault))
                {
                    isMultipartSigned = ConvertUtils.IsMessageMultipartSigned(coreItem, streamAttachment);
                    if (isMultipartSigned)
                    {
                        attachment = streamAttachment;
                        disposeGuard.Success();
                        return(true);
                    }
                }
                isOpaqueSigned = ConvertUtils.IsMessageOpaqueSigned(coreItem, streamAttachment);
                if (isOpaqueSigned)
                {
                    attachment = streamAttachment;
                    disposeGuard.Success();
                    return(true);
                }
            }
            return(false);
        }
Example #12
0
 public Stream GetPhotoStream()
 {
     foreach (AttachmentHandle handle in base.AttachmentCollection)
     {
         using (Attachment attachment = base.AttachmentCollection.Open(handle, null))
         {
             if (attachment.IsContactPhoto)
             {
                 StreamAttachment streamAttachment = attachment as StreamAttachment;
                 if (streamAttachment != null)
                 {
                     return(streamAttachment.TryGetContentStream(PropertyOpenMode.ReadOnly));
                 }
             }
         }
     }
     return(null);
 }
Example #13
0
        public StreamAttachment ConvertToImageAttachment(CoreAttachmentCollection collection, ImageFormat format)
        {
            base.CheckDisposed("ConvertToImageAttachment");
            Util.ThrowOnNullArgument(collection, "collection");
            EnumValidator.ThrowIfInvalid <ImageFormat>(format);
            StreamAttachment result;

            using (DisposeGuard disposeGuard = default(DisposeGuard))
            {
                CoreAttachment coreAttachment = collection.InternalCreateCopy(new AttachmentType?(AttachmentType.Stream), base.CoreAttachment);
                disposeGuard.Add <CoreAttachment>(coreAttachment);
                StreamAttachment streamAttachment = (StreamAttachment)AttachmentCollection.CreateTypedAttachment(coreAttachment, new AttachmentType?(AttachmentType.Stream));
                disposeGuard.Add <StreamAttachment>(streamAttachment);
                string text = streamAttachment.FileName;
                if (string.IsNullOrEmpty(text))
                {
                    text = Attachment.GenerateFilename();
                }
                string str = null;
                switch (format)
                {
                case ImageFormat.Jpeg:
                    str = ".jpg";
                    break;

                case ImageFormat.Png:
                    str = ".png";
                    break;
                }
                streamAttachment.FileName    = text + str;
                streamAttachment.ContentType = "image/jpeg";
                streamAttachment.IsInline    = true;
                using (Stream contentStream = streamAttachment.GetContentStream(PropertyOpenMode.Create))
                {
                    if (!this.TryConvertToImage(contentStream, ImageFormat.Jpeg))
                    {
                        ConvertUtils.SaveDefaultImage(contentStream);
                    }
                }
                disposeGuard.Success();
                result = streamAttachment;
            }
            return(result);
        }
Example #14
0
 public void UnprotectAttachment(AttachmentId attachmentId)
 {
     using (Attachment attachment = this.ProtectedAttachmentCollection.Open(attachmentId))
     {
         StreamAttachment streamAttachment = attachment as StreamAttachment;
         if (streamAttachment == null)
         {
             throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachment);
         }
         using (Stream stream = StreamAttachment.OpenRestrictedContent(streamAttachment, this.orgId))
         {
             using (Stream contentStream = streamAttachment.GetContentStream(PropertyOpenMode.Create))
             {
                 Util.StreamHandler.CopyStreamData(stream, contentStream);
             }
         }
         attachment.Save();
     }
 }
Example #15
0
 public override void Export(ContactWriter writer, Contact contact, OutboundVCardConverter.PropertyExporter.Context context)
 {
     foreach (AttachmentHandle handle in contact.AttachmentCollection)
     {
         using (Attachment attachment = contact.AttachmentCollection.Open(handle, null))
         {
             if (attachment.IsContactPhoto)
             {
                 StreamAttachment streamAttachment = attachment as StreamAttachment;
                 if (streamAttachment != null)
                 {
                     string text = streamAttachment.ContentType;
                     if (string.IsNullOrEmpty(text))
                     {
                         text = streamAttachment.CalculatedContentType;
                     }
                     string value = null;
                     if (!string.IsNullOrEmpty(text) && OutboundVCardConverter.PhotoExporter.contentTypeToType.TryGetValue(text, out value))
                     {
                         using (Stream stream = streamAttachment.TryGetContentStream(PropertyOpenMode.ReadOnly))
                         {
                             if (stream != null)
                             {
                                 writer.StartProperty(PropertyId.Photo);
                                 writer.WriteParameter(ParameterId.Type, value);
                                 writer.WriteParameter(ParameterId.Encoding, "B");
                                 using (Stream stream2 = new EncoderStream(stream, new Base64Encoder(0), EncoderStreamAccess.Read))
                                 {
                                     writer.WritePropertyValue(stream2);
                                     break;
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Example #16
0
        private void DecryptMsg(MessageItem rightsProtectedMessage, string useLicense, SafeRightsManagementHandle decryptorHandle)
        {
            if (decryptorHandle == null)
            {
                throw new ArgumentNullException("decryptorHandle");
            }
            if (decryptorHandle.IsInvalid)
            {
                throw new ArgumentException("decryptorHandle");
            }
            this.originalItem = rightsProtectedMessage;
            DrmEmailMessage drmEmailMessage = null;
            bool            flag            = false;

            try
            {
                ExTraceGlobals.RightsManagementTracer.TraceDebug((long)this.GetHashCode(), "Found a use license for server. Decrypting message");
                DrmEmailMessageBinding messageBinding = new DrmEmailMessageBinding(this.drmMsgContainer.PublishLicense, decryptorHandle);
                this.drmMsgContainer.Bind(messageBinding, new CreateStreamCallbackDelegate(this.BodyStreamCallback), new CreateStreamCallbackDelegate(this.AttachmentsStreamCallback));
                drmEmailMessage = this.drmMsgContainer.EmailMessage;
                this.SaveAndCloseCurrentAttachment();
                this.decryptedItem.SafeSetProperty(InternalSchema.DRMServerLicense, useLicense);
                this.decryptedItem.SafeSetProperty(InternalSchema.DrmPublishLicense, this.drmMsgContainer.PublishLicense);
                if (drmEmailMessage.Attachments.Count > 0)
                {
                    ExTraceGlobals.RightsManagementTracer.TraceDebug <int>((long)this.GetHashCode(), "Number of attachments in the rights protected message : {0}", drmEmailMessage.Attachments.Count);
                    int num = 0;
                    foreach (DrmEmailAttachment drmEmailAttachment in drmEmailMessage.Attachments)
                    {
                        using (Attachment attachment = this.decryptedItem.AttachmentCollection.Open(this.messageAttachmentIds[num++], null))
                        {
                            attachment.FileName = drmEmailAttachment.FileName;
                            attachment[InternalSchema.DisplayName] = drmEmailAttachment.DisplayName;
                            attachment.ContentId = drmEmailAttachment.ContentId;
                            attachment[InternalSchema.AttachContentLocation] = drmEmailAttachment.ContentLocation;
                            attachment[InternalSchema.AttachMhtmlFlags]      = drmEmailAttachment.AttachFlags;
                            attachment[InternalSchema.AttachCalendarHidden]  = drmEmailAttachment.AttachHidden;
                            if (drmEmailAttachment.AttachHidden)
                            {
                                attachment.IsInline = true;
                            }
                            if (drmEmailMessage.BodyFormat == BodyFormat.Rtf)
                            {
                                attachment.RenderingPosition = (int)drmEmailAttachment.CharacterPosition;
                                if (attachment.AttachmentType == AttachmentType.EmbeddedMessage || attachment.AttachmentType == AttachmentType.Stream)
                                {
                                    attachment[InternalSchema.AttachRendering] = drmEmailAttachment.AttachRendering;
                                }
                            }
                            if (this.decryptAttachments)
                            {
                                Stream           stream           = null;
                                StreamAttachment streamAttachment = attachment as StreamAttachment;
                                if (streamAttachment != null && StreamAttachment.TryOpenRestrictedContent(streamAttachment, this.orgId, out stream))
                                {
                                    using (stream)
                                    {
                                        using (Stream contentStream = streamAttachment.GetContentStream(PropertyOpenMode.Create))
                                        {
                                            Util.StreamHandler.CopyStreamData(stream, contentStream);
                                        }
                                    }
                                }
                            }
                            attachment.Save();
                        }
                    }
                }
                drmEmailMessage.Close();
                drmEmailMessage = null;
                if (this.originalItem != null)
                {
                    PersistablePropertyBag.CopyProperty(this.originalItem.PropertyBag, InternalSchema.TransportMessageHeaders, this.decryptedItem.PropertyBag);
                    this.decryptedItem.Recipients.CopyRecipientsFrom(this.originalItem.Recipients);
                }
                this.decryptedItem.Save(SaveMode.NoConflictResolution);
                this.decryptedItem.Load(InternalSchema.ContentConversionProperties);
                flag = true;
            }
            finally
            {
                if (drmEmailMessage != null)
                {
                    drmEmailMessage.Close();
                    drmEmailMessage = null;
                }
                if (!flag && this.decryptedItem != null)
                {
                    this.decryptedItem.Dispose();
                    this.decryptedItem = null;
                }
            }
        }
 public static bool TryOpenRestrictedContent(StreamAttachment sourceAttachment, out Stream result)
 {
     return(StreamAttachment.TryOpenRestrictedContent(sourceAttachment, OrganizationId.ForestWideOrgId, out result));
 }
Example #18
0
        protected override void OnBeforeSave()
        {
            if (this.decodedItem == null && !base.AttachmentCollection.IsDirty && base.IsRestricted && (base.Recipients.IsDirty || base.IsPropertyDirty(ItemSchema.Sender)))
            {
                this.EnsureIsDecoded();
            }
            if (this.decodedItem != null)
            {
                string contentClass = base.TryGetProperty(InternalSchema.ContentClass) as string;
                if (this.rmsTemplate == null)
                {
                    this.UnprotectAllAttachments();
                    RightsManagedMessageItem.CopyProtectableData(this.decodedItem, this);
                    if (ObjectClass.IsRightsManagedContentClass(contentClass))
                    {
                        base.Delete(StoreObjectSchema.ContentClass);
                    }
                }
                else
                {
                    this.charsetDetectionStringForProtectedData = new StringBuilder((int)Math.Min(this.ProtectedBody.Size, 2147483647L));
                    this.GetCharsetDetectionStringFromProtectedData(this.charsetDetectionStringForProtectedData);
                    if (!ObjectClass.IsRightsManagedContentClass(contentClass))
                    {
                        this[StoreObjectSchema.ContentClass] = "rpmsg.message";
                    }
                    if (this.isSending)
                    {
                        byte[][] valueOrDefault = base.GetValueOrDefault <byte[][]>(InternalSchema.DRMLicense);
                        if (valueOrDefault != null && valueOrDefault.Length == RightsManagedMessageItem.EmptyDrmLicense.Length && valueOrDefault[0].Length == RightsManagedMessageItem.EmptyDrmLicense[0].Length)
                        {
                            base.DeleteProperties(new PropertyDefinition[]
                            {
                                InternalSchema.DRMLicense
                            });
                        }
                    }
                    else if (base.IsDraft && base.GetValueOrDefault <byte[][]>(InternalSchema.DRMLicense) == null)
                    {
                        this[InternalSchema.DRMLicense] = RightsManagedMessageItem.EmptyDrmLicense;
                    }
                    base.AttachmentCollection.RemoveAll();
                    using (StreamAttachment streamAttachment = base.AttachmentCollection.Create(AttachmentType.Stream) as StreamAttachment)
                    {
                        streamAttachment.FileName    = "message.rpmsg";
                        streamAttachment.ContentType = "application/x-microsoft-rpmsg-message";
                        using (Stream stream = new PooledMemoryStream(131072))
                        {
                            if (this.serverUseLicense == null || ((this.UsageRights & ContentRight.Owner) == ContentRight.Owner && this.rmsTemplate.RequiresRepublishingWhenRecipientsChange && this.CanRepublish && (base.Recipients.IsDirty || (base.IsPropertyDirty(ItemSchema.Sender) && this.conversationOwner == null))))
                            {
                                if (this.ConversationOwner == null)
                                {
                                    throw new InvalidOperationException("Conversation owner must be set before protecting the message.");
                                }
                                this.UnprotectAllAttachments();
                                using (MsgToRpMsgConverter msgToRpMsgConverter = new MsgToRpMsgConverter(this, this.ConversationOwner, this.orgId, this.rmsTemplate, this.options))
                                {
                                    msgToRpMsgConverter.Convert(this.decodedItem, stream);
                                    using (Stream stream2 = base.OpenPropertyStream(MessageItemSchema.DRMServerLicenseCompressed, PropertyOpenMode.Create))
                                    {
                                        DrmEmailCompression.CompressUseLicense(msgToRpMsgConverter.ServerUseLicense, stream2);
                                    }
                                    if (this.InternalSession != null && this.InternalSession.MailboxOwner.Sid != null)
                                    {
                                        ExDateTime useLicenseExpiryTime = RmsClientManagerUtils.GetUseLicenseExpiryTime(msgToRpMsgConverter.ServerUseLicense, this.UsageRights);
                                        this[MessageItemSchema.DRMRights]     = (int)this.UsageRights;
                                        this[MessageItemSchema.DRMExpiryTime] = useLicenseExpiryTime;
                                        using (RightsSignatureBuilder rightsSignatureBuilder = new RightsSignatureBuilder(msgToRpMsgConverter.ServerUseLicense, msgToRpMsgConverter.PublishLicense, RmsClientManager.EnvironmentHandle, msgToRpMsgConverter.LicensePair))
                                        {
                                            this[MessageItemSchema.DRMPropsSignature] = rightsSignatureBuilder.Sign(this.UsageRights, useLicenseExpiryTime, this.InternalSession.MailboxOwner.Sid);
                                        }
                                    }
                                    goto IL_362;
                                }
                            }
                            using (MsgToRpMsgConverter msgToRpMsgConverter2 = new MsgToRpMsgConverter(this, this.orgId, this.publishLicense, this.serverUseLicense, this.options))
                            {
                                msgToRpMsgConverter2.Convert(this.decodedItem, stream);
                            }
IL_362:
                            using (Stream contentStream = streamAttachment.GetContentStream(PropertyOpenMode.Create))
                            {
                                stream.Seek(0L, SeekOrigin.Begin);
                                Util.StreamHandler.CopyStreamData(stream, contentStream);
                            }
                        }
                        bool flag = false;
                        foreach (AttachmentHandle handle in this.decodedItem.AttachmentCollection)
                        {
                            if (!CoreAttachmentCollection.IsInlineAttachment(handle))
                            {
                                flag = true;
                                break;
                            }
                        }
                        this[InternalSchema.AllAttachmentsHidden] = !flag;
                        streamAttachment.Save();
                    }
                }
                this.decodedItem.Dispose();
                this.decodedItem       = null;
                this.effectiveRights   = ContentRight.Owner;
                this.publishLicense    = null;
                this.restrictionInfo   = null;
                this.rmsTemplate       = null;
                this.serverUseLicense  = null;
                this.conversationOwner = null;
            }
            base.OnBeforeSave();
        }
        public static Stream OpenRestrictedAttachment(StreamAttachment sourceAttachment, OrganizationId orgId, string userIdentity, SecurityIdentifier userSid, RecipientTypeDetails userType, out UseLicenseAndUsageRights validatedUseLicenseAndUsageRights, out bool acquiredNewLicense)
        {
            StreamAttachment.< > c__DisplayClass2 CS$ < > 8__locals1 = new StreamAttachment.< > c__DisplayClass2();
            CS$ < > 8__locals1.sourceAttachment = sourceAttachment;
            CS$ < > 8__locals1.orgId            = orgId;
            CS$ < > 8__locals1.userIdentity     = userIdentity;
            CS$ < > 8__locals1.userSid          = userSid;
            CS$ < > 8__locals1.userType         = userType;
            Util.ThrowOnNullArgument(CS$ < > 8__locals1.sourceAttachment, "sourceAttachment");
            Util.ThrowOnNullArgument(CS$ < > 8__locals1.orgId, "orgId");
            Util.ThrowOnNullArgument(CS$ < > 8__locals1.userIdentity, "userIdentity");
            Util.ThrowOnNullArgument(CS$ < > 8__locals1.userSid, "userSid");
            if (!Enum.IsDefined(typeof(RecipientTypeDetails), CS$ < > 8__locals1.userType))
            {
                throw new EnumArgumentException("userType");
            }
            CS$ < > 8__locals1.cachedServerUseLicense = null;
            if (!PropertyError.IsPropertyNotFound(CS$ < > 8__locals1.sourceAttachment.TryGetProperty(AttachmentSchema.DRMServerLicenseCompressed)))
            {
                using (Stream stream = CS$ < > 8__locals1.sourceAttachment.OpenPropertyStream(AttachmentSchema.DRMServerLicenseCompressed, PropertyOpenMode.ReadOnly))
                {
                    CS$ < > 8__locals1.cachedServerUseLicense = DrmEmailCompression.DecompressUseLicense(stream);
                }
            }
            StreamAttachment.< > c__DisplayClass2 CS$ < > 8__locals2 = CS$ < > 8__locals1;
            int?valueAsNullable = CS$ < > 8__locals1.sourceAttachment.PropertyBag.GetValueAsNullable <int>(AttachmentSchema.DRMRights);

            CS$ < > 8__locals2.cachedUsageRights       = ((valueAsNullable != null) ? new ContentRight?((ContentRight)valueAsNullable.GetValueOrDefault()) : null);
            CS$ < > 8__locals1.cachedExpiryTime        = CS$ < > 8__locals1.sourceAttachment.PropertyBag.GetValueAsNullable <ExDateTime>(AttachmentSchema.DRMExpiryTime);
            CS$ < > 8__locals1.cachedDrmPropsSignature = CS$ < > 8__locals1.sourceAttachment.PropertyBag.GetValueOrDefault <byte[]>(AttachmentSchema.DRMPropsSignature);
            CS$ < > 8__locals1.item = CS$ < > 8__locals1.sourceAttachment.CoreAttachment.ParentCollection.ContainerItem;
            if (string.IsNullOrEmpty(CS$ < > 8__locals1.cachedServerUseLicense) || CS$ < > 8__locals1.cachedUsageRights == null || CS$ < > 8__locals1.cachedExpiryTime == null || CS$ < > 8__locals1.cachedDrmPropsSignature == null)
            {
                string valueOrDefault = CS$ < > 8__locals1.item.PropertyBag.GetValueOrDefault <string>(StoreObjectSchema.ItemClass, string.Empty);
                if (ObjectClass.IsMessage(valueOrDefault, false))
                {
                    CS$ < > 8__locals1.cachedServerUseLicense = CS$ < > 8__locals1.item.PropertyBag.GetValueOrDefault <string>(MessageItemSchema.DRMServerLicense, string.Empty);
                    StreamAttachment.< > c__DisplayClass2 CS$ < > 8__locals3 = CS$ < > 8__locals1;
                    int?valueAsNullable2 = CS$ < > 8__locals1.item.PropertyBag.GetValueAsNullable <int>(MessageItemSchema.DRMRights);
                    CS$ < > 8__locals3.cachedUsageRights       = ((valueAsNullable2 != null) ? new ContentRight?((ContentRight)valueAsNullable2.GetValueOrDefault()) : null);
                    CS$ < > 8__locals1.cachedExpiryTime        = CS$ < > 8__locals1.item.PropertyBag.GetValueAsNullable <ExDateTime>(MessageItemSchema.DRMExpiryTime);
                    CS$ < > 8__locals1.cachedDrmPropsSignature = CS$ < > 8__locals1.item.PropertyBag.GetValueOrDefault <byte[]>(MessageItemSchema.DRMPropsSignature);
                }
            }
            CS$ < > 8__locals1.unprotectionSuccess      = false;
            CS$ < > 8__locals1.useLicenseAndUsageRights = null;
            CS$ < > 8__locals1.validCachedLicense       = false;
            Stream unprotectedAttachment;

            using (DisposeGuard disposeGuard = default(DisposeGuard))
            {
                StreamAttachment.< > c__DisplayClass4 CS$ < > 8__locals4 = new StreamAttachment.< > c__DisplayClass4();
                CS$ < > 8__locals4.unprotectedAttachment = disposeGuard.Add <Stream>(Streams.CreateTemporaryStorageStream());
                CS$ < > 8__locals4.decryptorHandle       = null;
                using (Stream inputStream = CS$ < > 8__locals1.sourceAttachment.GetContentStream(PropertyOpenMode.ReadOnly))
                {
                    try
                    {
                        MsgToRpMsgConverter.CallRM(delegate
                        {
                            CS$ < > 8__locals1.unprotectionSuccess = ProtectorsManager.Instance.Unprotect(delegate(string protectedDocumentIssuanceLicense)
                            {
                                string valueOrDefault2 = CS$ < > 8__locals1.item.PropertyBag.GetValueOrDefault <string>(ItemSchema.InternetMessageId, string.Empty);
                                bool flag = string.IsNullOrEmpty(valueOrDefault2);
                                RmsClientManagerContext context = new RmsClientManagerContext(CS$ < > 8__locals1.orgId, flag ? RmsClientManagerContext.ContextId.AttachmentFileName : RmsClientManagerContext.ContextId.MessageId, flag ? CS$ < > 8__locals1.sourceAttachment.FileName : valueOrDefault2, null);
                                if (!string.IsNullOrEmpty(CS$ < > 8__locals1.cachedServerUseLicense) && CS$ < > 8__locals1.cachedUsageRights != null && CS$ < > 8__locals1.cachedExpiryTime != null && CS$ < > 8__locals1.cachedDrmPropsSignature != null)
                                {
                                    try
                                    {
                                        CS$ < > 8__locals4.decryptorHandle    = RmsClientManager.VerifyDRMPropsSignatureAndGetDecryptor(context, CS$ < > 8__locals1.userSid, CS$ < > 8__locals1.userType, CS$ < > 8__locals1.userIdentity, CS$ < > 8__locals1.cachedUsageRights.Value, CS$ < > 8__locals1.cachedExpiryTime.Value, CS$ < > 8__locals1.cachedDrmPropsSignature, CS$ < > 8__locals1.cachedServerUseLicense, protectedDocumentIssuanceLicense, UsageRightsSignatureVerificationOptions.LookupSidHistory, StreamAttachment.EmptySidList);
                                        CS$ < > 8__locals1.validCachedLicense = true;
                                        Uri licensingUri = null;
                                        XmlNode[] array  = null;
                                        bool flag2;
                                        RmsClientManager.GetLicensingUri(CS$ < > 8__locals1.orgId, protectedDocumentIssuanceLicense, out licensingUri, out array, out flag2);
                                        CS$ < > 8__locals1.useLicenseAndUsageRights = new UseLicenseAndUsageRights(CS$ < > 8__locals1.cachedServerUseLicense, CS$ < > 8__locals1.cachedUsageRights.Value, CS$ < > 8__locals1.cachedExpiryTime.Value, CS$ < > 8__locals1.cachedDrmPropsSignature, CS$ < > 8__locals1.orgId, protectedDocumentIssuanceLicense, licensingUri);
                                    }
                                    catch (BadDRMPropsSignatureException)
                                    {
                                    }
                                }
                                if (CS$ < > 8__locals1.useLicenseAndUsageRights == null)
                                {
                                    CS$ < > 8__locals1.useLicenseAndUsageRights = RmsClientManager.AcquireUseLicenseAndUsageRights(context, protectedDocumentIssuanceLicense, CS$ < > 8__locals1.userIdentity, CS$ < > 8__locals1.userSid, CS$ < > 8__locals1.userType);
                                    if (CS$ < > 8__locals4.decryptorHandle != null)
                                    {
                                        CS$ < > 8__locals4.decryptorHandle.Close();
                                        CS$ < > 8__locals4.decryptorHandle = null;
                                    }
                                    RmsClientManager.BindUseLicenseForDecryption(context, CS$ < > 8__locals1.useLicenseAndUsageRights.LicensingUri, CS$ < > 8__locals1.useLicenseAndUsageRights.UseLicense, CS$ < > 8__locals1.useLicenseAndUsageRights.PublishingLicense, out CS$ < > 8__locals4.decryptorHandle);
                                }
                                return(CS$ < > 8__locals4.decryptorHandle);
                            }, CS$ < > 8__locals1.sourceAttachment.FileName, inputStream, CS$ < > 8__locals4.unprotectedAttachment);
                        }, ServerStrings.FailedToUnprotectAttachment(CS$ < > 8__locals1.sourceAttachment.FileName));
                    }