internal static void ReplaceAttachmentContent(string smtpAddress, string cultureName, string ewsAttachmentID, bool isArchive, Stream source)
        {
            ADSessionSettings   adsessionSettings;
            ExchangePrincipal   exchangePrincipal   = WacUtilities.GetExchangePrincipal(smtpAddress, out adsessionSettings, isArchive);
            CultureInfo         cultureInfo         = CultureInfo.GetCultureInfo(cultureName);
            List <AttachmentId> attachmentIds       = new List <AttachmentId>();
            IdHeaderInformation idHeaderInformation = ServiceIdConverter.ConvertFromConcatenatedId(ewsAttachmentID, BasicTypes.Attachment, attachmentIds);

            idHeaderInformation.ToStoreObjectId();
            using (MailboxSession mailboxSession = MailboxSession.OpenAsSystemService(exchangePrincipal, cultureInfo, "Client=OWA;Action=WAC"))
            {
                WacUtilities.ProcessAttachment(mailboxSession, ewsAttachmentID, exchangePrincipal, PropertyOpenMode.Modify, delegate(IExchangePrincipal principal, Attachment attachment, Stream stream, bool anyContentProtected)
                {
                    BinaryReader binaryReader = new BinaryReader(source);
                    stream.Seek(0L, SeekOrigin.Begin);
                    int num       = 10000;
                    int num2      = 0;
                    byte[] buffer = new byte[num];
                    for (;;)
                    {
                        int num3 = binaryReader.Read(buffer, 0, num);
                        num2    += num3;
                        if (num3 == 0)
                        {
                            break;
                        }
                        stream.Write(buffer, 0, num3);
                    }
                    stream.SetLength((long)num2);
                    attachment.Save();
                });
            }
        }
        private static bool TryProcessUnprotectedAttachment(IExchangePrincipal exchangePrincipal, Item item, StreamAttachment streamAttachment, PropertyOpenMode openMode, WacUtilities.AttachmentProcessor attachmentProcessor)
        {
            if (openMode == PropertyOpenMode.Modify)
            {
                item.OpenAsReadWrite();
            }
            bool result;

            using (Stream contentStream = streamAttachment.GetContentStream(openMode))
            {
                bool flag = WacUtilities.IsContentProtected(streamAttachment.FileName, contentStream);
                if (flag)
                {
                    result = false;
                }
                else
                {
                    attachmentProcessor(exchangePrincipal, streamAttachment, contentStream, false);
                    if (openMode == PropertyOpenMode.Modify)
                    {
                        item.Save(SaveMode.NoConflictResolution);
                    }
                    result = true;
                }
            }
            return(result);
        }
Exemple #3
0
        public static WacFileRep Parse(string fileRepAsString)
        {
            byte[]     array      = WacUtilities.FromBase64String(fileRepAsString);
            WacFileRep wacFileRep = null;

            try
            {
                using (MemoryStream memoryStream = new MemoryStream(array))
                {
                    using (BinaryReader binaryReader = new BinaryReader(memoryStream, new UTF8Encoding()))
                    {
                        string   text                    = binaryReader.ReadString();
                        DateTime creationTime            = new DateTime(binaryReader.ReadInt64());
                        bool     directFileAccessEnabled = binaryReader.ReadBoolean();
                        bool     externalServicesEnabled = binaryReader.ReadBoolean();
                        bool     wacOMEXEnabled          = binaryReader.ReadBoolean();
                        bool     isEdit                  = binaryReader.ReadBoolean();
                        bool     isArchive               = binaryReader.ReadBoolean();
                        wacFileRep = new WacFileRep(new SecurityIdentifier(text), creationTime, directFileAccessEnabled, externalServicesEnabled, wacOMEXEnabled, isEdit, isArchive);
                        if (!wacFileRep.LogonSid.IsAccountSid())
                        {
                            throw new OwaInvalidRequestException("WacFileRep contained an invalid SecurityIdentifier: " + text);
                        }
                    }
                }
            }
            catch (EndOfStreamException)
            {
                throw new OwaInvalidRequestException("Unable to parse WacRequest. (" + array.Length.ToString() + " bytes)");
            }
            return(wacFileRep);
        }
Exemple #4
0
 public void Clean(IList <string> rootDirectories)
 {
     if (this.IsCleaningOverdue())
     {
         lock (CobaltStoreCleaner.syncObject)
         {
             if (this.IsCleaningOverdue())
             {
                 SimulatedWebRequestContext.ExecuteWithoutUserContext("WAC.CleanCobaltStore", delegate(RequestDetailsLogger logger)
                 {
                     WacUtilities.SetEventId(logger, "WAC.CleanCobaltStore");
                     foreach (string text in rootDirectories)
                     {
                         CobaltStoreCleaner.ValidatePath(text);
                         try
                         {
                             this.CleanRootDirectory(text);
                         }
                         catch (DirectoryNotFoundException)
                         {
                         }
                     }
                 });
             }
         }
     }
 }
        private static bool MessageIsDraft(WacRequest wacRequest)
        {
            ADSessionSettings adsessionSettings;
            ExchangePrincipal exchangePrincipal = WacUtilities.GetExchangePrincipal(wacRequest, out adsessionSettings, wacRequest.WacFileRep.IsArchive);
            CultureInfo       cultureInfo       = CultureInfo.GetCultureInfo(wacRequest.CultureName);

            if (exchangePrincipal.RecipientTypeDetails == RecipientTypeDetails.PublicFolder)
            {
                return(false);
            }
            bool result;

            using (MailboxSession mailboxSession = MailboxSession.OpenAsSystemService(exchangePrincipal, cultureInfo, "Client=OWA;Action=WAC"))
            {
                IdConverterDependencies converterDependencies = new IdConverterDependencies.FromRawData(false, false, null, null, wacRequest.MailboxSmtpAddress.ToString(), null, mailboxSession, null);
                using (AttachmentHandler.IAttachmentRetriever attachmentRetriever = AttachmentRetriever.CreateInstance(wacRequest.EwsAttachmentId, converterDependencies))
                {
                    Item       rootItem   = attachmentRetriever.RootItem;
                    Attachment attachment = attachmentRetriever.Attachment;
                    string     text;
                    string     text2;
                    result = WacUtilities.ItemIsMessageDraft(rootItem, attachment, out text, out text2);
                }
            }
            return(result);
        }
        // Token: 0x06000227 RID: 551 RVA: 0x00008860 File Offset: 0x00006A60
        public static bool IsWacActiveMonitoringRequest(HttpRequest request, HttpResponse response)
        {
            if (string.Equals(request.QueryString["owaatt"], "Exch_WopiTest", StringComparison.InvariantCultureIgnoreCase))
            {
                switch (WacRequest.GetRequestType(request))
                {
                case WacRequestType.CheckFile:
                {
                    DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(WacCheckFileResponse));
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        dataContractJsonSerializer.WriteObject(memoryStream, WacActiveMonitoringHandler.DefaultCheckFileResponse());
                        memoryStream.Position = 0L;
                        response.OutputStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
                        return(true);
                    }
                    break;
                }

                case WacRequestType.GetFile:
                    break;

                default:
                    return(false);
                }
                using (MemoryStream memoryStream2 = new MemoryStream(WacActiveMonitoringHandler.fileContentBytes))
                {
                    WacUtilities.WriteStreamBody(response, memoryStream2);
                    return(true);
                }
                return(false);
            }
            return(false);
        }
        public static void ProcessAttachment(IStoreSession session, string ewsAttachmentId, IExchangePrincipal exchangePrincipal, PropertyOpenMode openMode, WacUtilities.AttachmentProcessor attachmentProcessor)
        {
            IdConverterDependencies converterDependencies = new IdConverterDependencies.FromRawData(false, false, null, null, exchangePrincipal.MailboxInfo.PrimarySmtpAddress.ToString(), session as MailboxSession, session as MailboxSession, session as PublicFolderSession);

            using (AttachmentHandler.IAttachmentRetriever attachmentRetriever = AttachmentRetriever.CreateInstance(ewsAttachmentId, converterDependencies))
            {
                bool flag = WacUtilities.IsIrmRestricted(attachmentRetriever.RootItem);
                if (openMode == PropertyOpenMode.Modify)
                {
                    attachmentRetriever.RootItem.OpenAsReadWrite();
                }
                StreamAttachment streamAttachment = attachmentRetriever.Attachment as StreamAttachment;
                if (streamAttachment == null)
                {
                    attachmentProcessor(exchangePrincipal, attachmentRetriever.Attachment, null, flag);
                }
                else
                {
                    using (Stream contentStream = streamAttachment.GetContentStream(openMode))
                    {
                        bool flag2 = WacUtilities.IsContentProtected(attachmentRetriever.Attachment.FileName, contentStream);
                        attachmentProcessor(exchangePrincipal, streamAttachment, contentStream, flag || flag2);
                        if (openMode == PropertyOpenMode.Modify)
                        {
                            attachmentRetriever.RootItem.Save(SaveMode.NoConflictResolution);
                        }
                    }
                }
            }
        }
        // Token: 0x060002C9 RID: 713 RVA: 0x0000A280 File Offset: 0x00008480
        public static WacRequest ParseWacRequest(string mailboxSmtpAddress, HttpRequest request)
        {
            if (request == null)
            {
                throw new OwaInvalidRequestException("Request object is null");
            }
            if (!UrlUtilities.IsWacRequest(request))
            {
                throw new OwaInvalidRequestException("Expected a WAC request, but got this instead: " + request.Url.AbsoluteUri);
            }
            WacRequestType requestType       = WacRequest.GetRequestType(request);
            string         text              = request.QueryString["access_token"] ?? string.Empty;
            string         exchangeSessionId = WacUtilities.GetExchangeSessionId(text);
            string         ewsAttachmentId;

            WacRequest.ParseAccessToken(text, out ewsAttachmentId);
            string     fileRepAsString = request.QueryString["owaatt"] ?? string.Empty;
            WacFileRep fileRep         = WacFileRep.Parse(fileRepAsString);
            string     value           = request.Headers["X-WOPI-PerfTraceRequested"] ?? string.Empty;
            bool       perfTraceRequested;

            if (!bool.TryParse(value, out perfTraceRequested))
            {
                perfTraceRequested = false;
            }
            return(new WacRequest(requestType, fileRep, (SmtpAddress)mailboxSmtpAddress, exchangeSessionId, ewsAttachmentId, request.QueryString["ui"] ?? "en-us", request.Headers["X-WOPI-InterfaceVersion"] ?? string.Empty, request.Headers["X-WOPI-MachineName"] ?? string.Empty, perfTraceRequested, request.Headers["X-WOPI-CorrelationID"] ?? string.Empty));
        }
 private static void ProcessGetFileRequest(HttpContext context, WacRequest wacRequest, RequestDetailsLogger logger)
 {
     WacRequestHandler.UpdateAttachment(wacRequest, logger);
     WacRequestHandler.ProcessAttachment(wacRequest, PropertyOpenMode.ReadOnly, delegate(IExchangePrincipal exchangePrincipal, Attachment attachment, Stream stream, bool contentProtected)
     {
         WacUtilities.WriteStreamBody(context.Response, stream);
     });
 }
 private static void EnsureLocalServerNameAndVersion()
 {
     if (string.IsNullOrEmpty(WacUtilities.localServerName) || string.IsNullOrEmpty(WacUtilities.localServerVersion))
     {
         ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.FullyConsistent, ADSessionSettings.FromRootOrgScopeSet(), 599, "EnsureLocalServerNameAndVersion", "f:\\15.00.1497\\sources\\dev\\clients\\src\\Owa2\\Server\\Core\\attachment\\WacUtilities.cs");
         Server server = topologyConfigurationSession.FindLocalServer();
         WacUtilities.localServerName    = server.Fqdn;
         WacUtilities.localServerVersion = WacUtilities.ConvertVersionNumberToString(server.VersionNumber);
     }
 }
Exemple #11
0
 // Token: 0x0600019F RID: 415 RVA: 0x0000706A File Offset: 0x0000526A
 private void TimerCallback(object unused)
 {
     SimulatedWebRequestContext.ExecuteWithoutUserContext("WAC.AutoSave", delegate(RequestDetailsLogger logger)
     {
         WacUtilities.SetEventId(logger, "WAC.AutoSave");
         logger.ActivityScope.SetProperty(OwaServerLogger.LoggerData.PrimarySmtpAddress, this.smtpAddress);
         logger.ActivityScope.SetProperty(WacRequestHandlerMetadata.ExchangeSessionId, this.exchangeSessionId);
         this.SaveAndLogExceptions(logger);
     });
 }
        private static void UpdateAttachment(WacRequest wacRequest, RequestDetailsLogger logger)
        {
            string           mailboxSmtpAddress = wacRequest.MailboxSmtpAddress.ToString();
            string           ewsAttachmentId    = wacRequest.EwsAttachmentId;
            CobaltStoreSaver cobaltStoreSaver;

            if (WacUtilities.ShouldUpdateAttachment(mailboxSmtpAddress, ewsAttachmentId, out cobaltStoreSaver))
            {
                logger.Set(WacRequestHandlerMetadata.Updated, true);
                cobaltStoreSaver.SaveAndLogExceptions(logger);
                return;
            }
            logger.Set(WacRequestHandlerMetadata.Updated, false);
        }
Exemple #13
0
        // Token: 0x06000205 RID: 517 RVA: 0x00007F14 File Offset: 0x00006114
        private bool TryExecuteWithNewLogger(out Dictionary <Guid, string> result)
        {
            Dictionary <Guid, string> paths = null;

            SimulatedWebRequestContext.ExecuteWithoutUserContext("WAC.MdbCacheUpdate", delegate(RequestDetailsLogger logger)
            {
                WacUtilities.SetEventId(logger, "WAC.MdbCacheUpdate");
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    paths = this.ExecuteQuery(logger);
                });
            });
            result = paths;
            return(result != null);
        }
        // Token: 0x06001AD7 RID: 6871 RVA: 0x00065FAC File Offset: 0x000641AC
        private static WacAttachmentType GetResultForStreamAttachment(CallContext callContext, UserContext userContext, ConfigurationContext configurationContext, AttachmentPolicy attachmentPolicy, bool isPublicLogon, string cultureName, bool isEdit, IStreamAttachment attachment, string attachmentExtension, AttachmentIdType attachmentIdType, bool isInDraft, IStoreSession storeSession, string mailboxSmtpAddress, bool isArchive)
        {
            WacFileRep  wacFileRep = GetWacAttachmentInfo.CreateWacFileRep(callContext, configurationContext, attachmentPolicy, isPublicLogon, isEdit, isArchive);
            HttpRequest request    = callContext.HttpContext.Request;
            string      text;
            string      arg;

            GetWacAttachmentInfo.GenerateWopiSrcUrl(request, wacFileRep, mailboxSmtpAddress, out text, out arg);
            if (text == null)
            {
                throw new OwaInvalidOperationException("WOPI URL is null.");
            }
            string      id                = attachmentIdType.Id;
            TokenResult oauthToken        = GetWacAttachmentInfo.GetOAuthToken(id, userContext, mailboxSmtpAddress, text);
            string      exchangeSessionId = WacUtilities.GetExchangeSessionId(oauthToken.TokenString);

            callContext.ProtocolLog.Set(GetWacAttachmentInfoMetadata.ExchangeSessionId, exchangeSessionId);
            SecurityIdentifier effectiveCallerSid = callContext.EffectiveCallerSid;

            CachedAttachmentInfo.GetInstance(mailboxSmtpAddress, id, exchangeSessionId, effectiveCallerSid, cultureName);
            string wacUrl = GetWacAttachmentInfo.GetWacUrl(isEdit, cultureName, attachmentExtension);

            if (string.IsNullOrEmpty(wacUrl))
            {
                throw new OwaInvalidRequestException(string.Format("Wac Base Url is null for this given extension {0} and culture {1}", attachmentExtension, cultureName));
            }
            new Uri(wacUrl);
            string format = "{0}WOPISrc={1}&access_token={2}";
            string arg2   = HttpUtility.UrlEncode(oauthToken.TokenString);
            string text2  = string.Format(format, wacUrl, HttpUtility.UrlEncode(text), arg2);
            string value  = string.Format(format, wacUrl, arg, arg2);

            callContext.ProtocolLog.Set(GetWacAttachmentInfoMetadata.WacUrl, value);
            if (!Uri.IsWellFormedUriString(text2, UriKind.Absolute))
            {
                throw new OwaInvalidOperationException("The WAC Iframe URL that was generated is not a well formed URI: " + text2);
            }
            return(new WacAttachmentType
            {
                AttachmentId = attachmentIdType,
                IsEdit = isEdit,
                IsInDraft = isInDraft,
                WacUrl = text2,
                Status = WacAttachmentStatus.Success
            });
        }
 internal static void OnCacheEntryExpired(CachedAttachmentInfo attachmentInfo)
 {
     SimulatedWebRequestContext.ExecuteWithoutUserContext("WAC.CacheEntryExpired", delegate(RequestDetailsLogger logger)
     {
         WacUtilities.SetEventId(logger, "WAC.CacheEntryExpired");
         logger.ActivityScope.SetProperty(OwaServerLogger.LoggerData.PrimarySmtpAddress, attachmentInfo.MailboxSmtpAddress);
         CobaltStore store = attachmentInfo.CobaltStore;
         ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
         {
             store.Saver.SaveAndLogExceptions(logger);
         });
         store.Dispose();
         Exception exception = adoperationResult.Exception;
         if (exception != null)
         {
             logger.ActivityScope.SetProperty(ServiceCommonMetadata.GenericErrors, exception.ToString());
         }
     });
 }
 // Token: 0x06000229 RID: 553 RVA: 0x00008944 File Offset: 0x00006B44
 private static void Initialize()
 {
     if (WacActiveMonitoringHandler.initialized)
     {
         return;
     }
     lock (WacActiveMonitoringHandler.initializationLock)
     {
         if (!WacActiveMonitoringHandler.initialized)
         {
             WacActiveMonitoringHandler.fileContentBytes = Encoding.Default.GetBytes("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");
             using (MemoryStream memoryStream = new MemoryStream(WacActiveMonitoringHandler.fileContentBytes))
             {
                 WacActiveMonitoringHandler.shaHash256ForContentStream = WacUtilities.GenerateSHA256HashForStream(memoryStream);
             }
             WacActiveMonitoringHandler.defaultMonitoringResponse = new WacCheckFileResponse("DummyAttachment", 1911L, WacActiveMonitoringHandler.shaHash256ForContentStream, "https://DummyWopiDownloadUrl", "DummyOwnerId", "DummyOwnerId", "DummyOwnerId", "DummyOwnerId", false, true, true, false);
             Thread.MemoryBarrier();
             WacActiveMonitoringHandler.initialized = true;
         }
     }
 }
        private static void ProcessCheckFileRequest(HttpContext context, WacRequest wacRequest, RequestDetailsLogger logger)
        {
            WacRequestHandler.UpdateAttachment(wacRequest, logger);
            CachedAttachmentInfo cachedAttachmentInfo = WacRequestHandler.GetCachedAttachmentInfo(wacRequest);
            string attachmentStreamHash   = null;
            long   attachmentStreamLength = 0L;
            string attachmentFileName     = null;
            string attachmentExtension    = null;
            bool   attachmentIsProtected  = false;

            WacRequestHandler.ProcessAttachment(wacRequest, PropertyOpenMode.ReadOnly, delegate(IExchangePrincipal exchangePrincipal, Attachment attachment, Stream stream, bool isProtected)
            {
                attachmentStreamHash   = WacUtilities.GenerateSHA256HashForStream(stream);
                attachmentStreamLength = stream.Length;
                attachmentFileName     = attachment.FileName;
                attachmentExtension    = attachment.FileExtension;
                attachmentIsProtected  = isProtected;
            });
            WacFileRep           wacFileRep           = wacRequest.WacFileRep;
            string               downloadUrl          = WacRequestHandler.GetDownloadUrl(context.Request, wacFileRep, wacRequest);
            WacCheckFileResponse wacCheckFileResponse = new WacCheckFileResponse(attachmentFileName, attachmentStreamLength, attachmentStreamHash, downloadUrl, cachedAttachmentInfo.MailboxSmtpAddress, cachedAttachmentInfo.LogonSmtpAddress, cachedAttachmentInfo.LogonDisplayName, cachedAttachmentInfo.LogonPuid, attachmentIsProtected, wacFileRep.DirectFileAccessEnabled, wacFileRep.WacExternalServicesEnabled, wacFileRep.OMEXEnabled);

            if (wacFileRep.IsEdit)
            {
                wacCheckFileResponse.UserCanWrite    = true;
                wacCheckFileResponse.ReadOnly        = false;
                wacCheckFileResponse.SupportsUpdate  = true;
                wacCheckFileResponse.SupportsLocks   = true;
                wacCheckFileResponse.SupportsCobalt  = true;
                wacCheckFileResponse.SupportsFolders = true;
            }
            DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(WacCheckFileResponse));

            using (MemoryStream memoryStream = new MemoryStream())
            {
                dataContractJsonSerializer.WriteObject(memoryStream, wacCheckFileResponse);
                memoryStream.Position = 0L;
                context.Response.OutputStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
            }
        }
        private static void ProcessAttachment(WacRequest wacRequest, PropertyOpenMode openMode, WacUtilities.AttachmentProcessor attachmentProcessor)
        {
            ADSessionSettings adSessionSettings;
            ExchangePrincipal exchangePrincipal = WacUtilities.GetExchangePrincipal(wacRequest, out adSessionSettings, wacRequest.WacFileRep.IsArchive);

            WacRequestHandler.ProcessUsingBudget(wacRequest.WacFileRep.LogonSid, delegate
            {
                string ewsAttachmentId  = wacRequest.EwsAttachmentId;
                CultureInfo cultureInfo = CultureInfo.GetCultureInfo(wacRequest.CultureName);
                string clientInfoString = "Client=OWA;Action=WAC";
                if (exchangePrincipal.RecipientTypeDetails.HasFlag(RecipientTypeDetails.PublicFolder) || exchangePrincipal.RecipientTypeDetails.HasFlag(RecipientTypeDetails.PublicFolderMailbox))
                {
                    using (PublicFolderSession publicFolderSession = PublicFolderSession.OpenAsAdmin(null, exchangePrincipal, null, cultureInfo, clientInfoString, null))
                    {
                        WacUtilities.ProcessAttachment(publicFolderSession, ewsAttachmentId, exchangePrincipal, openMode, attachmentProcessor);
                        return;
                    }
                }
                using (MailboxSession mailboxSession = MailboxSession.OpenAsSystemService(exchangePrincipal, cultureInfo, clientInfoString))
                {
                    WacUtilities.ProcessAttachment(mailboxSession, ewsAttachmentId, exchangePrincipal, openMode, attachmentProcessor);
                }
            }, adSessionSettings);
        }
        protected override Stream InternalExecute()
        {
            UserContext          userContext          = UserContextManager.GetUserContext(HttpContext.Current, CallContext.Current.EffectiveCaller, true);
            ConfigurationContext configurationContext = new ConfigurationContext(userContext);
            string           mailboxSmtpAddress       = userContext.MailboxIdentity.PrimarySmtpAddress.ToString();
            CobaltStoreSaver cobaltStoreSaver;

            if (WacUtilities.ShouldUpdateAttachment(mailboxSmtpAddress, this.id, out cobaltStoreSaver))
            {
                base.CallContext.ProtocolLog.Set(GetAttachmentMetadata.Updated, true);
                cobaltStoreSaver.SaveAndLogExceptions(base.CallContext.ProtocolLog);
            }
            else
            {
                base.CallContext.ProtocolLog.Set(GetAttachmentMetadata.Updated, false);
            }
            AttachmentHandler attachmentHandler = new AttachmentHandler(this.id, this.webOperationContext, base.CallContext, configurationContext);

            attachmentHandler.IsImagePreview = this.isImagePreview;
            Stream result;

            try
            {
                using (AttachmentHandler.IAttachmentRetriever attachmentRetriever = AttachmentRetriever.CreateInstance(this.id, base.CallContext))
                {
                    AttachmentHandler.IAttachmentPolicyChecker policyChecker = AttachmentPolicyChecker.CreateInstance(configurationContext.AttachmentPolicy);
                    Stream attachmentStream = attachmentHandler.GetAttachmentStream(attachmentRetriever, policyChecker, this.asDataUri);
                    GetAttachment.EliminateGzFileDoubleCompression(attachmentRetriever);
                    base.CallContext.OnDisposed += delegate(object sender, EventArgs args)
                    {
                        if (attachmentStream != null)
                        {
                            attachmentStream.Dispose();
                        }
                    };
                    if (attachmentRetriever.Attachment != null)
                    {
                        base.CallContext.ProtocolLog.Set(GetAttachmentMetadata.Extension, attachmentRetriever.Attachment.FileExtension);
                        base.CallContext.ProtocolLog.Set(GetAttachmentMetadata.Length, attachmentRetriever.Attachment.Size);
                    }
                    result = attachmentStream;
                }
            }
            catch (InvalidStoreIdException innerException)
            {
                throw new OwaInvalidRequestException("Invalid ID, " + this.GetParametersForLogging(), innerException);
            }
            catch (InvalidIdMalformedException innerException2)
            {
                throw new OwaInvalidRequestException("Malformed ID, " + this.GetParametersForLogging(), innerException2);
            }
            catch (CannotOpenFileAttachmentException)
            {
                this.webOperationContext.StatusCode = HttpStatusCode.NotFound;
                result = null;
            }
            catch (ObjectNotFoundException)
            {
                this.webOperationContext.StatusCode = HttpStatusCode.NotFound;
                result = null;
            }
            return(result);
        }
Exemple #20
0
        private string GetFilePath(string fileName)
        {
            string path = WacUtilities.GetCurrentTimeForFileName() + "-" + fileName;

            return(Path.Combine(this.workingDirectory, path));
        }
 private static void ReplaceAttachmentContent(Stream stream, WacRequest wacRequest)
 {
     WacUtilities.ReplaceAttachmentContent(wacRequest.MailboxSmtpAddress.ToString(), wacRequest.CultureName, wacRequest.EwsAttachmentId, wacRequest.WacFileRep.IsArchive, stream);
 }
        // Token: 0x06001ACF RID: 6863 RVA: 0x0006569C File Offset: 0x0006389C
        public static WacAttachmentType Execute(CallContext callContext, IStoreSession originalAttachmentSession, IItem originalAttachmentItem, IAttachment originalAttachment, string draftId, string ewsAttachmentId, bool isEdit)
        {
            MdbCache.GetInstance().BeginAsyncUpdate();
            UserContext userContext = UserContextManager.GetUserContext(callContext.HttpContext, callContext.EffectiveCaller, true);

            if (userContext == null)
            {
                throw new OwaInvalidRequestException("Unable to determine user context.");
            }
            if (!userContext.IsWacEditingEnabled)
            {
                isEdit = false;
            }
            ConfigurationContext configurationContext = new ConfigurationContext(userContext);
            AttachmentPolicy     attachmentPolicy     = configurationContext.AttachmentPolicy;
            bool isPublicLogon = userContext.IsPublicLogon;

            if (!attachmentPolicy.GetWacViewingEnabled(isPublicLogon))
            {
                throw new OwaOperationNotSupportedException("WAC viewing not enabled for the current user");
            }
            MailboxSession mailboxSession = null;
            StoreObjectId  draftObjectId  = null;

            if (draftId != null)
            {
                IdAndSession idAndSession = GetWacAttachmentInfo.GetIdAndSession(callContext, draftId, false);
                mailboxSession = (idAndSession.Session as MailboxSession);
                draftObjectId  = StoreId.EwsIdToStoreObjectId(draftId);
                if (mailboxSession == null)
                {
                    throw new OwaOperationNotSupportedException("We need a MailboxSession to create the draft, but this a " + idAndSession.Session.GetType().Name);
                }
            }
            string text = originalAttachmentSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString();
            string primarySmtpAddress        = callContext.EffectiveCaller.PrimarySmtpAddress;
            RequestDetailsLogger protocolLog = callContext.ProtocolLog;

            protocolLog.Set(GetWacAttachmentInfoMetadata.LogonSmtpAddress, primarySmtpAddress);
            protocolLog.Set(GetWacAttachmentInfoMetadata.MailboxSmtpAddress, text);
            protocolLog.Set(GetWacAttachmentInfoMetadata.Edit, isEdit);
            protocolLog.Set(GetWacAttachmentInfoMetadata.Extension, originalAttachment.FileExtension);
            protocolLog.Set(GetWacAttachmentInfoMetadata.DraftProvided, draftId != null);
            string                 displayName = callContext.AccessingPrincipal.MailboxInfo.DisplayName;
            XSOFactory             factory     = new XSOFactory();
            AttachmentDataProvider defaultUploadDataProvider = new AttachmentDataProviderManager().GetDefaultUploadDataProvider(callContext);
            IReferenceAttachment   referenceAttachment       = originalAttachment as IReferenceAttachment;

            if (referenceAttachment != null)
            {
                GetWacAttachmentInfo.LogReferenceAttachmentProperties(protocolLog, referenceAttachment.ProviderEndpointUrl, GetWacAttachmentInfoMetadata.OriginalReferenceAttachmentServiceUrl, referenceAttachment.AttachLongPathName, GetWacAttachmentInfoMetadata.OriginalReferenceAttachmentUrl);
            }
            if (defaultUploadDataProvider != null)
            {
                protocolLog.Set(GetWacAttachmentInfoMetadata.AttachmentDataProvider, defaultUploadDataProvider.ToString());
            }
            WacAttachmentType wacAttachmentType;

            try
            {
                using (GetWacAttachmentInfo.Implementation implementation = new GetWacAttachmentInfo.Implementation(defaultUploadDataProvider, factory, originalAttachmentSession, originalAttachmentSession.MailboxOwner.ModernGroupType, originalAttachmentItem, originalAttachment, ewsAttachmentId, mailboxSession, draftObjectId, isEdit, displayName, (IStoreSession session, StoreId itemId, AttachmentId attachmentId) => new IdAndSession(itemId, (StoreSession)session)
                {
                    AttachmentIds =
                    {
                        attachmentId
                    }
                }.GetConcatenatedId().Id))
                {
                    implementation.Execute();
                    protocolLog.Set(GetWacAttachmentInfoMetadata.OriginalAttachmentType, implementation.OriginalAttachmentType);
                    protocolLog.Set(GetWacAttachmentInfoMetadata.ResultAttachmentType, implementation.ResultAttachmentType);
                    protocolLog.Set(GetWacAttachmentInfoMetadata.ResultAttachmentCreation, implementation.ResultAttachmentCreation);
                    if (implementation.ResultAttachmentType == AttachmentType.Reference)
                    {
                        IMailboxInfo mailboxInfo       = originalAttachmentSession.MailboxOwner.MailboxInfo;
                        string       mailboxAddress    = mailboxInfo.PrimarySmtpAddress.ToString();
                        StoreId      id                = originalAttachmentItem.Id;
                        BaseItemId   itemIdFromStoreId = IdConverter.GetItemIdFromStoreId(id, new MailboxId(mailboxInfo.MailboxGuid));
                        string       exchangeSessionId = WacUtilities.GetExchangeSessionId(default(Guid).ToString());
                        protocolLog.Set(GetWacAttachmentInfoMetadata.ExchangeSessionId, exchangeSessionId);
                        wacAttachmentType = GetWacAttachmentInfo.GetResultForReferenceAttachment(callContext, userContext, implementation, defaultUploadDataProvider, mailboxAddress, itemIdFromStoreId, originalAttachment.FileName, isEdit, displayName, exchangeSessionId, protocolLog);
                    }
                    else
                    {
                        if (implementation.ResultAttachmentType != AttachmentType.Stream)
                        {
                            throw new OwaNotSupportedException("Unsupported attachment type " + implementation.ResultAttachmentType);
                        }
                        AttachmentIdType ewsAttachmentIdType = GetWacAttachmentInfo.GetEwsAttachmentIdType(callContext, implementation.ResultItemId, implementation.ResultAttachmentId);
                        wacAttachmentType = GetWacAttachmentInfo.GetResultForStreamAttachment(callContext, userContext, configurationContext, attachmentPolicy, isPublicLogon, Thread.CurrentThread.CurrentCulture.Name, isEdit, (IStreamAttachment)implementation.ResultAttachment, implementation.ResultAttachmentExtension, ewsAttachmentIdType, implementation.ResultIsInDraft, implementation.ResultStoreSession, text, originalAttachmentSession.MailboxOwner.MailboxInfo.IsArchive);
                    }
                }
            }
            catch (ServerException exception)
            {
                wacAttachmentType = GetWacAttachmentInfo.HandleException(protocolLog, isEdit, exception, WacAttachmentStatus.UploadFailed);
            }
            catch (GetWacAttachmentInfo.AttachmentUploadException exception2)
            {
                wacAttachmentType = GetWacAttachmentInfo.HandleException(protocolLog, isEdit, exception2, WacAttachmentStatus.UploadFailed);
            }
            catch (RightsManagementPermanentException exception3)
            {
                wacAttachmentType = GetWacAttachmentInfo.HandleException(protocolLog, isEdit, exception3, WacAttachmentStatus.ProtectedByUnsupportedIrm);
            }
            catch (AttachmentProtectionException exception4)
            {
                wacAttachmentType = GetWacAttachmentInfo.HandleException(protocolLog, isEdit, exception4, WacAttachmentStatus.ProtectedByUnsupportedIrm);
            }
            catch (ObjectNotFoundException exception5)
            {
                wacAttachmentType = GetWacAttachmentInfo.HandleException(protocolLog, isEdit, exception5, WacAttachmentStatus.NotFound);
            }
            catch (OwaInvalidRequestException exception6)
            {
                wacAttachmentType = GetWacAttachmentInfo.HandleException(protocolLog, isEdit, exception6, WacAttachmentStatus.InvalidRequest);
            }
            catch (WacDiscoveryFailureException exception7)
            {
                wacAttachmentType = GetWacAttachmentInfo.HandleException(protocolLog, isEdit, exception7, WacAttachmentStatus.WacDiscoveryFailed);
            }
            catch (WebException exception8)
            {
                wacAttachmentType = GetWacAttachmentInfo.HandleException(protocolLog, isEdit, exception8, WacAttachmentStatus.AttachmentDataProviderError);
            }
            if (wacAttachmentType == null)
            {
                throw new OwaInvalidOperationException("There is no reason known for code to reach here without throwing an unhandled exception elsewhere");
            }
            protocolLog.Set(GetWacAttachmentInfoMetadata.Status, wacAttachmentType.Status.ToString());
            return(wacAttachmentType);
        }
        public static void WriteStreamBody(HttpResponse response, Stream contentStream)
        {
            Stream outputStream = response.OutputStream;

            WacUtilities.WriteStreamBody(outputStream, contentStream);
        }
 public static ExchangePrincipal GetExchangePrincipal(WacRequest wacRequest, out ADSessionSettings adSessionSettings, bool isArchive)
 {
     return(WacUtilities.GetExchangePrincipal(wacRequest.MailboxSmtpAddress.ToString(), out adSessionSettings, isArchive));
 }
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            RequestDetailsLogger logger = OwaApplication.GetRequestDetailsLogger;
            string text = context.Request.QueryString["UserEmail"];

            logger.ActivityScope.SetProperty(OwaServerLogger.LoggerData.PrimarySmtpAddress, text);
            WacUtilities.SetEventId(logger, "WAC.BadRequest");
            context.Response.TrySkipIisCustomErrors = true;
            try
            {
                if (WacActiveMonitoringHandler.IsWacActiveMonitoringRequest(context.Request, context.Response))
                {
                    WacUtilities.SetEventId(logger, "WAC.ActiveMonitoring");
                }
                else
                {
                    WacRequest wacRequest = WacRequest.ParseWacRequest(text, context.Request);
                    WacRequestHandler.SetCommonResponseHeaders(wacRequest, context.Response);
                    string text2 = wacRequest.GetElapsedTime().TotalHours.ToString("0.00");
                    logger.ActivityScope.SetProperty(WacRequestHandlerMetadata.SessionElapsedTime, text2);
                    if (wacRequest.IsExpired())
                    {
                        throw new OwaInvalidRequestException(string.Concat(new object[]
                        {
                            "Can't process ",
                            wacRequest.RequestType,
                            " request because the Url has expired. Hours since start: ",
                            text2
                        }));
                    }
                    logger.Set(WacRequestHandlerMetadata.ExchangeSessionId, wacRequest.ExchangeSessionId);
                    switch (wacRequest.RequestType)
                    {
                    case WacRequestType.CheckFile:
                        WacUtilities.SetEventId(logger, "WAC.CheckFile");
                        WacRequestHandler.ProcessCheckFileRequest(context, wacRequest, logger);
                        goto IL_28B;

                    case WacRequestType.GetFile:
                        WacUtilities.SetEventId(logger, "WAC.GetFile");
                        WacRequestHandler.ProcessGetFileRequest(context, wacRequest, logger);
                        goto IL_28B;

                    case WacRequestType.Lock:
                        WacUtilities.SetEventId(logger, "WAC.Lock");
                        WacRequestHandler.IncrementLockCount(wacRequest);
                        goto IL_28B;

                    case WacRequestType.UnLock:
                        WacUtilities.SetEventId(logger, "WAC.Unlock");
                        WacRequestHandler.DecrementLockCount(wacRequest);
                        goto IL_28B;

                    case WacRequestType.RefreshLock:
                        WacUtilities.SetEventId(logger, "WAC.RefreshLock");
                        goto IL_28B;

                    case WacRequestType.PutFile:
                        WacUtilities.SetEventId(logger, "WAC.PutFile");
                        WacRequestHandler.ReplaceAttachmentContent(context.Request.InputStream, wacRequest);
                        goto IL_28B;

                    case WacRequestType.Cobalt:
                        WacUtilities.SetEventId(logger, "WAC.Cobalt");
                        WacRequestHandler.ProcessCobaltRequest(context, wacRequest, delegate(Enum key, string value)
                        {
                            logger.ActivityScope.SetProperty(key, value);
                        });
                        goto IL_28B;

                    case WacRequestType.DeleteFile:
                        WacUtilities.SetEventId(logger, "WAC.DeleteFile");
                        throw new OwaInvalidRequestException("Exchange does not support WAC's DeleteFile operation.");
                    }
                    WacUtilities.SetEventId(logger, "WAC.Unknown");
                    throw new OwaInvalidRequestException("Invalid request type");
                    IL_28B :;
                }
            }
            catch (Exception ex)
            {
                logger.ActivityScope.SetProperty(ServiceCommonMetadata.GenericErrors, ex.ToString());
                logger.ActivityScope.SetProperty(WacRequestHandlerMetadata.RequestUrl, context.Request.Url.ToString());
                logger.ActivityScope.SetProperty(WacRequestHandlerMetadata.UserAgent, context.Request.UserAgent);
                context.Response.Headers["X-WOPI-ServerError"] = ex.ToString();
                if (ex is OwaInvalidRequestException || ex is OwaOperationNotSupportedException || ex is OverBudgetException)
                {
                    context.Response.StatusCode = 404;
                }
                else
                {
                    context.Response.StatusCode = 500;
                }
            }
            finally
            {
                logger.ActivityScope.SetProperty(WacRequestHandlerMetadata.WopiServerName, context.Request.Headers["X-WOPI-ServerVersion"]);
                logger.ActivityScope.SetProperty(WacRequestHandlerMetadata.WopiClientVersion, context.Request.Headers["X-WOPI-InterfaceVersion"]);
                logger.ActivityScope.SetProperty(WacRequestHandlerMetadata.WopiCorrelationId, context.Request.Headers["X-WOPI-CorrelationID"]);
            }
        }