Example #1
0
 public static void ThrowIfRightsTemplatesInvalid(IEnumerable <string> templates, string tpdName, TrustedPublishingDomainImportUtilities tpdImportUtilities, Uri intranetLicensingUrl, Uri extranetLicensingUrl, out object failureTarget)
 {
     failureTarget = null;
     if (templates != null)
     {
         RmsUtil.ThrowIfStringParameterNullOrEmpty(tpdName, "tpdName");
         RmsUtil.ThrowIfParameterNull(tpdImportUtilities, "tpdImportUtilities");
         RmsUtil.ThrowIfParameterNull(intranetLicensingUrl, "intranetLicensingUrl");
         RmsUtil.ThrowIfParameterNull(extranetLicensingUrl, "extranetLicensingUrl");
         foreach (string template in templates)
         {
             Uri  templateDistributionPoint;
             Uri  templateDistributionPoint2;
             Guid templateGuid;
             try
             {
                 DrmClientUtils.ParseTemplate(template, out templateDistributionPoint, out templateDistributionPoint2, out templateGuid);
             }
             catch (RightsManagementException innerException)
             {
                 failureTarget = tpdName;
                 throw new InvalidTemplateException(innerException);
             }
             RmsUtil.ThrowIfRightsTemplateInvalid(tpdImportUtilities, tpdName, template, templateGuid, out failureTarget);
             RmsUtil.ThrowIfTemplateDistributionPointInvalid(templateDistributionPoint, RmsUtil.TemplateDistributionPointType.Intranet, templateGuid, intranetLicensingUrl, extranetLicensingUrl, out failureTarget);
             RmsUtil.ThrowIfTemplateDistributionPointInvalid(templateDistributionPoint2, RmsUtil.TemplateDistributionPointType.Extranet, templateGuid, intranetLicensingUrl, extranetLicensingUrl, out failureTarget);
         }
     }
 }
        // Token: 0x06001569 RID: 5481 RVA: 0x0007E1B0 File Offset: 0x0007C3B0
        protected bool IsIrmOperation(out Guid templateId)
        {
            string templateID = this.TemplateID;

            if (templateID == null)
            {
                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, this, "IRM operation not requested by device");
                templateId = Guid.Empty;
                return(false);
            }
            AirSyncCounters.NumberOfSendIRMMails.Increment();
            if (!base.User.IrmEnabled || !base.Request.IsSecureConnection)
            {
                AirSyncDiagnostics.TraceError <string>(ExTraceGlobals.RequestsTracer, this, "IRM feature disabled for user {0}", base.User.DisplayName);
                throw new AirSyncPermanentException(StatusCode.IRM_FeatureDisabled, false)
                      {
                          ErrorStringForProtocolLogger = "smbIioFeatureDisabled"
                      };
            }
            if (!DrmClientUtils.TryParseGuid(templateID, out templateId))
            {
                AirSyncDiagnostics.TraceError <string>(ExTraceGlobals.RequestsTracer, this, "Invalid template Guid {0}", templateID);
                throw new AirSyncPermanentException(StatusCode.IRM_InvalidTemplateID, false)
                      {
                          ErrorStringForProtocolLogger = "smbIioInvalidTemplateID"
                      };
            }
            return(true);
        }
 public static LicenseResponse[] GetLicenseResponses(UseLicenseResult[] endUseLicenses, Uri licenseUri)
 {
     RmsClientManagerUtils.ThrowOnNullOrEmptyArrayArgument("endUseLicenses", endUseLicenses);
     LicenseResponse[] array = new LicenseResponse[endUseLicenses.Length];
     for (int i = 0; i < endUseLicenses.Length; i++)
     {
         UseLicenseResult useLicenseResult = endUseLicenses[i];
         if (useLicenseResult.Error != null)
         {
             array[i] = new LicenseResponse(new RightsManagementException(RightsManagementFailureCode.OfflineRmsServerFailure, ServerStrings.FailedToAcquireUseLicense(licenseUri), useLicenseResult.Error));
         }
         else
         {
             ContentRight?usageRights;
             try
             {
                 usageRights = new ContentRight?(DrmClientUtils.GetUsageRightsFromLicense(useLicenseResult.EndUseLicense));
             }
             catch (RightsManagementException arg)
             {
                 Microsoft.Exchange.Diagnostics.Components.Data.Storage.ExTraceGlobals.RightsManagementTracer.TraceError <int, RightsManagementException>(0L, "Failed to get usage rights from license for recipient index {0}. Error {1}", i, arg);
                 usageRights = null;
             }
             array[i] = new LicenseResponse(useLicenseResult.EndUseLicense, usageRights);
         }
     }
     return(array);
 }
        public ConfigurationInformationProvider(IPerTenantRMSTrustedPublishingDomainConfiguration perTenantconfig)
        {
            this.serverLicensorCertificate             = new ConfigurationInformationProvider.ServerLicensorCertInformation(ConfigurationInformationProvider.GetTrustedDomainChainArrayFromCompressedString(perTenantconfig.CompressedSLCCertChain));
            this.serverLicensorCertificate.IsValidated = true;
            List <string[]> list = new List <string[]>(perTenantconfig.CompressedTrustedDomainChains.Count);

            foreach (string compressedCertChainString in perTenantconfig.CompressedTrustedDomainChains)
            {
                list.Add(ConfigurationInformationProvider.GetTrustedDomainChainArrayFromCompressedString(compressedCertChainString));
            }
            this.trustedUserDomains             = new ConfigurationInformationProvider.TrustedDomainInformation(list);
            this.trustedUserDomains.IsValidated = true;
            this.trustedPublishingDomains       = this.trustedUserDomains;
            Dictionary <string, string> dictionary = new Dictionary <string, string>();

            foreach (string compressedTemplateString in perTenantconfig.CompressedRMSTemplates)
            {
                string templateFromCompressedString = ConfigurationInformationProvider.GetTemplateFromCompressedString(compressedTemplateString);
                Guid   templateGuidFromLicense;
                try
                {
                    templateGuidFromLicense = DrmClientUtils.GetTemplateGuidFromLicense(templateFromCompressedString);
                }
                catch (RightsManagementException ex)
                {
                    throw new ConfigurationProviderException(true, "ConfigurationInformationProvider failed to parse template data for tenant ", ex);
                }
                dictionary.Add(templateGuidFromLicense.ToString("B"), templateFromCompressedString);
            }
            this.rightsTemplateInformation                 = new ConfigurationInformationProvider.RightsTemplateInformation(dictionary);
            this.licensingIntranetDistributionPointUrl     = perTenantconfig.IntranetLicensingUrl;
            this.licensingExtranetDistributionPointUrl     = perTenantconfig.ExtranetLicensingUrl;
            this.certificationIntranetDistributionPointUrl = perTenantconfig.IntranetCertificationUrl;
            this.certificationExtranetDistributionPointUrl = perTenantconfig.ExtranetCertificationUrl;
        }
 // Token: 0x06000B7D RID: 2941 RVA: 0x00024770 File Offset: 0x00022970
 private void Parse(string identity)
 {
     if (!DrmClientUtils.TryParseGuid(identity, out this.templateId))
     {
         this.templateId = Guid.Empty;
     }
     this.templateName = (string.IsNullOrEmpty(identity) ? null : identity.Trim());
 }
Example #6
0
        private bool WriteToStore(Guid tenantId, Uri url, XmlNode[] rac, XmlNode[] clc, byte version)
        {
            bool     flag      = clc == null;
            DateTime dateTime  = RMUtil.GetRacExpirationTime(rac[0]);
            DateTime dateTime2 = flag ? DateTime.MaxValue : RMUtil.GetClcExpirationTime(clc[0]);

            if (RmsClientManager.AppSettings.RacClcStoreExpirationInterval.TotalMinutes != 0.0)
            {
                DateTime dateTime3 = DateTime.UtcNow.Add(RmsClientManager.AppSettings.RacClcStoreExpirationInterval);
                dateTime  = ((dateTime3 > dateTime) ? dateTime : dateTime3);
                dateTime2 = ((dateTime3 > dateTime2) ? dateTime2 : dateTime3);
            }
            string text  = DrmClientUtils.ConvertXmlNodeArrayToCertificateChain(rac);
            string text2 = flag ? null : DrmClientUtils.ConvertXmlNodeArrayToCertificateChain(clc);
            string text3 = null;
            string text4 = null;

            try
            {
                text3 = DrmClientUtils.AddCertToLicenseStore(text, true);
                if (flag)
                {
                    this.perfCounters.FileWrite(1);
                }
                else
                {
                    text4 = DrmClientUtils.AddCertToLicenseStore(text2, false);
                    this.perfCounters.FileWrite(2);
                }
            }
            catch (IOException arg)
            {
                RmsLicenseStoreManager.Tracer.TraceError <Guid, Uri, IOException>(0L, "License Store Manager failed to write RAC-CLC to store for tenant ({0}) and URL ({1}). IOException - {2}.", tenantId, url, arg);
                return(false);
            }
            catch (UnauthorizedAccessException arg2)
            {
                RmsLicenseStoreManager.Tracer.TraceError <Guid, Uri, UnauthorizedAccessException>(0L, "License Store Manager failed to write RAC-CLC to store for tenant ({0}) and URL ({1}). UnauthorizedAccessException - {2}.", tenantId, url, arg2);
                return(false);
            }
            if (string.IsNullOrEmpty(text3) || (!flag && string.IsNullOrEmpty(text4)))
            {
                RmsLicenseStoreManager.Tracer.TraceError <Guid, Uri>(0L, "License Store Manager failed to write RAC-CLC to store for tenant ({0}) and URL ({1}).", tenantId, url);
                return(false);
            }
            RmsLicenseStoreInfo rmsLicenseStoreInfo = new RmsLicenseStoreInfo(tenantId, url, text3, text4, dateTime, dateTime2, version);

            this.licenseMap.Add(rmsLicenseStoreInfo);
            this.cache.TryAdd(new MultiValueKey(new object[]
            {
                rmsLicenseStoreInfo.TenantId,
                rmsLicenseStoreInfo.Url
            }), new TenantLicensePair(rmsLicenseStoreInfo.TenantId, rac, (clc != null) ? clc[0] : null, text, text2, rmsLicenseStoreInfo.RacExpire, rmsLicenseStoreInfo.ClcExpire, version, RmsClientManager.EnvironmentHandle, RmsClientManager.LibraryHandle));
            return(true);
        }
Example #7
0
        private void ValidateTemplate(string templateXrml, Uri intranetLicensingUrl, Uri extranetLicensingUrl)
        {
            Uri  uri  = null;
            Uri  uri2 = null;
            Guid templateGuid;

            DrmClientUtils.ParseTemplate(templateXrml, out uri, out uri2, out templateGuid);
            if (uri != null && Uri.Compare(uri, intranetLicensingUrl, UriComponents.SchemeAndServer, UriFormat.UriEscaped, StringComparison.OrdinalIgnoreCase) != 0 && Uri.Compare(uri, extranetLicensingUrl, UriComponents.SchemeAndServer, UriFormat.UriEscaped, StringComparison.OrdinalIgnoreCase) != 0)
            {
                base.WriteError(new FailedToMatchTemplateDistributionPointToLicensingUriException(templateGuid, uri, intranetLicensingUrl), (ErrorCategory)1000, intranetLicensingUrl);
            }
            if (uri2 != null && Uri.Compare(uri2, intranetLicensingUrl, UriComponents.SchemeAndServer, UriFormat.UriEscaped, StringComparison.OrdinalIgnoreCase) != 0 && Uri.Compare(uri2, extranetLicensingUrl, UriComponents.SchemeAndServer, UriFormat.UriEscaped, StringComparison.OrdinalIgnoreCase) != 0)
            {
                base.WriteError(new FailedToMatchTemplateDistributionPointToLicensingUriException(templateGuid, uri2, extranetLicensingUrl), (ErrorCategory)1000, extranetLicensingUrl);
            }
        }
Example #8
0
 public void PrepareAcquiredLicensesBeforeSave()
 {
     this.CheckDisposed("PrepareAcquiredLicensesBeforeSave");
     if (this.licenseAcquired)
     {
         this[MessageItemSchema.DRMRights]     = this.useLicenseValue.UsageRights;
         this[MessageItemSchema.DRMExpiryTime] = this.useLicenseValue.ExpiryTime;
         if (!DrmClientUtils.IsCachingOfLicenseDisabled(this.useLicenseValue.UseLicense))
         {
             using (Stream stream = base.OpenPropertyStream(MessageItemSchema.DRMServerLicenseCompressed, PropertyOpenMode.Create))
             {
                 DrmEmailCompression.CompressUseLicense(this.useLicenseValue.UseLicense, stream);
             }
         }
         this[MessageItemSchema.DRMPropsSignature] = this.useLicenseValue.DRMPropsSignature;
     }
 }
Example #9
0
 public AcquireTenantLicensesRpcParameters(RmsClientManagerContext rmsClientManagerContext, string identity, XmlNode[] machineCertificateChain) : base(rmsClientManagerContext)
 {
     if (rmsClientManagerContext == null)
     {
         throw new ArgumentNullException("rmsClientManagerContext");
     }
     if (string.IsNullOrEmpty(identity))
     {
         throw new ArgumentNullException("identity");
     }
     if (machineCertificateChain == null || machineCertificateChain.Length <= 0)
     {
         throw new ArgumentNullException("machineCertificateChain");
     }
     base.SetParameterValue("Identity", identity);
     base.SetParameterValue("MachineCertificateChainStringArray", DrmClientUtils.ConvertXmlNodeArrayToStringArray(machineCertificateChain));
 }
Example #10
0
 public AcquireTenantLicensesRpcResults(OverallRpcResult overallRpcResult, XmlNode[] rac, XmlNode[] clc) : base(overallRpcResult)
 {
     if (overallRpcResult == null)
     {
         throw new ArgumentNullException("overallRpcResult");
     }
     if (rac == null || rac.Length <= 0)
     {
         throw new ArgumentNullException("rac");
     }
     if (clc == null || clc.Length <= 0)
     {
         throw new ArgumentNullException("clc");
     }
     base.SetParameterValue("RacStringArray", DrmClientUtils.ConvertXmlNodeArrayToStringArray(rac));
     base.SetParameterValue("ClcStringArray", DrmClientUtils.ConvertXmlNodeArrayToStringArray(clc));
 }
 internal MsgToRpMsgConverter(MessageItem envelopeMessage, OrganizationId orgId, string publishLicense, string serverUseLicense, OutboundConversionOptions options)
 {
     using (DisposeGuard disposeGuard = this.Guard())
     {
         this.serverUseLicense = serverUseLicense;
         this.publishLicense   = publishLicense;
         this.options          = options;
         this.charset          = ConvertUtils.GetItemMimeCharset(envelopeMessage.CoreItem.PropertyBag);
         this.messageId        = envelopeMessage.InternetMessageId;
         this.orgId            = RmsClientManagerUtils.OrgIdFromPublishingLicenseOrDefault(publishLicense, orgId);
         this.InitTenantLicenses();
         MsgToRpMsgConverter.CallRM(delegate
         {
             DrmClientUtils.GetContentIdFromLicense(this.publishLicense, out this.contentId, out this.contentIdType);
         }, ServerStrings.FailedToParseUseLicense);
         disposeGuard.Success();
     }
 }
        public void Save(IConfigurable instance)
        {
            if (this.orgId == OrganizationId.ForestWideOrgId)
            {
                throw new NotSupportedException();
            }
            RmsTemplatePresentation rmsTemplatePresentation = instance as RmsTemplatePresentation;

            if (rmsTemplatePresentation == null)
            {
                throw new ArgumentException("passed in instance not of type RmsTemplatePresentation", "instance");
            }
            Guid templateGuid = rmsTemplatePresentation.TemplateGuid;
            RMSTrustedPublishingDomain rmstrustedPublishingDomain = this.FindDefaultTPD();

            if (rmstrustedPublishingDomain == null)
            {
                return;
            }
            if (!MultiValuedPropertyBase.IsNullOrEmpty(rmstrustedPublishingDomain.RMSTemplates))
            {
                string text  = null;
                string text2 = null;
                foreach (string text3 in rmstrustedPublishingDomain.RMSTemplates)
                {
                    RmsTemplateType rmsTemplateType;
                    string          text4 = RMUtil.DecompressTemplate(text3, out rmsTemplateType);
                    Guid            templateGuidFromLicense = DrmClientUtils.GetTemplateGuidFromLicense(text4);
                    if (templateGuidFromLicense == templateGuid && rmsTemplateType != rmsTemplatePresentation.Type)
                    {
                        text  = text3;
                        text2 = RMUtil.CompressTemplate(text4, rmsTemplatePresentation.Type);
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(text2))
                {
                    rmstrustedPublishingDomain.RMSTemplates.Remove(text);
                    rmstrustedPublishingDomain.RMSTemplates.Add(text2);
                    this.adSession.Save(rmstrustedPublishingDomain);
                }
            }
        }
 public AcquireUseLicensesRpcParameters(RmsClientManagerContext rmsClientManagerContext, XmlNode[] rightsAccountCertificate, XmlNode[] issuanceLicense, LicenseeIdentity[] licenseeIdentities) : base(rmsClientManagerContext)
 {
     if (rmsClientManagerContext == null)
     {
         throw new ArgumentNullException("rmsClientManagerContext");
     }
     if (rightsAccountCertificate == null || rightsAccountCertificate.Length <= 0)
     {
         throw new ArgumentNullException("rightsAccountCertificate");
     }
     if (issuanceLicense == null || issuanceLicense.Length <= 0)
     {
         throw new ArgumentNullException("issuanceLicense");
     }
     if (licenseeIdentities == null || licenseeIdentities.Length <= 0)
     {
         throw new ArgumentNullException("licenseeIdentities");
     }
     base.SetParameterValue("RightsAccountCertificateStringArray", DrmClientUtils.ConvertXmlNodeArrayToStringArray(rightsAccountCertificate));
     base.SetParameterValue("IssuanceLicenseStringArray", DrmClientUtils.ConvertXmlNodeArrayToStringArray(issuanceLicense));
     base.SetParameterValue("LicenseeIdentities", licenseeIdentities);
 }
Example #14
0
 private void Refresh(bool throwExceptions)
 {
     if (DateTime.UtcNow < this.timeout)
     {
         return;
     }
     RmsConfiguration.Tracer.TraceDebug <bool>((long)this.objHashCode, "Refreshing the first org service locations cache. Initializing for the first time: {0}", throwExceptions);
     lock (this)
     {
         if (DateTime.UtcNow < this.timeout)
         {
             return;
         }
         RmsConfiguration.FirstOrgServiceLocationsCache.FirstOrgServiceLocations firstOrgServiceLocations = new RmsConfiguration.FirstOrgServiceLocationsCache.FirstOrgServiceLocations();
         try
         {
             firstOrgServiceLocations.CertificationLocation = DrmClientUtils.GetServiceLocation(SafeRightsManagementSessionHandle.InvalidHandle, ServiceType.Certification, ServiceLocation.Enterprise, null);
             firstOrgServiceLocations.PublishingLocaton     = DrmClientUtils.GetServiceLocation(SafeRightsManagementSessionHandle.InvalidHandle, ServiceType.ClientLicensor, ServiceLocation.Enterprise, null);
             this.firstOrgServiceLocations = firstOrgServiceLocations;
         }
         catch (RightsManagementException ex)
         {
             RmsConfiguration.Tracer.TraceError <RightsManagementException>((long)this.objHashCode, "Failed to get the service locations. Error {0}", ex);
             if (ex.FailureCode != RightsManagementFailureCode.ServiceNotFound && throwExceptions)
             {
                 throw;
             }
             RmsConfiguration.Tracer.TraceError((long)this.objHashCode, "Failed to refresh the first org cache");
         }
         if (this.firstOrgServiceLocations != null)
         {
             this.timeout = DateTime.UtcNow.Add(RmsConfiguration.FirstOrgServiceLocationsCache.ExpirationTime);
         }
     }
     RmsConfiguration.Tracer.TraceDebug <Uri, Uri, DateTime>((long)this.objHashCode, "Values for the first org cache. CertificationLocation: {0}, PublishingLocation: {1}, ExpirationTime: {2}", (this.firstOrgServiceLocations != null) ? this.firstOrgServiceLocations.CertificationLocation : null, (this.firstOrgServiceLocations != null) ? this.firstOrgServiceLocations.PublishingLocaton : null, this.timeout);
 }
Example #15
0
        public bool ReadFromStore(Guid tenantId, Uri url, byte version, out TenantLicensePair tenantLicenses)
        {
            if (null == url)
            {
                throw new ArgumentNullException("url");
            }
            MultiValueKey multiValueKey = new MultiValueKey(new object[]
            {
                tenantId,
                url
            });
            RmsLicenseStoreInfo rmsLicenseStoreInfo;

            if (this.ReadFromCache(multiValueKey, out tenantLicenses))
            {
                this.licenseMap.TryGet(multiValueKey, out rmsLicenseStoreInfo);
                return(true);
            }
            if (!this.licenseMap.TryGet(multiValueKey, out rmsLicenseStoreInfo))
            {
                RmsLicenseStoreManager.Tracer.TraceDebug <MultiValueKey>(0L, "License Store Manager doesn't have entry in map for key ({0}) or certs are expired.", multiValueKey);
                return(false);
            }
            string text  = null;
            string text2 = null;

            try
            {
                text = DrmClientUtils.GetCertFromLicenseStore(rmsLicenseStoreInfo.RacFileName);
                if (!string.IsNullOrEmpty(rmsLicenseStoreInfo.ClcFileName))
                {
                    text2 = DrmClientUtils.GetCertFromLicenseStore(rmsLicenseStoreInfo.ClcFileName);
                    this.perfCounters.FileRead(2);
                }
                else
                {
                    this.perfCounters.FileRead(1);
                }
            }
            catch (IOException arg)
            {
                RmsLicenseStoreManager.Tracer.TraceError <MultiValueKey, IOException>(0L, "License Store Manager failed to read certs from store for key ({0}). IOException - {1}.", multiValueKey, arg);
                return(false);
            }
            catch (UnauthorizedAccessException arg2)
            {
                RmsLicenseStoreManager.Tracer.TraceError <MultiValueKey, UnauthorizedAccessException>(0L, "License Store Manager failed to read certs from store for key ({0}). UnauthorizedAccessException - {1}.", multiValueKey, arg2);
                return(false);
            }
            catch (SecurityException arg3)
            {
                RmsLicenseStoreManager.Tracer.TraceError <MultiValueKey, SecurityException>(0L, "License Store Manager failed to read certs from store for key ({0}). SecurityException - {1}.", multiValueKey, arg3);
                return(false);
            }
            XmlNode[] rac;
            XmlNode[] array;
            if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(text2) && RMUtil.TryConvertAppendedCertsToXmlNodeArray(text, out rac) && RMUtil.TryConvertAppendedCertsToXmlNodeArray(text2, out array))
            {
                tenantLicenses = new TenantLicensePair(tenantId, rac, array[0], null, DrmClientUtils.ConvertXmlNodeArrayToCertificateChain(array), rmsLicenseStoreInfo.RacExpire, rmsLicenseStoreInfo.ClcExpire, rmsLicenseStoreInfo.Version, RmsClientManager.EnvironmentHandle, RmsClientManager.LibraryHandle);
                this.cache.TryAdd(multiValueKey, tenantLicenses);
                return(true);
            }
            if (!string.IsNullOrEmpty(text) && RMUtil.TryConvertAppendedCertsToXmlNodeArray(text, out rac) && version == rmsLicenseStoreInfo.Version)
            {
                tenantLicenses = new TenantLicensePair(tenantId, rac, null, null, null, rmsLicenseStoreInfo.RacExpire, rmsLicenseStoreInfo.ClcExpire, rmsLicenseStoreInfo.Version, RmsClientManager.EnvironmentHandle, RmsClientManager.LibraryHandle);
                this.cache.TryAdd(multiValueKey, tenantLicenses);
                return(true);
            }
            RmsLicenseStoreManager.Tracer.TraceError <MultiValueKey>(0L, "License Store Manager failed to read certs from store for key ({0}) - certs are empty or invalid.", multiValueKey);
            this.licenseMap.Remove(multiValueKey);
            return(false);
        }
Example #16
0
 public static void AcquireTenantLicenses(RmsClientManagerContext clientContext, XmlNode[] machineCertificateChain, string identity, out XmlNode[] racXml, out XmlNode[] clcXml)
 {
     ArgumentValidator.ThrowIfNull("clientContext", clientContext);
     ArgumentValidator.ThrowIfNull("machineCertificateChain", machineCertificateChain);
     ArgumentValidator.ThrowIfNullOrEmpty("identity", identity);
     racXml = null;
     clcXml = null;
     ServerManager.InitializeIfNeeded();
     if (ServerManager.instance.isHostingInstance)
     {
         PerTenantRMSTrustedPublishingDomainConfiguration tenantTrustedPublishingDomainConfig = ServerManager.instance.GetTenantTrustedPublishingDomainConfig(clientContext);
         ContextProvider contextProvider = null;
         try
         {
             IRightsAccountCertificateGenerator  rightsAccountCertificateGenerator;
             IClientLicensorCertificateGenerator clientLicensorCertificateGenerator;
             try
             {
                 contextProvider = new ContextProvider(clientContext, tenantTrustedPublishingDomainConfig);
                 rightsAccountCertificateGenerator  = GeneratorFactory.CreateRightsAccountCertificateGenerator(contextProvider);
                 clientLicensorCertificateGenerator = GeneratorFactory.CreateClientLicensorCertificateGenerator(contextProvider);
             }
             catch (ConfigurationProviderException ex)
             {
                 ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireTenantLicenses, ServerManagerLog.EventType.Error, clientContext, string.Format("Failed to create Generator with Exception: {0}", ServerManagerLog.GetExceptionLogString(ex, ServerManagerLog.ExceptionLogOption.IncludeStack | ServerManagerLog.ExceptionLogOption.IncludeInnerException)));
                 throw new RightsManagementServerException(ServerStrings.FailedToCreateLicenseGenerator(clientContext.OrgId.ToString(), "RacClc"), ex);
             }
             catch (CertificationException ex2)
             {
                 ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireTenantLicenses, ServerManagerLog.EventType.Error, clientContext, string.Format("Failed to create Generator with WellKnownErrorCode {0}, Exception: {1}", ex2.ErrorCode, ServerManagerLog.GetExceptionLogString(ex2, ServerManagerLog.ExceptionLogOption.IncludeStack | ServerManagerLog.ExceptionLogOption.IncludeInnerException)));
                 throw new RightsManagementServerException(ServerStrings.FailedToCreateLicenseGenerator(clientContext.OrgId.ToString(), "Rac"), ex2);
             }
             catch (PublishingException ex3)
             {
                 ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireTenantLicenses, ServerManagerLog.EventType.Error, clientContext, string.Format("Failed to create Generator with WellKnownErrorCode {0}, Exception: {1}", ex3.ErrorCode, ServerManagerLog.GetExceptionLogString(ex3, ServerManagerLog.ExceptionLogOption.IncludeStack | ServerManagerLog.ExceptionLogOption.IncludeInnerException)));
                 throw new RightsManagementServerException(ServerStrings.FailedToCreateLicenseGenerator(clientContext.OrgId.ToString(), "Clc"), ex3);
             }
             XrmlCertificateChain xrmlCertificateChain = new XrmlCertificateChain(DrmClientUtils.ConvertXmlNodeArrayToStringArray(machineCertificateChain));
             ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireTenantLicenses, ServerManagerLog.EventType.Entry, clientContext, string.Format("AcquireTenantLicenses for identity {0}", identity));
             XrmlCertificateChain xrmlCertificateChain2;
             XrmlCertificateChain xrmlCertificateChain3;
             try
             {
                 string text = ServerManager.ReadOrganizationRacKeysFromIRMConfig(clientContext.OrgId);
                 xrmlCertificateChain2 = rightsAccountCertificateGenerator.AcquireCertificate(xrmlCertificateChain, identity, text);
                 xrmlCertificateChain3 = clientLicensorCertificateGenerator.AcquireCertificate(xrmlCertificateChain2);
             }
             catch (CertificationException ex4)
             {
                 ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireTenantLicenses, ServerManagerLog.EventType.Error, clientContext, string.Format("Failed to AcquireTenantLicenses with WellKnownErrorCode {0}, Exception: {1}", ex4.ErrorCode, ServerManagerLog.GetExceptionLogString(ex4, ServerManagerLog.ExceptionLogOption.IncludeStack | ServerManagerLog.ExceptionLogOption.IncludeInnerException)));
                 throw new RightsManagementServerException(ServerStrings.FailedToAcquireRacAndClc(clientContext.OrgId.ToString(), identity), ex4);
             }
             catch (PublishingException ex5)
             {
                 ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireTenantLicenses, ServerManagerLog.EventType.Error, clientContext, string.Format("Failed to AcquireTenantLicenses with WellKnownErrorCode {0}, Exception: {1}", ex5.ErrorCode, ServerManagerLog.GetExceptionLogString(ex5, ServerManagerLog.ExceptionLogOption.IncludeStack | ServerManagerLog.ExceptionLogOption.IncludeInnerException)));
                 throw new RightsManagementServerException(ServerStrings.FailedToAcquireRacAndClc(clientContext.OrgId.ToString(), identity), ex5);
             }
             if (!RMUtil.TryConvertCertChainStringArrayToXmlNodeArray(xrmlCertificateChain2.ToStringArray(), out racXml))
             {
                 throw new RightsManagementServerException(ServerStrings.FailedToAcquireRacAndClc(clientContext.OrgId.ToString(), identity), true);
             }
             if (!RMUtil.TryConvertCertChainStringArrayToXmlNodeArray(xrmlCertificateChain3.ToStringArray(), out clcXml))
             {
                 throw new RightsManagementServerException(ServerStrings.FailedToAcquireRacAndClc(clientContext.OrgId.ToString(), identity), true);
             }
             return;
         }
         finally
         {
             if (contextProvider != null)
             {
                 contextProvider.Dispose();
             }
         }
     }
     RpcClientWrapper.AcquireTenantLicenses(clientContext, machineCertificateChain, identity, out racXml, out clcXml);
 }
Example #17
0
        public static UseLicenseResult[] AcquireUseLicenses(RmsClientManagerContext clientContext, XmlNode[] rightsAccountCertificate, XmlNode[] issuanceLicense, LicenseeIdentity[] licenseeIdentities)
        {
            ArgumentValidator.ThrowIfNull("clientContext", clientContext);
            ArgumentValidator.ThrowIfNull("rightsAccountCertificate", rightsAccountCertificate);
            ArgumentValidator.ThrowIfNull("issuanceLicense", issuanceLicense);
            ArgumentValidator.ThrowIfNull("licenseeIdentities", licenseeIdentities);
            Stopwatch watch = Stopwatch.StartNew();

            ServerManager.InitializeIfNeeded();
            if (ServerManager.instance.isHostingInstance)
            {
                PerTenantRMSTrustedPublishingDomainConfiguration tenantTrustedPublishingDomainConfig = ServerManager.instance.GetTenantTrustedPublishingDomainConfig(clientContext);
                ContextProvider contextProvider = null;
                try
                {
                    IEndUserLicenseGenerator endUserLicenseGenerator;
                    try
                    {
                        contextProvider         = new ContextProvider(clientContext, tenantTrustedPublishingDomainConfig);
                        endUserLicenseGenerator = GeneratorFactory.CreateEndUserLicenseGenerator(contextProvider);
                    }
                    catch (ConfigurationProviderException ex)
                    {
                        ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireUseLicense, ServerManagerLog.EventType.Error, clientContext, string.Format("Failed in CreateEndUserLicenseGenerator with Exception: {0}", ServerManagerLog.GetExceptionLogString(ex, ServerManagerLog.ExceptionLogOption.IncludeStack | ServerManagerLog.ExceptionLogOption.IncludeInnerException)));
                        throw new RightsManagementServerException(ServerStrings.FailedToCreateLicenseGenerator(clientContext.OrgId.ToString(), "UseLicenseGenerator"), ex);
                    }
                    catch (LicensingException ex2)
                    {
                        ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireUseLicense, ServerManagerLog.EventType.Error, clientContext, string.Format("Failed in CreateEndUserLicenseGenerator with WellKnownError {0} and Exception: {1}", ex2.ErrorCode, ServerManagerLog.GetExceptionLogString(ex2, ServerManagerLog.ExceptionLogOption.IncludeStack | ServerManagerLog.ExceptionLogOption.IncludeInnerException)));
                        throw new RightsManagementServerException(ServerStrings.FailedToCreateLicenseGenerator(clientContext.OrgId.ToString(), "UseLicenseGenerator"), ex2);
                    }
                    XrmlCertificateChain xrmlCertificateChain  = new XrmlCertificateChain(DrmClientUtils.ConvertXmlNodeArrayToStringArray(issuanceLicense));
                    XrmlCertificateChain xrmlCertificateChain2 = new XrmlCertificateChain(DrmClientUtils.ConvertXmlNodeArrayToStringArray(rightsAccountCertificate));
                    ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireUseLicense, ServerManagerLog.EventType.Entry, clientContext, string.Format("AcquireLicenses for {0} licensees, they are {1}", licenseeIdentities.Length, ServerManager.GetLicenseeLogString(licenseeIdentities)));
                    LicensingBatchResults licensingBatchResults;
                    try
                    {
                        licensingBatchResults = endUserLicenseGenerator.AcquireLicenses(xrmlCertificateChain2, xrmlCertificateChain, licenseeIdentities);
                    }
                    catch (LicensingException ex3)
                    {
                        ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireUseLicense, ServerManagerLog.EventType.Error, clientContext, string.Format("Failed useLicenseGenerator.AcquireLicenses with WellKnownErrorCode {0}, Exception: {1}", ex3.ErrorCode, ServerManagerLog.GetExceptionLogString(ex3, ServerManagerLog.ExceptionLogOption.IncludeStack | ServerManagerLog.ExceptionLogOption.IncludeInnerException)));
                        throw new RightsManagementServerException(ServerStrings.FailedToAcquireUseLicenses(clientContext.OrgId.ToString()), ex3);
                    }
                    int num = 0;
                    UseLicenseResult[] array = new UseLicenseResult[licensingBatchResults.LicensingResults.Count];
                    for (int i = 0; i < licensingBatchResults.LicensingResults.Count; i++)
                    {
                        StringBuilder stringBuilder = null;
                        if (licensingBatchResults.LicensingResults[i].EndUserLicense != null && licensingBatchResults.LicensingResults[i].Error == null)
                        {
                            stringBuilder = new StringBuilder();
                            stringBuilder.Append(licensingBatchResults.LicensingResults[i].EndUserLicense);
                            string[] array2 = licensingBatchResults.ServerLicensorCertificateChain.ToStringArray();
                            foreach (string value in array2)
                            {
                                stringBuilder.Append(value);
                            }
                        }
                        LicensingException error            = licensingBatchResults.LicensingResults[i].Error;
                        RightsManagementServerException ex4 = (error != null) ? new RightsManagementServerException(ServerStrings.FailedToAcquireUseLicenses(clientContext.OrgId.ToString()), error) : null;
                        if (error != null)
                        {
                            num++;
                            ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireUseLicense, ServerManagerLog.EventType.Error, clientContext, string.Format("Failed to AcquireLicenses for Licensee {0} with WellKnownErrorCode {1}, Exception: {2}", licenseeIdentities[i], error.ErrorCode, ServerManagerLog.GetExceptionLogString(error, ServerManagerLog.ExceptionLogOption.IncludeStack | ServerManagerLog.ExceptionLogOption.IncludeInnerException)));
                        }
                        if (stringBuilder != null && ex4 != null)
                        {
                            throw new InvalidOperationException("LicensingResult.EndUserLicense and LicensingResult.Error are both non-null");
                        }
                        if (stringBuilder == null && ex4 == null)
                        {
                            throw new InvalidOperationException("LicensingResult.EndUserLicense and LicensingResult.Error are null");
                        }
                        array[i] = new UseLicenseResult((stringBuilder != null) ? stringBuilder.ToString() : null, ex4);
                    }
                    ServerManagerLog.LogEvent(ServerManagerLog.Subcomponent.AcquireUseLicense, (num == 0) ? ServerManagerLog.EventType.Success : ServerManagerLog.EventType.Error, clientContext, string.Format("AcquireLicenses finishes with successs count {0} and failed count {1}", array.Length - num, num));
                    ServerManager.instance.rpcAcquireUseLicensePerformanceMonitor.Record(watch);
                    return(array);
                }
                finally
                {
                    if (contextProvider != null)
                    {
                        contextProvider.Dispose();
                    }
                }
            }
            UseLicenseRpcResult[] array4 = RpcClientWrapper.AcquireUseLicenses(clientContext, rightsAccountCertificate, issuanceLicense, licenseeIdentities);
            UseLicenseResult[]    array5 = new UseLicenseResult[array4.Length];
            for (int k = 0; k < array4.Length; k++)
            {
                RightsManagementServerException e = null;
                if (array4[k].ErrorResults != null && array4[k].ErrorResults.Count > 0)
                {
                    e = new RightsManagementServerException(array4[k].GetSerializedString(), array4[k].IsPermanentFailure);
                }
                array5[k] = new UseLicenseResult(array4[k].EndUseLicense, e);
            }
            ServerManager.instance.acquireUseLicensePerformanceMonitor.Record(watch);
            return(array5);
        }
 private void AcquireUseLicenseAndUsageRightsCallback(IAsyncResult asyncResult)
 {
     if (asyncResult == null)
     {
         throw new ArgumentNullException("asyncResult");
     }
     if (asyncResult.AsyncState == null)
     {
         IrmLicensingManager.Tracer.TraceError((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: asyncResult.AsyncState is null.");
         throw new InvalidOperationException("asyncResult.AsyncState must NOT be null.");
     }
     IrmLicensingManager.AsyncState asyncState = (IrmLicensingManager.AsyncState)asyncResult.AsyncState;
     try
     {
         IrmLicensingManager.Tracer.TraceDebug <OwaStoreObjectId>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: calling EndAcquireUseLicenseAndUsageRights to get results for message {0}", asyncState.MessageId);
         UseLicenseAndUsageRights useLicenseAndUsageRights = RmsClientManager.EndAcquireUseLicenseAndUsageRights(asyncResult);
         if (string.IsNullOrEmpty(useLicenseAndUsageRights.UseLicense))
         {
             IrmLicensingManager.Tracer.TraceError((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: Use license is null/empty");
             throw new InvalidOperationException("Use license must NOT be null/empty");
         }
         if (this.userContext.State != UserContextState.Active)
         {
             IrmLicensingManager.Tracer.TraceDebug((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: User context is no longer active.  Bailing out.");
         }
         else
         {
             SafeRightsManagementHandle safeRightsManagementHandle = null;
             try
             {
                 RmsClientManager.BindUseLicenseForDecryption(new RmsClientManagerContext(useLicenseAndUsageRights.OrganizationId, RmsClientManagerContext.ContextId.MessageId, asyncState.MessageId.ToString(), null), useLicenseAndUsageRights.LicensingUri, useLicenseAndUsageRights.UseLicense, useLicenseAndUsageRights.PublishingLicense, out safeRightsManagementHandle);
             }
             finally
             {
                 if (safeRightsManagementHandle != null)
                 {
                     safeRightsManagementHandle.Close();
                 }
             }
             bool flag = false;
             try
             {
                 this.userContext.Lock();
                 flag = true;
                 using (Item item = Item.Bind(asyncState.MessageId.GetSession(this.userContext), asyncState.MessageId.StoreObjectId, ItemBindOption.None))
                 {
                     MessageItem messageItem = item as MessageItem;
                     if (messageItem == null)
                     {
                         IrmLicensingManager.Tracer.TraceError((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: bound item is not a message.  Ignoring it.");
                     }
                     else
                     {
                         messageItem.OpenAsReadWrite();
                         messageItem[MessageItemSchema.DRMRights]     = useLicenseAndUsageRights.UsageRights;
                         messageItem[MessageItemSchema.DRMExpiryTime] = useLicenseAndUsageRights.ExpiryTime;
                         if (!DrmClientUtils.IsCachingOfLicenseDisabled(useLicenseAndUsageRights.UseLicense))
                         {
                             using (Stream stream = messageItem.OpenPropertyStream(MessageItemSchema.DRMServerLicenseCompressed, PropertyOpenMode.Create))
                             {
                                 DrmEmailCompression.CompressUseLicense(useLicenseAndUsageRights.UseLicense, stream);
                             }
                         }
                         messageItem[MessageItemSchema.DRMPropsSignature] = useLicenseAndUsageRights.DRMPropsSignature;
                         RightsManagedMessageItem rightsManagedMessageItem = messageItem as RightsManagedMessageItem;
                         if (rightsManagedMessageItem != null && rightsManagedMessageItem.IsRestricted && !rightsManagedMessageItem.TryDecode(Utilities.CreateOutboundConversionOptions(this.userContext), false).Failed)
                         {
                             bool flag2 = false;
                             foreach (AttachmentHandle attachmentHandle in rightsManagedMessageItem.ProtectedAttachmentCollection)
                             {
                                 if (!attachmentHandle.IsInline)
                                 {
                                     flag2 = true;
                                     break;
                                 }
                             }
                             messageItem[MessageItemSchema.AllAttachmentsHidden] = !flag2;
                             rightsManagedMessageItem.AbandonChangesOnProtectedData();
                         }
                         messageItem.Save(SaveMode.ResolveConflicts);
                         if (DrmClientUtils.IsCachingOfLicenseDisabled(useLicenseAndUsageRights.UseLicense))
                         {
                             this.EnqueueLicensingError(asyncState.MessageId, SanitizedHtmlString.FromStringId(-1616549110, this.userCulture), asyncState.RequestCorrelator);
                         }
                         else
                         {
                             this.EnqueueLicenseAcquired(asyncState.MessageId, asyncState.RequestCorrelator);
                         }
                     }
                 }
             }
             finally
             {
                 if (this.userContext.LockedByCurrentThread() && flag)
                 {
                     this.userContext.Unlock();
                 }
             }
         }
     }
     catch (OwaLockTimeoutException arg)
     {
         IrmLicensingManager.Tracer.TraceError <OwaLockTimeoutException>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: timed-out at acquiring user context lock.  Exception: {0}", arg);
         this.EnqueueLicensingError(asyncState.MessageId, new SanitizedHtmlString(LocalizedStrings.GetNonEncoded(858913858)), asyncState.RequestCorrelator);
     }
     catch (ExchangeConfigurationException arg2)
     {
         IrmLicensingManager.Tracer.TraceError <ExchangeConfigurationException>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: caught exception.  Exception: {0}", arg2);
         this.HandleExchangeConfigurationException(asyncState.MessageId, asyncState.RequestCorrelator);
     }
     catch (RightsManagementException ex)
     {
         IrmLicensingManager.Tracer.TraceError <RightsManagementException>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: caught exception.  Exception: {0}", ex);
         this.HandleRightsManagementException(ex, asyncState.MessageId, asyncState.RequestCorrelator);
     }
     catch (StoragePermanentException ex2)
     {
         IrmLicensingManager.Tracer.TraceError <StoragePermanentException>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: caught exception.  Exception: {0}", ex2);
         this.EnqueueLicensingError(asyncState.MessageId, SanitizedHtmlString.Format(LocalizedStrings.GetHtmlEncoded(994351595, this.userCulture), new object[]
         {
             ex2.Message
         }), asyncState.RequestCorrelator);
     }
     catch (TransientException arg3)
     {
         IrmLicensingManager.Tracer.TraceError <TransientException>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: caught exception.  Exception: {0}", arg3);
         this.EnqueueLicensingError(asyncState.MessageId, new SanitizedHtmlString(LocalizedStrings.GetNonEncoded(858913858)), asyncState.RequestCorrelator);
     }
     catch (Exception ex3)
     {
         IrmLicensingManager.Tracer.TraceError <Exception>((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: caught exception.  Exception: {0}", ex3);
         if (Globals.SendWatsonReports)
         {
             IrmLicensingManager.Tracer.TraceError((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: sending watson report...");
             string data = string.Format("OWA version: {0}; Message Id: {1}", Globals.ApplicationVersion, asyncState.MessageId.ToBase64String());
             ExWatson.AddExtraData(data);
             ExWatson.SendReport(ex3, ReportOptions.None, null);
             IrmLicensingManager.Tracer.TraceError((long)this.GetHashCode(), "AcquireLicenseAndRightsCB: watson report has been sent.");
         }
     }
 }
Example #19
0
        // Token: 0x0600012F RID: 303 RVA: 0x00007734 File Offset: 0x00005934
        private static void LicenseMessage(IExchangePrincipal userPrincipal, MessageItem item)
        {
            string publishLicense;

            using (Attachment attachment = item.AttachmentCollection.Open(item.AttachmentCollection.GetHandles()[0]))
            {
                using (Stream contentStream = ((StreamAttachmentBase)attachment).GetContentStream(PropertyOpenMode.ReadOnly))
                {
                    using (DrmEmailMessageContainer drmEmailMessageContainer = new DrmEmailMessageContainer())
                    {
                        try
                        {
                            drmEmailMessageContainer.Load(contentStream, (object param0) => Streams.CreateTemporaryStorageStream());
                            publishLicense = drmEmailMessageContainer.PublishLicense;
                        }
                        catch (InvalidRpmsgFormatException arg)
                        {
                            LicensingProcessor.Tracer.TraceError <object, InvalidRpmsgFormatException>(0L, "{0}: LicensingProcessor:Failed to load RPMSG. {1}", TraceContext.Get(), arg);
                            return;
                        }
                    }
                }
            }
            UseLicenseAndUsageRights useLicenseAndUsageRights;

            try
            {
                useLicenseAndUsageRights = RmsClientManager.AcquireUseLicenseAndUsageRights(new RmsClientManagerContext(userPrincipal.MailboxInfo.OrganizationId, RmsClientManagerContext.ContextId.MessageId, item.InternetMessageId, publishLicense), publishLicense, userPrincipal.MailboxInfo.PrimarySmtpAddress.ToString(), userPrincipal.Sid, userPrincipal.RecipientTypeDetails);
            }
            catch (RightsManagementException ex)
            {
                LicensingProcessor.Tracer.TraceError <object, RightsManagementException>(0L, "{0}: LicensingProcessor:Failed to license message. {1}", TraceContext.Get(), ex);
                if (!ex.IsPermanent)
                {
                    throw new StorageTransientException(Strings.FailedToAcquireUseLicense, ex);
                }
                return;
            }
            catch (ExchangeConfigurationException ex2)
            {
                LicensingProcessor.Tracer.TraceError <object, ExchangeConfigurationException>(0L, "{0}: LicensingProcessor:Failed to license message. {1}", TraceContext.Get(), ex2);
                throw new StorageTransientException(Strings.FailedToReadIRMConfig, ex2);
            }
            LicensingProcessor.Tracer.TraceDebug(0L, "{0}: LicensingProcesssor: Saving licenses", new object[]
            {
                TraceContext.Get()
            });
            item.OpenAsReadWrite();
            item[MessageItemSchema.DRMRights]     = useLicenseAndUsageRights.UsageRights;
            item[MessageItemSchema.DRMExpiryTime] = useLicenseAndUsageRights.ExpiryTime;
            if (!DrmClientUtils.IsCachingOfLicenseDisabled(useLicenseAndUsageRights.UseLicense))
            {
                using (Stream stream = item.OpenPropertyStream(MessageItemSchema.DRMServerLicenseCompressed, PropertyOpenMode.Create))
                {
                    DrmEmailCompression.CompressUseLicense(useLicenseAndUsageRights.UseLicense, stream);
                }
            }
            item[MessageItemSchema.DRMPropsSignature] = useLicenseAndUsageRights.DRMPropsSignature;
            item.Save(SaveMode.ResolveConflicts);
            LicensingProcessor.Tracer.TraceDebug(0L, "{0}: LicensingProcesssor: message was saved successfully", new object[]
            {
                TraceContext.Get()
            });
        }
        private Stream LoadAttachmentDocument(bool isLoadingStream, out RightsManagedMessageDecryptionStatus decryptionStatus)
        {
            decryptionStatus = RightsManagedMessageDecryptionStatus.Success;
            StringBuilder       stringBuilder     = new StringBuilder();
            List <AttachmentId> list              = new List <AttachmentId>();
            UserContext         userContext       = this.owaContext.UserContext;
            string           queryStringParameter = Utilities.GetQueryStringParameter(this.owaContext.HttpContext.Request, "ewsid", false);
            bool             flag = string.IsNullOrEmpty(queryStringParameter);
            OwaStoreObjectId owaStoreObjectId;
            string           text;

            if (!flag)
            {
                stringBuilder.Append("service.svc/s/GetFileAttachment?id=");
                stringBuilder.Append(Utilities.UrlEncode(queryStringParameter));
                string canary15CookieValue = Utilities.GetCanary15CookieValue();
                if (canary15CookieValue != null)
                {
                    stringBuilder.Append("&X-OWA-CANARY=" + canary15CookieValue);
                }
                IdHeaderInformation idHeaderInformation = ServiceIdConverter.ConvertFromConcatenatedId(queryStringParameter, BasicTypes.Attachment, list);
                owaStoreObjectId = OwaStoreObjectId.CreateFromMailboxItemId(idHeaderInformation.ToStoreObjectId());
                text             = owaStoreObjectId.ToString();
            }
            else
            {
                text             = Utilities.GetQueryStringParameter(this.owaContext.HttpContext.Request, "id");
                owaStoreObjectId = OwaStoreObjectId.CreateFromString(text);
                stringBuilder.Append("attachment.ashx?attach=1&id=");
                stringBuilder.Append(Utilities.UrlEncode(text));
            }
            Stream result;

            using (Item item = Utilities.GetItem <Item>(userContext, owaStoreObjectId, new PropertyDefinition[]
            {
                ItemSchema.SentRepresentingDisplayName,
                ItemSchema.Subject
            }))
            {
                if (!Utilities.IsPublic(item) && userContext.IsIrmEnabled && isLoadingStream)
                {
                    item.OpenAsReadWrite();
                }
                if (Utilities.IsIrmRestricted(item))
                {
                    if (!userContext.IsIrmEnabled || userContext.IsBasicExperience)
                    {
                        decryptionStatus = RightsManagedMessageDecryptionStatus.FeatureDisabled;
                        return(null);
                    }
                    RightsManagedMessageItem rightsManagedMessageItem = (RightsManagedMessageItem)item;
                    if (!rightsManagedMessageItem.CanDecode)
                    {
                        decryptionStatus = RightsManagedMessageDecryptionStatus.NotSupported;
                        return(null);
                    }
                    try
                    {
                        Utilities.IrmDecryptIfRestricted(item, userContext, true);
                    }
                    catch (RightsManagementPermanentException exception)
                    {
                        decryptionStatus = RightsManagedMessageDecryptionStatus.CreateFromException(exception);
                        return(null);
                    }
                    catch (RightsManagementTransientException exception2)
                    {
                        decryptionStatus = RightsManagedMessageDecryptionStatus.CreateFromException(exception2);
                        return(null);
                    }
                }
                this.messageFrom    = ItemUtility.GetProperty <string>(item, ItemSchema.SentRepresentingDisplayName, string.Empty);
                this.messageSubject = ItemUtility.GetProperty <string>(item, ItemSchema.Subject, string.Empty);
                this.messageId      = text;
                if (flag)
                {
                    Utilities.FillAttachmentIdList(item, this.owaContext.HttpContext.Request, list);
                }
                using (StreamAttachment streamAttachment = Utilities.GetAttachment(item, list, userContext) as StreamAttachment)
                {
                    if (streamAttachment == null)
                    {
                        throw new OwaInvalidRequestException("Attachment is not a stream attachment");
                    }
                    this.mimeType     = (streamAttachment.ContentType ?? streamAttachment.CalculatedContentType);
                    this.fileName     = ((!string.IsNullOrEmpty(streamAttachment.DisplayName)) ? streamAttachment.DisplayName : streamAttachment.FileName);
                    this.fileSize     = streamAttachment.Size;
                    this.documentPath = this.fileName;
                    this.documentIdStringBuilder.Append(Convert.ToBase64String(userContext.MailboxSession.MailboxOwner.MailboxInfo.GetDatabaseGuid().ToByteArray()));
                    this.documentIdStringBuilder.Append("-");
                    for (int i = 0; i < list.Count; i++)
                    {
                        this.documentIdStringBuilder.Append(list[i].ToBase64String());
                        this.documentIdStringBuilder.Append("-");
                        if (flag)
                        {
                            stringBuilder.Append("&attid");
                            stringBuilder.Append(i.ToString(CultureInfo.InstalledUICulture));
                            stringBuilder.Append("=");
                            stringBuilder.Append(Utilities.UrlEncode(list[i].ToBase64String()));
                        }
                    }
                    if (flag)
                    {
                        stringBuilder.Append("&attcnt=");
                        stringBuilder.Append(list.Count);
                    }
                    this.documentIdStringBuilder.Append(streamAttachment.LastModifiedTime.UtcTicks);
                    this.openLink = stringBuilder.ToString();
                    if (isLoadingStream)
                    {
                        Stream       contentStream = streamAttachment.GetContentStream();
                        MsoIpiResult msoIpiResult  = MsoIpiResult.Unknown;
                        try
                        {
                            msoIpiResult = ProtectorsManager.Instance.IsProtected(this.fileName, contentStream);
                        }
                        catch (AttachmentProtectionException exception3)
                        {
                            decryptionStatus = new RightsManagedMessageDecryptionStatus(RightsManagementFailureCode.CorruptData, exception3);
                            return(null);
                        }
                        if (msoIpiResult == MsoIpiResult.Protected)
                        {
                            this.isIrmProtected = true;
                            contentStream.Dispose();
                            if (!userContext.IsIrmEnabled || userContext.IsBasicExperience)
                            {
                                decryptionStatus = RightsManagedMessageDecryptionStatus.FeatureDisabled;
                                result           = null;
                            }
                            else
                            {
                                UseLicenseAndUsageRights useLicenseAndUsageRights;
                                bool   flag2;
                                Stream stream;
                                try
                                {
                                    stream = StreamAttachment.OpenRestrictedAttachment(streamAttachment, this.owaContext.ExchangePrincipal.MailboxInfo.OrganizationId, this.owaContext.ExchangePrincipal.MailboxInfo.PrimarySmtpAddress.ToString(), this.owaContext.LogonIdentity.UserSid, this.owaContext.ExchangePrincipal.RecipientTypeDetails, out useLicenseAndUsageRights, out flag2);
                                }
                                catch (RightsManagementPermanentException exception4)
                                {
                                    decryptionStatus = RightsManagedMessageDecryptionStatus.CreateFromException(exception4);
                                    return(null);
                                }
                                catch (RightsManagementTransientException exception5)
                                {
                                    decryptionStatus = RightsManagedMessageDecryptionStatus.CreateFromException(exception5);
                                    return(null);
                                }
                                if (flag2 && ObjectClass.IsMessage(item.ClassName, false) && !Utilities.IsIrmRestricted(item))
                                {
                                    object obj = item.TryGetProperty(MessageItemSchema.IsDraft);
                                    if (obj is bool && !(bool)obj && !DrmClientUtils.IsCachingOfLicenseDisabled(useLicenseAndUsageRights.UseLicense))
                                    {
                                        streamAttachment[AttachmentSchema.DRMRights]     = useLicenseAndUsageRights.UsageRights;
                                        streamAttachment[AttachmentSchema.DRMExpiryTime] = useLicenseAndUsageRights.ExpiryTime;
                                        using (Stream stream2 = streamAttachment.OpenPropertyStream(AttachmentSchema.DRMServerLicenseCompressed, PropertyOpenMode.Create))
                                        {
                                            DrmEmailCompression.CompressUseLicense(useLicenseAndUsageRights.UseLicense, stream2);
                                        }
                                        streamAttachment[AttachmentSchema.DRMPropsSignature] = useLicenseAndUsageRights.DRMPropsSignature;
                                        streamAttachment.Save();
                                        item.Save(SaveMode.ResolveConflicts);
                                    }
                                }
                                string      conversationOwnerFromPublishLicense = DrmClientUtils.GetConversationOwnerFromPublishLicense(useLicenseAndUsageRights.PublishingLicense);
                                RmsTemplate rmsTemplate = RmsTemplate.CreateFromPublishLicense(useLicenseAndUsageRights.PublishingLicense);
                                this.isPrintRestricted = !useLicenseAndUsageRights.UsageRights.IsUsageRightGranted(ContentRight.Print);
                                this.isCopyRestricted  = !useLicenseAndUsageRights.UsageRights.IsUsageRightGranted(ContentRight.Extract);
                                SanitizingStringBuilder <OwaHtml> sanitizingStringBuilder = new SanitizingStringBuilder <OwaHtml>();
                                string str = string.Format(LocalizedStrings.GetNonEncoded(-500320626), rmsTemplate.Name, rmsTemplate.Description);
                                sanitizingStringBuilder.Append(str);
                                if (!string.IsNullOrEmpty(conversationOwnerFromPublishLicense))
                                {
                                    sanitizingStringBuilder.Append("<br>");
                                    sanitizingStringBuilder.Append(string.Format(LocalizedStrings.GetNonEncoded(1670455506), conversationOwnerFromPublishLicense));
                                }
                                this.irmInfobarMessage = sanitizingStringBuilder.ToSanitizedString <SanitizedHtmlString>();
                                result = stream;
                            }
                        }
                        else
                        {
                            contentStream.Seek(0L, SeekOrigin.Begin);
                            result = contentStream;
                        }
                    }
                    else
                    {
                        result = null;
                    }
                }
            }
            return(result);
        }