Exemplo n.º 1
0
        private Uri Discover()
        {
            string sharerIdentity = this.subscription.SharerIdentity;
            Uri    result;

            using (AutodiscoverClient autodiscoverClient = new AutodiscoverClient())
            {
                autodiscoverClient.RequestedServerVersion = DefaultBinding_Autodiscover.Exchange2010RequestedServerVersion;
                autodiscoverClient.Authenticator          = this.CreateAuthenticator(Offer.Autodiscover);
                autodiscoverClient.Proxy     = this.WebProxy;
                autodiscoverClient.UserAgent = "ExchangeSharingSync";
                ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 1351, "Discover", "f:\\15.00.1497\\sources\\dev\\infoworker\\src\\common\\Sharing\\SharingEngine.cs");
                string[] autodiscoverTrustedHosters = topologyConfigurationSession.GetAutodiscoverTrustedHosters();
                if (autodiscoverTrustedHosters != null)
                {
                    autodiscoverClient.AllowedHostnames.AddRange(autodiscoverTrustedHosters);
                }
                UserSettings userSettings = SharingEngine.SingleGetUserSettings.Discover(autodiscoverClient, sharerIdentity);
                if (userSettings.IsSettingError("ExternalEwsUrl"))
                {
                    SharingEngine.Tracer.TraceError <UserSettings>((long)this.GetHashCode(), "ExternalEwsUrl not present in response: {0}", userSettings);
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                UserSetting setting = userSettings.GetSetting("ExternalEwsUrl");
                if (setting == null)
                {
                    SharingEngine.Tracer.TraceError <UserSettings>((long)this.GetHashCode(), "ExternalEwsUrl not present in response: {0}", userSettings);
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                StringSetting stringSetting = setting as StringSetting;
                if (stringSetting == null)
                {
                    SharingEngine.Tracer.TraceError <Type>((long)this.GetHashCode(), "Unexpected type for ExternalEwsUrl in response. Type is {0}", setting.GetType());
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                if (string.IsNullOrEmpty(stringSetting.Value))
                {
                    SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "Empty value returned for ExternalEwsUrl in response.");
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                if (!Uri.IsWellFormedUriString(stringSetting.Value, UriKind.Absolute))
                {
                    SharingEngine.Tracer.TraceError <string>((long)this.GetHashCode(), "Value returned for ExternalEwsUrl is not well-formed URL: {0}", stringSetting.Value);
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                Uri uri = new Uri(EwsWsSecurityUrl.Fix(stringSetting.Value));
                if (uri.Scheme != Uri.UriSchemeHttps)
                {
                    SharingEngine.Tracer.TraceError <string>((long)this.GetHashCode(), "Response has non-HTTPS ExternalEwsUrl: {0}", stringSetting.Value);
                    throw new AutodiscoverException(Strings.UnexpectedUserResponses, userSettings);
                }
                SharingEngine.Tracer.TraceDebug <Uri>((long)this.GetHashCode(), "Received valid response: {0}", uri);
                result = uri;
            }
            return(result);
        }
Exemplo n.º 2
0
 public void Authenticate(CustomSoapHttpClientProtocol client)
 {
     ProxyAuthenticator.SecurityTracer.TraceDebug <object, AuthenticatorType>((long)this.GetHashCode(), "{0}: Authenticating client with {1}", TraceContext.Get(), this.AuthenticatorType);
     client.Authenticator = this.authenticator;
     if (this.AuthenticatorType == AuthenticatorType.WSSecurity)
     {
         client.Url = EwsWsSecurityUrl.Fix(client.Url);
         client.ConnectionGroupName = "WS>";
         return;
     }
     client.Url = EwsWsSecurityUrl.FixForAnonymous(client.Url);
     client.UnsafeAuthenticatedConnectionSharing = Configuration.UnsafeAuthenticatedConnectionSharing.Value;
     client.ConnectionGroupName = "NC>";
 }
Exemplo n.º 3
0
        protected AutoDiscoverRequestResult GetAutodiscoverResult(string urlValue, string versionValue, EmailAddress emailAddress)
        {
            if (string.IsNullOrEmpty(urlValue) || !Uri.IsWellFormedUriString(urlValue, UriKind.Absolute))
            {
                SoapAutoDiscoverRequest.AutoDiscoverTracer.TraceError((long)this.GetHashCode(), "{0}: Request '{1}' got ExternalEwsUrl setting for user {2} has invalid value: {3}", new object[]
                {
                    TraceContext.Get(),
                    this,
                    emailAddress.Address,
                    urlValue
                });
                return(null);
            }
            int serverVersion = Globals.E14Version;

            if (!string.IsNullOrEmpty(versionValue))
            {
                Exception ex = null;
                try
                {
                    Version version = new Version(versionValue);
                    serverVersion = version.ToInt();
                }
                catch (ArgumentException ex2)
                {
                    ex = ex2;
                }
                catch (FormatException ex3)
                {
                    ex = ex3;
                }
                catch (OverflowException ex4)
                {
                    ex = ex4;
                }
                if (ex != null)
                {
                    SoapAutoDiscoverRequest.AutoDiscoverTracer.TraceError <object, Exception>((long)this.GetHashCode(), "{0}: Exception parsing version: {1}", TraceContext.Get(), ex);
                }
            }
            string url = urlValue;

            if (this.authenticator.ProxyAuthenticator != null && this.authenticator.ProxyAuthenticator.AuthenticatorType == AuthenticatorType.WSSecurity)
            {
                url = EwsWsSecurityUrl.Fix(url);
            }
            return(new AutoDiscoverRequestResult(this.TargetUri, null, null, new WebServiceUri(url, null, UriSource.EmailDomain, serverVersion), null, null));
        }
Exemplo n.º 4
0
        private string GetEnterpriseOrE14SharingUrl(ExchangePrincipal exchangePrincipal)
        {
            SharedFolderDataEncryption.Tracer.TraceDebug <ExchangePrincipal, bool>((long)this.GetHashCode(), "Entering GetEnterpriseOrE14SharingUrl - mailbox {0}, isMultitenancyEnabled={1}", exchangePrincipal, this.IsMultitenancyEnabled);
            ServiceTopology            serviceTopology = this.IsMultitenancyEnabled ? ServiceTopology.GetCurrentLegacyServiceTopology("f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\SharedFolderDataEncryption.cs", "GetEnterpriseOrE14SharingUrl", 655) : ServiceTopology.GetCurrentServiceTopology("f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\SharedFolderDataEncryption.cs", "GetEnterpriseOrE14SharingUrl", 655);
            IList <WebServicesService> list            = serviceTopology.FindAll <WebServicesService>(exchangePrincipal, ClientAccessType.External, SharedFolderDataEncryption.serviceVersionFilter, "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\SharedFolderDataEncryption.cs", "GetEnterpriseOrE14SharingUrl", 658);

            if (list.Count != 0)
            {
                return(EwsWsSecurityUrl.Fix(list[0].Url.ToString()));
            }
            SharedFolderDataEncryption.Tracer.TraceDebug <ExchangePrincipal>((long)this.GetHashCode(), "Unable to find a CAS with external access in same site of user {0}. Trying other sites.", exchangePrincipal);
            WebServicesService webServicesService = serviceTopology.FindAny <WebServicesService>(ClientAccessType.External, SharedFolderDataEncryption.serviceVersionFilter, "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\SharedFolderDataEncryption.cs", "GetEnterpriseOrE14SharingUrl", 671);

            if (webServicesService == null)
            {
                throw new NoExternalEwsAvailableException();
            }
            return(EwsWsSecurityUrl.Fix(webServicesService.Url.ToString()));
        }
Exemplo n.º 5
0
        private string GetE15MultitenancySharingUrl(ExchangePrincipal exchangePrincipal, IFrontEndLocator frontEndLocator)
        {
            SharedFolderDataEncryption.Tracer.TraceDebug <ExchangePrincipal>((long)this.GetHashCode(), "Entering GetE15MultitenancySharingUrl for mailbox {0}", exchangePrincipal);
            Uri       uri = null;
            Exception ex  = null;

            try
            {
                uri = frontEndLocator.GetWebServicesUrl(exchangePrincipal);
            }
            catch (ServerNotFoundException ex2)
            {
                ex = ex2;
            }
            catch (ADTransientException ex3)
            {
                ex = ex3;
            }
            catch (DataSourceOperationException ex4)
            {
                ex = ex4;
            }
            catch (DataValidationException ex5)
            {
                ex = ex5;
            }
            finally
            {
                if (ex != null)
                {
                    throw new NoExternalEwsAvailableException(ex);
                }
            }
            string text = uri.ToString();

            SharedFolderDataEncryption.Tracer.TraceDebug <string>((long)this.GetHashCode(), "GetE15MultitenancySharingUrl - EWS url '{0}'", text);
            string text2 = EwsWsSecurityUrl.Fix(text);

            SharedFolderDataEncryption.Tracer.TraceDebug <string>((long)this.GetHashCode(), "GetE15MultitenancySharingUrl - fixed EWS url '{0}'", text2);
            return(text2);
        }
        private void Discover(ExchangePrincipal principal, ADUser executingUser, out string ewsEndpoint, out DelegationTokenRequest ewsTokenRequest)
        {
            SmtpAddress              value           = principal.MailboxInfo.RemoteIdentity.Value;
            ADSessionSettings        sessionSettings = ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(OrganizationId.ForestWideOrgId);
            IRecipientSession        tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, true, ConsistencyMode.FullyConsistent, null, sessionSettings, ConfigScopes.TenantSubTree, 168, "Discover", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Search\\MailboxSearch\\MailboxSearchEwsClient.cs");
            ADUser                   aduser = null;
            TransportConfigContainer transportConfigContainer = DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(true, ConsistencyMode.IgnoreInvalid, sessionSettings, 171, "Discover", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Search\\MailboxSearch\\MailboxSearchEwsClient.cs").FindSingletonConfigurationObject <TransportConfigContainer>();

            if (transportConfigContainer != null && transportConfigContainer.OrganizationFederatedMailbox != SmtpAddress.NullReversePath)
            {
                SmtpAddress  organizationFederatedMailbox = transportConfigContainer.OrganizationFederatedMailbox;
                ProxyAddress proxyAddress = null;
                try
                {
                    proxyAddress = ProxyAddress.Parse(organizationFederatedMailbox.ToString());
                }
                catch (ArgumentException ex)
                {
                    ExTraceGlobals.SessionTracer.TraceError <string>((long)this.GetHashCode(), "Proxy address of organization federated mailbox is invalid: {0}", ex.ToString());
                }
                if (proxyAddress != null && !(proxyAddress is InvalidProxyAddress))
                {
                    aduser = (tenantOrRootOrgRecipientSession.FindByProxyAddress(proxyAddress) as ADUser);
                }
            }
            OrganizationIdCacheValue organizationIdCacheValue = OrganizationIdCache.Singleton.Get(OrganizationId.ForestWideOrgId);
            OrganizationRelationship organizationRelationship = organizationIdCacheValue.GetOrganizationRelationship(value.Domain);

            if (aduser == null || organizationRelationship == null)
            {
                throw new OrganizationNotFederatedException();
            }
            DelegationTokenRequest request = new DelegationTokenRequest
            {
                FederatedIdentity = aduser.GetFederatedIdentity(),
                EmailAddress      = aduser.GetFederatedSmtpAddress().ToString(),
                Target            = organizationRelationship.GetTokenTarget(),
                Offer             = Offer.Autodiscover
            };
            FedOrgCredentials credentials = new FedOrgCredentials(request, this.GetSecurityTokenService(aduser.OrganizationId));
            Uri uri = null;

            using (AutoDiscoverUserSettingsClient autoDiscoverUserSettingsClient = AutoDiscoverUserSettingsClient.CreateInstance(DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, sessionSettings, 215, "Discover", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Search\\MailboxSearch\\MailboxSearchEwsClient.cs"), credentials, value, organizationRelationship.TargetAutodiscoverEpr, MailboxSearchEwsClient.AutoDiscoverRequestedSettings))
            {
                UserSettings  userSettings  = autoDiscoverUserSettingsClient.Discover();
                StringSetting stringSetting = userSettings.GetSetting("ExternalEwsUrl") as StringSetting;
                if (stringSetting == null || !Uri.TryCreate(stringSetting.Value, UriKind.Absolute, out uri))
                {
                    throw new AutoDAccessException(ServerStrings.AutoDRequestFailed);
                }
            }
            ewsEndpoint = EwsWsSecurityUrl.Fix(uri.ToString());
            string text = null;

            if (executingUser.EmailAddresses != null && executingUser.EmailAddresses.Count > 0)
            {
                List <string> federatedEmailAddresses = executingUser.GetFederatedEmailAddresses();
                if (federatedEmailAddresses != null && federatedEmailAddresses.Count > 0)
                {
                    text = federatedEmailAddresses[0];
                }
            }
            if (string.IsNullOrEmpty(text))
            {
                ewsTokenRequest = new DelegationTokenRequest
                {
                    FederatedIdentity = aduser.GetFederatedIdentity(),
                    EmailAddress      = aduser.GetFederatedSmtpAddress().ToString(),
                    Target            = organizationRelationship.GetTokenTarget(),
                    Offer             = Offer.MailboxSearch
                };
                return;
            }
            ewsTokenRequest = new DelegationTokenRequest
            {
                FederatedIdentity = executingUser.GetFederatedIdentity(),
                EmailAddress      = text.ToString(),
                Target            = organizationRelationship.GetTokenTarget(),
                Offer             = Offer.MailboxSearch
            };
        }
Exemplo n.º 7
0
        public Dictionary <GroupId, List <MailboxInfo> > FindEwsEndpoints(out long localDiscoverTime, out long autoDiscoverTime)
        {
            Stopwatch stopwatch = new Stopwatch();

            localDiscoverTime = 0L;
            autoDiscoverTime  = 0L;
            stopwatch.Start();
            List <MailboxInfo> list;
            string             text;

            this.FilterLocalForestMailboxes(out list, out text);
            stopwatch.Stop();
            localDiscoverTime = stopwatch.ElapsedMilliseconds;
            Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, long>((long)this.GetHashCode(), "Correlation Id:{0}. Mapping local mailboxes to servers took {1}ms", this.callerInfo.QueryCorrelationId, localDiscoverTime);
            if (list == null || list.Count == 0)
            {
                return(this.mailboxGroups);
            }
            string searchId = string.Empty;
            Match  match    = Regex.Match(this.callerInfo.UserAgent, "SID=([a-fA-F0-9\\-]*)");

            if (match.Success && match.Groups != null && match.Groups.Count > 1)
            {
                searchId = match.Groups[1].Value;
            }
            Uri url = null;
            EndPointDiscoveryInfo endPointDiscoveryInfo;
            bool flag = RemoteDiscoveryEndPoint.TryGetDiscoveryEndPoint(this.orgId, text, this.GetOrgIdCacheValue, this.GetIntraOrganizationConnector, this.GetOrganizationRelationShip, out url, out endPointDiscoveryInfo);

            if (endPointDiscoveryInfo != null && endPointDiscoveryInfo.Status != EndPointDiscoveryInfo.DiscoveryStatus.Success)
            {
                SearchEventLogger.Instance.LogSearchErrorEvent(searchId, endPointDiscoveryInfo.Message);
            }
            if (!flag)
            {
                Factory.Current.MailboxGroupGeneratorTracer.TraceDebug <Guid, string>((long)this.GetHashCode(), "Correlation Id:{0}. Unable to find the discovery end point for domain {1}", this.callerInfo.QueryCorrelationId, text);
                GroupId key = new GroupId(new MultiMailboxSearchException(Strings.CouldNotFindOrgRelationship(text)));
                this.mailboxGroups.Add(key, list);
                return(this.mailboxGroups);
            }
            Factory.Current.MailboxGroupGeneratorTracer.TraceDebug <Guid, string, Uri>((long)this.GetHashCode(), "Correlation Id:{0}. EWS endpoint for domain {1} is {2}", this.callerInfo.QueryCorrelationId, text, EwsWsSecurityUrl.FixForAnonymous(url));
            OAuthCredentials oauthCredentialsForAppToken = OAuthCredentials.GetOAuthCredentialsForAppToken(this.orgId, text);

            stopwatch.Restart();
            List <MailboxInfo> list2 = (from mailboxInfo in list
                                        where mailboxInfo.IsArchive
                                        select mailboxInfo).ToList <MailboxInfo>();
            List <MailboxInfo> list3 = (from mailboxInfo in list
                                        where !mailboxInfo.IsArchive
                                        select mailboxInfo).ToList <MailboxInfo>();

            if (list2.Count > 0)
            {
                Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover started for cross premise archive mailboxes.", this.callerInfo.QueryCorrelationId, list2.Count);
                this.DoAutodiscover(list2, EwsWsSecurityUrl.FixForAnonymous(url), oauthCredentialsForAppToken);
                Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover completed for cross premise archive mailboxes.", this.callerInfo.QueryCorrelationId, list2.Count);
            }
            if (list3.Count > 0)
            {
                Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover started for cross premise primary mailboxes.", this.callerInfo.QueryCorrelationId, list3.Count);
                this.DoAutodiscover(list3, EwsWsSecurityUrl.FixForAnonymous(url), oauthCredentialsForAppToken);
                Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover completed for cross premise primary mailboxes.", this.callerInfo.QueryCorrelationId, list3.Count);
            }
            stopwatch.Stop();
            autoDiscoverTime = stopwatch.ElapsedMilliseconds;
            Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, long>((long)this.GetHashCode(), "Correlation Id:{0}. Autodiscover call took {1}ms", this.callerInfo.QueryCorrelationId, autoDiscoverTime);
            return(this.mailboxGroups);
        }
        public static AutoDiscoverUserSettingsClient CreateInstance(ITopologyConfigurationSession topologyConfigurationSession, FedOrgCredentials credentials, SmtpAddress identity, Uri autoDiscoveryEndpoint, string[] requestedSettings)
        {
            Util.ThrowOnNullArgument(credentials, "credentials");
            RequestedToken token;

            try
            {
                token = credentials.GetToken();
            }
            catch (WSTrustException ex)
            {
                string text  = identity.ToString();
                string text2 = ex.ToString();
                StorageGlobals.EventLogger.LogEvent(StorageEventLogConstants.Tuple_AutoDiscoverFailedToAquireSecurityToken, text, new object[]
                {
                    text,
                    text2
                });
                ExTraceGlobals.XtcTracer.TraceError <string, string>(0L, "AutoDiscover request failed for {0}, failed to aquire security token. Exception: {1}.", text, text2);
                throw new AutoDAccessException(ServerStrings.AutoDFailedToGetToken, ex);
            }
            return(new AutoDiscoverUserSettingsClient(topologyConfigurationSession, SoapHttpClientAuthenticator.Create(token), EwsWsSecurityUrl.Fix(autoDiscoveryEndpoint), identity, requestedSettings));
        }
        // Token: 0x0600059B RID: 1435 RVA: 0x0002B16C File Offset: 0x0002936C
        public static Uri DiscoverCloudArchiveEwsUrl(ADUser user)
        {
            Uri    result = null;
            string text   = null;
            string domain = user.ArchiveDomain.Domain;
            Uri    uri    = null;
            EndPointDiscoveryInfo endPointDiscoveryInfo;
            bool flag = RemoteDiscoveryEndPoint.TryGetDiscoveryEndPoint(OrganizationId.ForestWideOrgId, domain, null, null, null, out uri, out endPointDiscoveryInfo);

            if (endPointDiscoveryInfo != null && endPointDiscoveryInfo.Status != EndPointDiscoveryInfo.DiscoveryStatus.Success)
            {
                ElcEwsClientHelper.Tracer.TraceDebug <SmtpAddress, EndPointDiscoveryInfo.DiscoveryStatus, string>(0L, "Getting autodiscover url for {0} encountered problem with status {1}. {2}", user.PrimarySmtpAddress, endPointDiscoveryInfo.Status, endPointDiscoveryInfo.Message);
            }
            if (!flag || uri == null)
            {
                ElcEwsClientHelper.Tracer.TraceError <SmtpAddress>(0L, "Failed to get autodiscover URL for {0}.", user.PrimarySmtpAddress);
                return(null);
            }
            SmtpAddress      archiveAddress = new SmtpAddress(SmtpProxyAddress.EncapsulateExchangeGuid(domain, user.ArchiveGuid));
            Guid             value          = Guid.NewGuid();
            OAuthCredentials oauthCredentialsForAppActAsToken = OAuthCredentials.GetOAuthCredentialsForAppActAsToken(OrganizationId.ForestWideOrgId, user, domain);

            oauthCredentialsForAppActAsToken.ClientRequestId = new Guid?(value);
            AutodiscoverService service = new AutodiscoverService(EwsWsSecurityUrl.FixForAnonymous(uri), 4)
            {
                Credentials     = new OAuthCredentials(oauthCredentialsForAppActAsToken),
                PreAuthenticate = true,
                UserAgent       = ElcEwsClientHelper.GetOAuthUserAgent("ElcAutoDiscoverClient")
            };

            service.ClientRequestId       = value.ToString();
            service.ReturnClientRequestId = true;
            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(ElcEwsClientHelper.CertificateErrorHandler));
                GetUserSettingsResponse response = null;
                Exception arg   = null;
                bool      flag2 = ElcEwsClientHelper.ExecuteEwsCall(delegate
                {
                    response = service.GetUserSettings(archiveAddress.ToString(), new UserSettingName[]
                    {
                        58
                    });
                }, out arg);
                if (flag2)
                {
                    if (response.ErrorCode == null)
                    {
                        if (!response.TryGetSettingValue <string>(58, ref text) || string.IsNullOrEmpty(text))
                        {
                            ElcEwsClientHelper.Tracer.TraceError <SmtpAddress, SmtpAddress>(0L, "Sucessfully called autodiscover, but did not retrieve a url for {0}/{1}.", user.PrimarySmtpAddress, archiveAddress);
                        }
                    }
                    else
                    {
                        ElcEwsClientHelper.Tracer.TraceError(0L, "Unable to autodiscover EWS endpoint for {0}/{1}, error code: {2}, message {3}.", new object[]
                        {
                            user.PrimarySmtpAddress,
                            archiveAddress,
                            response.ErrorCode,
                            response.ErrorMessage
                        });
                    }
                }
                else
                {
                    ElcEwsClientHelper.Tracer.TraceError <SmtpAddress, SmtpAddress, Exception>(0L, "Unable to autodiscover EWS endpoint for {0}/{1}, exception {2}.", user.PrimarySmtpAddress, archiveAddress, arg);
                }
            }
            finally
            {
                ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Remove(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(ElcEwsClientHelper.CertificateErrorHandler));
            }
            if (!string.IsNullOrEmpty(text))
            {
                result = new Uri(text);
            }
            return(result);
        }
 // Token: 0x06000170 RID: 368 RVA: 0x00009C70 File Offset: 0x00007E70
 internal void Synchronize(object argument)
 {
     try
     {
         ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(CertificateValidation.CertificateErrorHandler));
         Guid b = (Guid)argument;
         SearchEventLogger.Instance.LogSyncDiscoveryHoldToExchangeOnlineStartEvent(b.ToString());
         DiscoverySearchDataProvider discoverySearchDataProvider = new DiscoverySearchDataProvider(OrganizationId.ForestWideOrgId);
         if (discoverySearchDataProvider.ObjectGuid == b)
         {
             Dictionary <string, MailboxDiscoverySearch> dictionary = new Dictionary <string, MailboxDiscoverySearch>();
             SmtpAddress discoveryHolds = DiscoveryHoldSynchronizer.GetDiscoveryHolds(discoverySearchDataProvider, dictionary);
             SearchEventLogger.Instance.LogSyncDiscoveryHoldToExchangeOnlineDetailsEvent(dictionary.Count, discoveryHolds.ToString());
             if (discoveryHolds != SmtpAddress.Empty)
             {
                 Uri    uri = null;
                 string str = string.Empty;
                 EndPointDiscoveryInfo endPointDiscoveryInfo;
                 bool flag = RemoteDiscoveryEndPoint.TryGetDiscoveryEndPoint(OrganizationId.ForestWideOrgId, discoveryHolds.Domain, null, null, null, out uri, out endPointDiscoveryInfo);
                 if (endPointDiscoveryInfo != null && endPointDiscoveryInfo.Status != EndPointDiscoveryInfo.DiscoveryStatus.Success)
                 {
                     str = endPointDiscoveryInfo.Message;
                     DiscoveryHoldSynchronizer.Tracer.TraceDebug <EndPointDiscoveryInfo.DiscoveryStatus, string>((long)this.GetHashCode(), "Getting autodiscover url encountered problem with status {0}. {1}", endPointDiscoveryInfo.Status, endPointDiscoveryInfo.Message);
                 }
                 if (flag && uri != null)
                 {
                     uri = EwsWsSecurityUrl.FixForAnonymous(uri);
                     AutodiscoverService autodiscoverService = new AutodiscoverService(uri, 4);
                     OAuthCredentials    credentials         = new OAuthCredentials(OAuthCredentials.GetOAuthCredentialsForAppToken(OrganizationId.ForestWideOrgId, discoveryHolds.Domain));
                     autodiscoverService.Credentials = credentials;
                     GetUserSettingsResponse userSettings = autodiscoverService.GetUserSettings(discoveryHolds.ToString(), new UserSettingName[]
                     {
                         58
                     });
                     if (userSettings != null && userSettings.ErrorCode == null && userSettings.Settings != null && userSettings.Settings.ContainsKey(58))
                     {
                         string          uriString       = userSettings.Settings[58].ToString();
                         ExchangeService exchangeService = new ExchangeService(4);
                         exchangeService.Credentials     = credentials;
                         exchangeService.Url             = new Uri(uriString);
                         exchangeService.ManagementRoles = new ManagementRoles(null, "LegalHoldApplication");
                         GetDiscoverySearchConfigurationResponse discoverySearchConfiguration = exchangeService.GetDiscoverySearchConfiguration(null, false, true);
                         if (discoverySearchConfiguration.Result == 2)
                         {
                             SearchEventLogger.Instance.LogFailedToSyncDiscoveryHoldToExchangeOnlineEvent(string.Format("ErrorCode={0}&ErrorMessage={1}", discoverySearchConfiguration.ErrorCode, discoverySearchConfiguration.ErrorMessage));
                             goto IL_402;
                         }
                         foreach (DiscoverySearchConfiguration discoverySearchConfiguration2 in discoverySearchConfiguration.DiscoverySearchConfigurations)
                         {
                             MailboxDiscoverySearch mailboxDiscoverySearch = null;
                             if (dictionary.TryGetValue(discoverySearchConfiguration2.InPlaceHoldIdentity, out mailboxDiscoverySearch))
                             {
                                 if (mailboxDiscoverySearch.Name != discoverySearchConfiguration2.SearchId)
                                 {
                                     if (DiscoveryHoldSynchronizer.CallSetHoldOnMailboxes(exchangeService, discoverySearchConfiguration2.SearchId, 2, discoverySearchConfiguration2.SearchQuery, discoverySearchConfiguration2.InPlaceHoldIdentity, null))
                                     {
                                         DiscoveryHoldSynchronizer.CallSetHoldOnMailboxes(exchangeService, mailboxDiscoverySearch.Name, 0, mailboxDiscoverySearch.CalculatedQuery, mailboxDiscoverySearch.InPlaceHoldIdentity, mailboxDiscoverySearch.ItemHoldPeriod.ToString());
                                     }
                                 }
                                 else
                                 {
                                     DiscoveryHoldSynchronizer.CallSetHoldOnMailboxes(exchangeService, mailboxDiscoverySearch.Name, 1, mailboxDiscoverySearch.CalculatedQuery, mailboxDiscoverySearch.InPlaceHoldIdentity, mailboxDiscoverySearch.ItemHoldPeriod.ToString());
                                 }
                                 dictionary.Remove(discoverySearchConfiguration2.InPlaceHoldIdentity);
                             }
                             else if (discoverySearchConfiguration2.ManagedByOrganization == "b5d6efcd-1aee-42b9-b168-6fef285fe613")
                             {
                                 DiscoveryHoldSynchronizer.CallSetHoldOnMailboxes(exchangeService, discoverySearchConfiguration2.SearchId, 2, discoverySearchConfiguration2.SearchQuery, discoverySearchConfiguration2.InPlaceHoldIdentity, null);
                             }
                         }
                         using (Dictionary <string, MailboxDiscoverySearch> .ValueCollection.Enumerator enumerator = dictionary.Values.GetEnumerator())
                         {
                             while (enumerator.MoveNext())
                             {
                                 MailboxDiscoverySearch mailboxDiscoverySearch2 = enumerator.Current;
                                 DiscoveryHoldSynchronizer.CallSetHoldOnMailboxes(exchangeService, mailboxDiscoverySearch2.Name, 0, mailboxDiscoverySearch2.CalculatedQuery, mailboxDiscoverySearch2.InPlaceHoldIdentity, mailboxDiscoverySearch2.ItemHoldPeriod.ToString());
                             }
                             goto IL_402;
                         }
                     }
                     string str2 = string.Empty;
                     if (userSettings != null && userSettings.ErrorCode != null)
                     {
                         str2 = string.Format("ErrorCode={0}&ErrorMessage={1}", userSettings.ErrorCode, userSettings.ErrorMessage);
                     }
                     SearchEventLogger.Instance.LogFailedToSyncDiscoveryHoldToExchangeOnlineEvent("Failed to get autodiscover settings. " + str2);
                 }
                 else
                 {
                     SearchEventLogger.Instance.LogFailedToSyncDiscoveryHoldToExchangeOnlineEvent("Failed to get autodiscover URL. " + str);
                 }
             }
         }
         IL_402 :;
     }
     finally
     {
         ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Remove(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(CertificateValidation.CertificateErrorHandler));
     }
 }
Exemplo n.º 11
0
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            base.InternalProcessRecord();
            ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 66, "InternalProcessRecord", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\SystemConfigurationTasks\\Federation\\GetFederationInformation.cs");

            string[] autodiscoverTrustedHosters = topologyConfigurationSession.GetAutodiscoverTrustedHosters();
            using (AutodiscoverClient autodiscoverClient = new AutodiscoverClient())
            {
                Server localServer = LocalServerCache.LocalServer;
                if (localServer != null && localServer.InternetWebProxy != null)
                {
                    base.WriteVerbose(Strings.GetFederationInformationProxy(localServer.InternetWebProxy.ToString()));
                    autodiscoverClient.Proxy = new WebProxy(localServer.InternetWebProxy);
                }
                if (this.TrustedHostnames != null)
                {
                    autodiscoverClient.AllowedHostnames.AddRange(this.TrustedHostnames);
                }
                if (autodiscoverTrustedHosters != null)
                {
                    autodiscoverClient.AllowedHostnames.AddRange(autodiscoverTrustedHosters);
                }
                base.WriteVerbose(Strings.GetFederationInformationTrustedHostnames(autodiscoverClient.AllowedHostnames.ToString()));
                base.WriteProgress(Strings.GetFederationInformationProgress, Strings.DiscoveringDomain(this.DomainName.Domain), 5);
                List <GetFederationInformationResult> list = new List <GetFederationInformationResult>(GetFederationInformationClient.Discover(autodiscoverClient, this.DomainName.Domain));
                base.WriteProgress(Strings.GetFederationInformationProgress, Strings.DiscoveringDomain(this.DomainName.Domain), 25);
                base.WriteVerbose(Strings.GetFederationInformationResults(GetFederationInformation.GetFormattedResults(list)));
                GetFederationInformationResult result = this.GetResult(list);
                if (result == null)
                {
                    base.WriteError(new GetFederationInformationFailedException(list.ToArray()), (ErrorCategory)1001, null);
                }
                else
                {
                    ICollection domainNames;
                    if (this.BypassAdditionalDomainValidation)
                    {
                        domainNames = result.Domains;
                    }
                    else
                    {
                        domainNames = this.GetValidatedAdditionalDomains(autodiscoverClient, result.ApplicationUri, result.Domains);
                    }
                    if (result.TokenIssuerUris != null && result.TokenIssuerUris.Length > 0)
                    {
                        bool  flag  = false;
                        Uri[] array = Array.ConvertAll <string, Uri>(result.TokenIssuerUris, (string uri) => new Uri(uri, UriKind.RelativeOrAbsolute));
                        ExternalAuthentication current = ExternalAuthentication.GetCurrent();
                        if (current.Enabled)
                        {
                            foreach (SecurityTokenService securityTokenService in current.SecurityTokenServices)
                            {
                                Uri tokenIssuerUri = securityTokenService.TokenIssuerUri;
                                foreach (Uri uri2 in array)
                                {
                                    if (tokenIssuerUri.Equals(uri2))
                                    {
                                        base.WriteVerbose(Strings.GetFederationInformationTokenIssuerMatches(tokenIssuerUri.ToString(), uri2.ToString()));
                                        flag = true;
                                        break;
                                    }
                                    base.WriteVerbose(Strings.GetFederationInformationTokenIssuerDoesntMatch(tokenIssuerUri.ToString(), uri2.ToString()));
                                }
                            }
                            if (!flag)
                            {
                                StringBuilder stringBuilder = new StringBuilder(100);
                                foreach (SecurityTokenService securityTokenService2 in current.SecurityTokenServices)
                                {
                                    if (stringBuilder.Length > 0)
                                    {
                                        stringBuilder.Append(",");
                                    }
                                    stringBuilder.Append(securityTokenService2.TokenIssuerUri.ToString());
                                }
                                this.WriteWarning(Strings.GetFederationInformationTokenIssuerDoesntMatchAny(this.DomainName.ToString(), string.Join(",", result.TokenIssuerUris), stringBuilder.ToString()));
                            }
                        }
                    }
                    base.WriteObject(new FederationInformation(this.DomainName, new Uri(result.ApplicationUri, UriKind.RelativeOrAbsolute), result.TokenIssuerUris, domainNames, EwsWsSecurityUrl.Fix(result.Url)));
                }
                base.WriteProgress(Strings.GetFederationInformationProgress, Strings.ProgressStatusFinished, 100);
            }
            TaskLogger.LogExit();
        }
Exemplo n.º 12
0
        public IList <ISource> ValidateAndGetFinalSourceMailboxes(string searchQuery, IList <string> sourceMailboxes, IList <string> notFoundMailboxes, IList <string> versionSkippedMailboxes, IList <string> rbacDeniedMailboxes, IList <string> crossPremiseFailedMailboxes, IDictionary <Uri, string> crossPremiseUrls)
        {
            Util.ThrowIfNullOrEmpty(searchQuery, "Search query cannot be empty.");
            Util.ThrowIfNull(sourceMailboxes, "sourceMailboxes");
            Util.ThrowIfNull(notFoundMailboxes, "notFoundMailboxes");
            Util.ThrowIfNull(versionSkippedMailboxes, "versionSkippedMailboxes");
            Util.ThrowIfNull(rbacDeniedMailboxes, "rbacDeniedMailboxes");
            Util.ThrowIfNull(crossPremiseFailedMailboxes, "crossPremiseFailedMailboxes");
            Util.ThrowIfNull(crossPremiseUrls, "crossPremiseUrls");
            List <ISource> list = new List <ISource>();
            Dictionary <MiniRecipient, MailboxInfo> dictionary = new Dictionary <MiniRecipient, MailboxInfo>();
            int num = 0;

            if (sourceMailboxes.Count == 0)
            {
                AndFilter filter = new AndFilter(new QueryFilter[]
                {
                    new OrFilter(new QueryFilter[]
                    {
                        Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.UserMailbox),
                        Util.CreateRecipientTypeDetailsValueFilter((RecipientTypeDetails)((ulong)int.MinValue)),
                        Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.RemoteRoomMailbox),
                        Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.RemoteEquipmentMailbox),
                        Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.RemoteSharedMailbox),
                        Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.RemoteTeamMailbox)
                    }),
                    new NotFilter(Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.ArbitrationMailbox)),
                    new NotFilter(Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.MonitoringMailbox)),
                    new NotFilter(Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.AuditLogMailbox)),
                    new NotFilter(Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.MailboxPlan))
                });
                this.CheckRecipientSessionIsNotNull();
                ADPagedReader <StorageMiniRecipient> adpagedReader = this.recipientSession.FindPagedMiniRecipient <StorageMiniRecipient>(null, QueryScope.SubTree, filter, null, 1000, SearchMailboxCriteria.RecipientTypeDetailsProperty);
                using (IEnumerator <StorageMiniRecipient> enumerator = adpagedReader.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        StorageMiniRecipient storageMiniRecipient = enumerator.Current;
                        if (!storageMiniRecipient.LegacyExchangeDN.Equals(this.SearchObject.Target, StringComparison.OrdinalIgnoreCase))
                        {
                            if ((long)(++num) > (long)((ulong)this.MaxMailboxesToSearch))
                            {
                                throw new SearchTooManyMailboxesException((int)this.MaxMailboxesToSearch);
                            }
                            this.ValidateAndAddToFinalSourceMailboxes(searchQuery, storageMiniRecipient, list, versionSkippedMailboxes, rbacDeniedMailboxes, dictionary);
                        }
                    }
                    goto IL_2B6;
                }
            }
            foreach (ADObjectId adobjectId in this.ExpandGroupMembers(sourceMailboxes, this.DiscoverySystemMailboxUser.OrganizationId, notFoundMailboxes))
            {
                if ((this.SearchObject.Target == null || !adobjectId.Equals(this.TargetMailboxUser.Id)) && !adobjectId.Equals(this.DiscoverySystemMailboxUser.Id))
                {
                    this.CheckRecipientSessionIsNotNull();
                    StorageMiniRecipient storageMiniRecipient2 = this.recipientSession.ReadMiniRecipient <StorageMiniRecipient>(adobjectId, SearchMailboxCriteria.RecipientTypeDetailsProperty);
                    if (storageMiniRecipient2 != null)
                    {
                        if ((long)(++num) > (long)((ulong)this.MaxMailboxesToSearch))
                        {
                            throw new SearchTooManyMailboxesException((int)this.MaxMailboxesToSearch);
                        }
                        this.ValidateAndAddToFinalSourceMailboxes(searchQuery, storageMiniRecipient2, list, versionSkippedMailboxes, rbacDeniedMailboxes, dictionary);
                    }
                    else
                    {
                        Util.Tracer.TraceError <string>((long)this.GetHashCode(), "Unable to find mailbox: {0}", adobjectId.Name);
                    }
                }
            }
IL_2B6:
            if (dictionary.Count > 0)
            {
                string domain = dictionary.First <KeyValuePair <MiniRecipient, MailboxInfo> >().Value.GetDomain();
                Util.Tracer.TraceDebug <string>((long)this.GetHashCode(), "Before autodiscover for cross premise domain: {0}", domain);
                Uri uri = null;
                EndPointDiscoveryInfo endPointDiscoveryInfo;
                bool flag = RemoteDiscoveryEndPoint.TryGetDiscoveryEndPoint(this.SearchDataProvider.OrganizationId, domain, null, null, null, out uri, out endPointDiscoveryInfo);
                if (endPointDiscoveryInfo != null)
                {
                    ScenarioData.Current["IOC"] = ((int)endPointDiscoveryInfo.Status).ToString();
                    if (endPointDiscoveryInfo.Status != EndPointDiscoveryInfo.DiscoveryStatus.Success)
                    {
                        SearchEventLogger.Instance.LogSearchErrorEvent(ScenarioData.Current["SID"], endPointDiscoveryInfo.Message);
                    }
                }
                if (flag)
                {
                    Util.Tracer.TraceDebug <Uri>((long)this.GetHashCode(), "Auto discover Url : {1}", uri);
                    ICredentials       oauthCredentialsForAppToken = OAuthCredentials.GetOAuthCredentialsForAppToken(this.SearchDataProvider.OrganizationId, domain);
                    List <MailboxInfo> list2 = new List <MailboxInfo>(dictionary.Count);
                    foreach (KeyValuePair <MiniRecipient, MailboxInfo> keyValuePair in dictionary)
                    {
                        list2.Add(keyValuePair.Value);
                    }
                    IAutodiscoveryClient autodiscoveryClient = Factory.Current.CreateUserSettingAutoDiscoveryClient(list2, EwsWsSecurityUrl.FixForAnonymous(uri), oauthCredentialsForAppToken, new CallerInfo(true, null, null, string.Empty, null, null, null));
                    IAsyncResult         result = autodiscoveryClient.BeginAutodiscover(null, null);
                    Dictionary <GroupId, List <MailboxInfo> > dictionary2 = autodiscoveryClient.EndAutodiscover(result);
                    if (dictionary2 != null)
                    {
                        using (Dictionary <GroupId, List <MailboxInfo> > .Enumerator enumerator4 = dictionary2.GetEnumerator())
                        {
                            while (enumerator4.MoveNext())
                            {
                                KeyValuePair <GroupId, List <MailboxInfo> > keyValuePair2 = enumerator4.Current;
                                if (keyValuePair2.Key.GroupType == GroupType.CrossPremise)
                                {
                                    if (!crossPremiseUrls.ContainsKey(keyValuePair2.Key.Uri))
                                    {
                                        crossPremiseUrls.Add(keyValuePair2.Key.Uri, domain);
                                    }
                                    using (List <ISource> .Enumerator enumerator5 = list.GetEnumerator())
                                    {
                                        while (enumerator5.MoveNext())
                                        {
                                            ISource       source        = enumerator5.Current;
                                            SourceMailbox sourceMailbox = (SourceMailbox)source;
                                            foreach (MailboxInfo mailboxInfo in keyValuePair2.Value)
                                            {
                                                if (string.Compare(sourceMailbox.LegacyExchangeDN, mailboxInfo.LegacyExchangeDN, StringComparison.OrdinalIgnoreCase) == 0)
                                                {
                                                    sourceMailbox.ServiceEndpoint = keyValuePair2.Key.Uri;
                                                    break;
                                                }
                                            }
                                        }
                                        continue;
                                    }
                                }
                                if (keyValuePair2.Key.GroupType == GroupType.SkippedError)
                                {
                                    foreach (MailboxInfo mailboxInfo2 in keyValuePair2.Value)
                                    {
                                        Util.Tracer.TraceError <SmtpAddress>((long)this.GetHashCode(), "Auto discover skipped error for mailbox: {0}", mailboxInfo2.PrimarySmtpAddress);
                                        crossPremiseFailedMailboxes.Add(mailboxInfo2.LegacyExchangeDN);
                                    }
                                }
                            }
                            goto IL_5F2;
                        }
                    }
                    Util.Tracer.TraceError <string>((long)this.GetHashCode(), "Auto discover results is null for domain: {0}", domain);
                }
                else
                {
                    Util.Tracer.TraceError <string>((long)this.GetHashCode(), "Organization relationship is not set up for domain: {0}", domain);
                    foreach (KeyValuePair <MiniRecipient, MailboxInfo> keyValuePair3 in dictionary)
                    {
                        crossPremiseFailedMailboxes.Add(keyValuePair3.Value.LegacyExchangeDN);
                    }
                }
            }
IL_5F2:
            if (crossPremiseFailedMailboxes.Count > 0)
            {
                foreach (string b in crossPremiseFailedMailboxes)
                {
                    for (int i = list.Count - 1; i >= 0; i--)
                    {
                        ISource source2 = list[i];
                        if (source2.LegacyExchangeDN == b)
                        {
                            list.RemoveAt(i);
                        }
                    }
                }
            }
            return(list);
        }