internal static string GetAttachment(MailboxSession mailboxSession, string attachmentId, Stream outStream, int offset, int count, Unlimited <ByteQuantifiedSize> maxAttachmentSize, ItemIdMapping idmapping, bool rightsManagementSupport, out int total)
        {
            string[] array = attachmentId.Split(new char[]
            {
                ':'
            });
            if (array.Length != 2 && array.Length != 3)
            {
                return(AttachmentHelper.GetAttachmentByUrlCompName(mailboxSession, attachmentId, outStream, offset, count, maxAttachmentSize, out total));
            }
            StoreObjectId itemId;
            string        text;

            if (array.Length == 2)
            {
                itemId = AttachmentHelper.GetItemId(array[0]);
                text   = array[1];
            }
            else
            {
                itemId = AttachmentHelper.GetItemId(idmapping, array[0], array[1]);
                text   = array[2];
            }
            if (itemId == null)
            {
                throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentId));
            }
            AirSyncDiagnostics.TraceDebug <StoreObjectId, string>(ExTraceGlobals.RequestsTracer, null, "Getting attachment with itemId {0} and attachmentIndex {1}.", itemId, text);
            return(AttachmentHelper.GetAttachment(mailboxSession, itemId, text, outStream, offset, count, maxAttachmentSize, rightsManagementSupport, out total));
        }
 internal static void CreateAttachment(IItem parentItem, Attachment16Data attachmentData)
 {
     AirSyncDiagnostics.TraceDebug <byte>(ExTraceGlobals.RequestsTracer, null, "CreateAttachment with AttachMethod:{0}", attachmentData.Method);
     if (attachmentData.Method == 1)
     {
         if (attachmentData.Content == null)
         {
             throw new ConversionException(string.Format(" Attachment content can not be null.", new object[0]));
         }
         IStreamAttachment streamAttachment = parentItem.IAttachmentCollection.CreateIAttachment(AttachmentType.Stream) as IStreamAttachment;
         AttachmentHelper.CopyCommonAttachmentProperties(streamAttachment, attachmentData);
         using (Stream contentStream = streamAttachment.GetContentStream())
         {
             contentStream.Write(attachmentData.Content, 0, attachmentData.Content.Length);
         }
         streamAttachment.Save();
     }
     else
     {
         if (attachmentData.Method != 5)
         {
             throw new ConversionException(string.Format("UnSupported Value '{0}' for Attachment Method. Only 1 & 5 is supported AttachemntType", attachmentData.Method));
         }
         ItemAttachment itemAttachment = parentItem.IAttachmentCollection.CreateIAttachment(AttachmentType.EmbeddedMessage) as ItemAttachment;
         AttachmentHelper.CopyCommonAttachmentProperties(itemAttachment, attachmentData);
         using (Stream stream = new MemoryStream(attachmentData.Content))
         {
             stream.Seek(0L, SeekOrigin.Begin);
             InboundConversionOptions inboundConversionOptions = AirSyncUtility.GetInboundConversionOptions();
             inboundConversionOptions.ClearCategories = false;
             try
             {
                 using (Item item = itemAttachment.GetItem())
                 {
                     ItemConversion.ConvertAnyMimeToItem(item, stream, inboundConversionOptions);
                     item.Save(SaveMode.NoConflictResolution);
                 }
             }
             catch (ExchangeDataException innerException)
             {
                 throw new AirSyncPermanentException(HttpStatusCode.BadRequest, StatusCode.InvalidMIME, innerException, false);
             }
             catch (ConversionFailedException innerException2)
             {
                 throw new AirSyncPermanentException(HttpStatusCode.BadRequest, StatusCode.InvalidMIME, innerException2, false);
             }
         }
         itemAttachment.Save();
     }
     AirSyncDiagnostics.TraceDebug <int>(ExTraceGlobals.RequestsTracer, null, "AttachmentHelper:CreateAttachments:: AttachmentCreated successful. AttachmentCount:{0}", parentItem.IAttachmentCollection.Count);
 }
        // Token: 0x06000C3C RID: 3132 RVA: 0x00040194 File Offset: 0x0003E394
        protected override int InternalExecute(int count)
        {
            FolderSyncState folderSyncState = null;
            int             result;

            try
            {
                string        text          = HttpUtility.UrlDecode(base.FileReference);
                int           num           = text.IndexOf(':');
                ItemIdMapping itemIdMapping = null;
                if (num != -1 && num != text.LastIndexOf(':'))
                {
                    string text2 = text.Substring(0, num);
                    SyncCollection.CollectionTypes collectionType = AirSyncUtility.GetCollectionType(text2);
                    if (collectionType != SyncCollection.CollectionTypes.Mailbox && collectionType != SyncCollection.CollectionTypes.Unknown)
                    {
                        base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "NoAttachmentsOnVItem");
                        AirSyncPermanentException ex = new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.InvalidCombinationOfIDs, null, false);
                        throw ex;
                    }
                    folderSyncState = base.SyncStateStorage.GetFolderSyncState(new MailboxSyncProviderFactory(base.Session), text2);
                    if (folderSyncState == null)
                    {
                        throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(text));
                    }
                    itemIdMapping = (ItemIdMapping)folderSyncState[CustomStateDatumType.IdMapping];
                    if (itemIdMapping == null)
                    {
                        throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(text));
                    }
                }
                int num2;
                base.ContentType = AttachmentHelper.GetAttachment(base.Session, text, base.OutStream, base.MinRange, count, base.MaxAttachmentSize, itemIdMapping, base.RightsManagementSupport, out num2);
                result           = num2;
            }
            finally
            {
                if (folderSyncState != null)
                {
                    folderSyncState.Dispose();
                    folderSyncState = null;
                }
            }
            return(result);
        }
Example #4
0
        // Token: 0x06000767 RID: 1895 RVA: 0x00029340 File Offset: 0x00027540
        protected override int InternalExecute(int count)
        {
            string[] array = HttpUtility.UrlDecode(base.FileReference).Split(new char[]
            {
                ':'
            });
            if (array.Length != 2)
            {
                throw new AirSyncPermanentException(StatusCode.Sync_TooManyFolders, false)
                      {
                          ErrorStringForProtocolLogger = "InvalidEntityAttachemtnId"
                      };
            }
            StoreObjectId itemId = StoreId.EwsIdToStoreObjectId(array[0]);
            IEvents       events = EntitySyncItem.GetEvents(this.CalendaringContainer, base.Session, itemId);

            if (events == null)
            {
                throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, false)
                      {
                          ErrorStringForProtocolLogger = "EventsNotFound"
                      };
            }
            IAttachments attachments = events[array[0]].Attachments;

            if (attachments == null)
            {
                throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, false)
                      {
                          ErrorStringForProtocolLogger = "EntityNotFound"
                      };
            }
            IAttachment attachment = attachments.Read(array[1], null);

            if (attachment == null)
            {
                throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, false)
                      {
                          ErrorStringForProtocolLogger = "EntityAttachementNotFound"
                      };
            }
            base.ContentType = attachment.ContentType;
            FileAttachment fileAttachment = attachment as FileAttachment;
            ItemAttachment itemAttachment = attachment as ItemAttachment;

            if (fileAttachment != null)
            {
                if (!base.MaxAttachmentSize.IsUnlimited && fileAttachment.Content.Length > (int)base.MaxAttachmentSize.Value.ToBytes())
                {
                    throw new DataTooLargeException(StatusCode.AttachmentIsTooLarge);
                }
                count = ((count == -1) ? fileAttachment.Content.Length : Math.Min(count, fileAttachment.Content.Length - base.MinRange));
                base.OutStream.Write(fileAttachment.Content, base.MinRange, count);
                return(count);
            }
            else
            {
                if (itemAttachment != null)
                {
                    int result;
                    AttachmentHelper.GetAttachment(base.Session, itemId, attachment.Id, base.OutStream, base.MinRange, count, base.MaxAttachmentSize, base.RightsManagementSupport, out result);
                    return(result);
                }
                throw new AirSyncPermanentException(StatusCode.Sync_InvalidWaitTime, new LocalizedString(string.Format("Attachment type \"{0}\" is not supported.", attachment.GetType().FullName)), false)
                      {
                          ErrorStringForProtocolLogger = "UnsupportedEntityAttachementType"
                      };
            }
        }
        internal override Command.ExecutionState ExecuteCommand()
        {
            string          attachmentName  = this.AttachmentName;
            string          value           = string.Empty;
            FolderSyncState folderSyncState = null;

            AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, this, "GetAttachmentCommand.Execute(). AttachmentName: '{0}'", attachmentName);
            try
            {
                int incBy = 0;
                if (base.Request.ContentType != null && !string.Equals(base.Request.ContentType, "message/rfc822", StringComparison.OrdinalIgnoreCase))
                {
                    base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "InvalidContentType");
                    throw new AirSyncPermanentException(HttpStatusCode.BadRequest, StatusCode.First140Error, null, false);
                }
                int           num           = attachmentName.IndexOf(':');
                ItemIdMapping itemIdMapping = null;
                if (num != -1 && num != attachmentName.LastIndexOf(':'))
                {
                    folderSyncState = base.SyncStateStorage.GetFolderSyncState(new MailboxSyncProviderFactory(base.MailboxSession), attachmentName.Substring(0, num));
                    if (folderSyncState == null)
                    {
                        throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentName));
                    }
                    itemIdMapping = (ItemIdMapping)folderSyncState[CustomStateDatumType.IdMapping];
                    if (itemIdMapping == null)
                    {
                        throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentName));
                    }
                }
                PolicyData policyData = ADNotificationManager.GetPolicyData(base.User);
                if (policyData != null && !policyData.AttachmentsEnabled)
                {
                    base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "AttachmentsNotEnabledGetAttCmd");
                    throw new AirSyncPermanentException(HttpStatusCode.Forbidden, StatusCode.AccessDenied, null, false);
                }
                Unlimited <ByteQuantifiedSize> maxAttachmentSize = (policyData != null) ? policyData.MaxAttachmentSize : Unlimited <ByteQuantifiedSize> .UnlimitedValue;
                value = AttachmentHelper.GetAttachment(base.MailboxSession, attachmentName, base.OutputStream, maxAttachmentSize, itemIdMapping, out incBy);
                base.ProtocolLogger.IncrementValue(ProtocolLoggerData.Attachments);
                base.ProtocolLogger.IncrementValueBy(ProtocolLoggerData.AttachmentBytes, incBy);
            }
            catch (FormatException innerException)
            {
                base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "InvalidAttachmentName");
                AirSyncPermanentException ex = new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.InvalidIDs, innerException, false);
                throw ex;
            }
            catch (ObjectNotFoundException innerException2)
            {
                base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "AttachmentNotFound");
                AirSyncPermanentException ex2 = new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.None, innerException2, false);
                throw ex2;
            }
            catch (IOException innerException3)
            {
                base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "IOException");
                throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.None, innerException3, false);
            }
            catch (DataTooLargeException innerException4)
            {
                base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "AttachmentIsTooLarge");
                PolicyData policyData2 = ADNotificationManager.GetPolicyData(base.User);
                if (policyData2 != null)
                {
                    policyData2.MaxAttachmentSize.ToString();
                }
                else
                {
                    GlobalSettings.MaxDocumentDataSize.ToString(CultureInfo.InvariantCulture);
                }
                throw new AirSyncPermanentException(HttpStatusCode.RequestEntityTooLarge, StatusCode.AttachmentIsTooLarge, innerException4, false);
            }
            finally
            {
                if (folderSyncState != null)
                {
                    folderSyncState.Dispose();
                    folderSyncState = null;
                }
            }
            base.Context.Response.AppendHeader("Content-Type", value);
            return(Command.ExecutionState.Complete);
        }
        internal static string GetAttachment(MailboxSession mailboxSession, StoreObjectId itemId, string attachmentId, Stream outStream, int offset, int count, Unlimited <ByteQuantifiedSize> maxAttachmentSize, bool rightsManagementSupport, out int total)
        {
            string result;

            using (Item item = Item.Bind(mailboxSession, itemId))
            {
                if ("DRMLicense".Equals(attachmentId, StringComparison.OrdinalIgnoreCase))
                {
                    total  = AttachmentHelper.WriteDrmLicenseToStream(item, outStream, offset, count, maxAttachmentSize);
                    result = "application/x-microsoft-rpmsg-message-license";
                }
                else
                {
                    if (rightsManagementSupport)
                    {
                        Command.CurrentCommand.DecodeIrmMessage(item, true);
                    }
                    Attachment attachment = null;
                    try
                    {
                        AttachmentCollection attachmentCollection;
                        if (BodyConversionUtilities.IsMessageRestrictedAndDecoded(item))
                        {
                            attachmentCollection = ((RightsManagedMessageItem)item).ProtectedAttachmentCollection;
                        }
                        else
                        {
                            attachmentCollection = item.AttachmentCollection;
                        }
                        if (attachmentId.Length > 8)
                        {
                            AttachmentId attachmentId2 = EntitySyncItemId.GetAttachmentId(attachmentId);
                            if (attachmentId2 != null)
                            {
                                attachment = attachmentCollection.Open(attachmentId2);
                            }
                        }
                        if (attachment == null)
                        {
                            int num;
                            if (!int.TryParse(attachmentId, NumberStyles.None, CultureInfo.InvariantCulture, out num) || num < 0)
                            {
                                throw new FormatException("Invalid Attachment Index format: " + attachmentId.ToString(CultureInfo.InvariantCulture));
                            }
                            IList <AttachmentHandle> handles = attachmentCollection.GetHandles();
                            if (num < handles.Count)
                            {
                                attachment = attachmentCollection.Open(handles[num]);
                            }
                        }
                        if (attachment == null)
                        {
                            throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentId));
                        }
                        if (BodyConversionUtilities.IsMessageRestrictedAndDecoded(item) && AttachmentHelper.IsProtectedVoiceAttachment(attachment.FileName))
                        {
                            RightsManagedMessageItem rightsManagedMessageItem = item as RightsManagedMessageItem;
                            rightsManagedMessageItem.UnprotectAttachment(attachment.Id);
                            AttachmentId id = attachment.Id;
                            attachment.Dispose();
                            attachment = rightsManagedMessageItem.ProtectedAttachmentCollection.Open(id);
                        }
                        if (!maxAttachmentSize.IsUnlimited && attachment.Size > (long)maxAttachmentSize.Value.ToBytes())
                        {
                            throw new DataTooLargeException(StatusCode.AttachmentIsTooLarge);
                        }
                        result = AttachmentHelper.GetAttachmentItself(attachment, outStream, offset, count, out total);
                    }
                    finally
                    {
                        if (attachment != null)
                        {
                            attachment.Dispose();
                        }
                        if (rightsManagementSupport)
                        {
                            Command.CurrentCommand.SaveLicense(item);
                        }
                    }
                }
            }
            return(result);
        }
        private static string GetAttachmentByUrlCompName(MailboxSession mailboxSession, string attachmentId, Stream outStream, int offset, int count, Unlimited <ByteQuantifiedSize> maxAttachmentSize, out int total)
        {
            attachmentId = "/" + attachmentId;
            int    andCheckLastSlashLocation = AttachmentHelper.GetAndCheckLastSlashLocation(attachmentId, attachmentId);
            string text  = attachmentId.Substring(0, andCheckLastSlashLocation);
            string text2 = attachmentId.Substring(andCheckLastSlashLocation + 1);

            andCheckLastSlashLocation = AttachmentHelper.GetAndCheckLastSlashLocation(text, attachmentId);
            string      propertyValue = text.Substring(0, andCheckLastSlashLocation);
            StoreId     storeId       = null;
            QueryFilter seekFilter    = new ComparisonFilter(ComparisonOperator.Equal, FolderSchema.UrlName, propertyValue);

            using (Folder folder = Folder.Bind(mailboxSession, mailboxSession.GetDefaultFolderId(DefaultFolderType.Root)))
            {
                using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.DeepTraversal, AirSyncUtility.XsoFilters.GetHierarchyFilter, null, AttachmentHelper.folderPropertyIds))
                {
                    if (queryResult.SeekToCondition(SeekReference.OriginBeginning, seekFilter))
                    {
                        object[][] rows = queryResult.GetRows(1);
                        storeId = (rows[0][0] as StoreId);
                    }
                }
            }
            if (storeId == null)
            {
                throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentId));
            }
            AirSyncDiagnostics.TraceDebug <StoreId>(ExTraceGlobals.RequestsTracer, null, "Getting attachment with parentStoreId {0}.", storeId);
            StoreId storeId2 = null;

            seekFilter = new ComparisonFilter(ComparisonOperator.Equal, FolderSchema.UrlName, text);
            using (Folder folder2 = Folder.Bind(mailboxSession, storeId))
            {
                using (QueryResult queryResult2 = folder2.ItemQuery(ItemQueryType.None, null, null, AttachmentHelper.itemPropertyIds))
                {
                    if (queryResult2.SeekToCondition(SeekReference.OriginBeginning, seekFilter))
                    {
                        object[][] rows2 = queryResult2.GetRows(1);
                        storeId2 = (rows2[0][0] as StoreId);
                    }
                }
            }
            if (storeId2 == null)
            {
                throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentId));
            }
            AirSyncDiagnostics.TraceDebug <StoreId>(ExTraceGlobals.RequestsTracer, null, "Getting attachment with itemStoreId {0}.", storeId2);
            PropertyTagPropertyDefinition propertyTagPropertyDefinition = PropertyTagPropertyDefinition.CreateCustom("UrlCompName", 284360734U);
            string attachmentItself;

            using (Item item = Item.Bind(mailboxSession, storeId2))
            {
                AttachmentCollection attachmentCollection = item.AttachmentCollection;
                attachmentCollection.Load(new PropertyDefinition[]
                {
                    propertyTagPropertyDefinition
                });
                AttachmentId attachmentId2 = null;
                foreach (AttachmentHandle handle in attachmentCollection)
                {
                    using (Attachment attachment = attachmentCollection.Open(handle))
                    {
                        if (text2.Equals((string)attachment[propertyTagPropertyDefinition], StringComparison.Ordinal))
                        {
                            attachmentId2 = attachment.Id;
                            break;
                        }
                    }
                }
                if (attachmentId2 == null)
                {
                    foreach (AttachmentHandle handle2 in attachmentCollection)
                    {
                        using (Attachment attachment2 = attachmentCollection.Open(handle2))
                        {
                            string str = (string)attachment2[propertyTagPropertyDefinition];
                            if (text2.EndsWith("_" + str, StringComparison.Ordinal))
                            {
                                attachmentId2 = attachment2.Id;
                                break;
                            }
                        }
                    }
                }
                if (attachmentId2 == null)
                {
                    throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentId));
                }
                AirSyncDiagnostics.TraceDebug <AttachmentId>(ExTraceGlobals.RequestsTracer, null, "Getting attachment with attachment ID {0}.", attachmentId2);
                using (Attachment attachment3 = attachmentCollection.Open(attachmentId2))
                {
                    if (!maxAttachmentSize.IsUnlimited && attachment3.Size > (long)maxAttachmentSize.Value.ToBytes())
                    {
                        throw new DataTooLargeException(StatusCode.AttachmentIsTooLarge);
                    }
                    attachmentItself = AttachmentHelper.GetAttachmentItself(attachment3, outStream, offset, count, out total);
                }
            }
            return(attachmentItself);
        }
 internal static string GetAttachment(MailboxSession mailboxSession, string attachmentId, Stream outStream, Unlimited <ByteQuantifiedSize> maxAttachmentSize, ItemIdMapping idmapping, out int total)
 {
     return(AttachmentHelper.GetAttachment(mailboxSession, attachmentId, outStream, 0, -1, maxAttachmentSize, idmapping, false, out total));
 }