public bool TryGet(string key, IRequestContext requestContext, out AnchorMailboxCacheEntry entry)
 {
     PerfCounters.HttpProxyCacheCountersInstance.AnchorMailboxLocalCacheHitsRateBase.Increment();
     PerfCounters.HttpProxyCacheCountersInstance.AnchorMailboxOverallCacheHitsRateBase.Increment();
     entry = null;
     if (this.innerCache.TryGetValue(key, out entry))
     {
         PerfCounters.HttpProxyCacheCountersInstance.AnchorMailboxLocalCacheHitsRate.Increment();
     }
     else if (HttpProxySettings.AnchorMailboxSharedCacheEnabled.Value)
     {
         long   latency  = 0L;
         string diagInfo = null;
         AnchorMailboxCacheEntry sharedCacheEntry = null;
         bool latency2 = LatencyTracker.GetLatency <bool>(() => this.sharedCacheClient.TryGet <AnchorMailboxCacheEntry>(key, requestContext.ActivityId, out sharedCacheEntry, out diagInfo), out latency);
         requestContext.LogSharedCacheCall(latency, diagInfo);
         if (latency2)
         {
             this.Add(key, sharedCacheEntry, requestContext, false);
             entry = sharedCacheEntry;
         }
     }
     if (entry != null)
     {
         PerfCounters.HttpProxyCacheCountersInstance.AnchorMailboxOverallCacheHitsRate.Increment();
         return(true);
     }
     return(false);
 }
示例#2
0
        internal static IRecipientSession GetRecipientSessionFromPartition(LatencyTracker latencyTracker, string partitionId)
        {
            if (latencyTracker == null)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            if (string.IsNullOrEmpty(partitionId))
            {
                throw new ArgumentNullException("partitionId");
            }
            ADSessionSettings adsessionSettings = null;
            PartitionId       partitionIdObject = null;

            if ((Utilities.IsPartnerHostedOnly || VariantConfiguration.InvariantNoFlightingSnapshot.Global.MultiTenancy.Enabled) && PartitionId.TryParse(partitionId, out partitionIdObject))
            {
                try
                {
                    adsessionSettings = DirectoryHelper.ExecuteFunctionAndUpdateMovingAveragePerformanceCounter <ADSessionSettings>(PerfCounters.HttpProxyCountersInstance.MovingAverageTenantLookupLatency, () => DirectoryHelper.InvokeGls <ADSessionSettings>(latencyTracker, () => ADSessionSettings.FromAllTenantsPartitionId(partitionIdObject)));
                }
                catch (CannotResolvePartitionException arg)
                {
                    ExTraceGlobals.VerboseTracer.TraceWarning <string, CannotResolvePartitionException>(0L, "[DirectoryHelper::GetRecipientSessionFromPartition] Caught CannotResolvePartitionException when resolving partition by partition ID {0}. Exception details: {1}.", partitionId, arg);
                }
            }
            if (adsessionSettings == null)
            {
                adsessionSettings = ADSessionSettings.FromRootOrgScopeSet();
            }
            return(DirectoryHelper.CreateSession(adsessionSettings));
        }
示例#3
0
 internal static IRecipientSession GetRecipientSessionFromSmtpOrLiveId(LatencyTracker latencyTracker, string smtpOrLiveId, bool ignoreCannotResolveTenantNameException = false)
 {
     if (latencyTracker == null)
     {
         throw new ArgumentNullException("latencyTracker");
     }
     if (string.IsNullOrEmpty(smtpOrLiveId))
     {
         throw new ArgumentNullException("smtpOrLiveId");
     }
     if ((Utilities.IsPartnerHostedOnly || VariantConfiguration.InvariantNoFlightingSnapshot.Global.WindowsLiveID.Enabled) && SmtpAddress.IsValidSmtpAddress(smtpOrLiveId))
     {
         string domain = SmtpAddress.Parse(smtpOrLiveId).Domain;
         if (!string.IsNullOrEmpty(domain))
         {
             try
             {
                 return(DirectoryHelper.GetRecipientSessionFromDomain(latencyTracker, domain, ignoreCannotResolveTenantNameException));
             }
             catch (CannotResolveTenantNameException ex)
             {
                 if (!ignoreCannotResolveTenantNameException)
                 {
                     throw new HttpProxyException(HttpStatusCode.NotFound, HttpProxySubErrorCode.DomainNotFound, ex.Message, ex);
                 }
                 ExTraceGlobals.VerboseTracer.TraceWarning <string, CannotResolveTenantNameException>(0L, "[DirectoryHelper::GetRecipientSessionFromSmtpOrLiveId] Caught CannotResolveTenantNameException when trying to get domain scopederecipient session from smtp or liveId for {0}. Exception details: {1}.", smtpOrLiveId, ex);
                 return(null);
             }
         }
     }
     return(DirectoryHelper.GetRootOrgRecipientSession());
 }
示例#4
0
 // Token: 0x06000433 RID: 1075 RVA: 0x000181F8 File Offset: 0x000163F8
 private static ADRawEntry GetCallerAdEntry(IRequestContext requestContext)
 {
     if (!requestContext.HttpContext.Items.Contains(Constants.CallerADRawEntryKeyName))
     {
         CommonAccessToken commonAccessToken = requestContext.HttpContext.Items["Item-CommonAccessToken"] as CommonAccessToken;
         if (commonAccessToken == null)
         {
             throw new InvalidOperationException("CAT token not present - cannot lookup LiveIdBasic user's AD entry.");
         }
         ADRawEntry               value          = null;
         LatencyTracker           latencyTracker = (LatencyTracker)requestContext.HttpContext.Items[Constants.LatencyTrackerContextKeyName];
         LiveIdBasicTokenAccessor accessor       = LiveIdBasicTokenAccessor.Attach(commonAccessToken);
         if (accessor.TokenType == 2)
         {
             if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
             {
                 ExTraceGlobals.VerboseTracer.TraceDebug <string, string>(0L, "[Extensions::GetFullCallerIdentity] Calling AD to convert PUID {0} for LiveIdMemberName {1} to SID to construct GenericSidIdentity.", accessor.Puid, accessor.LiveIdMemberName);
             }
             ITenantRecipientSession session = DirectoryHelper.GetTenantRecipientSessionFromSmtpOrLiveId(accessor.LiveIdMemberName, requestContext.Logger, latencyTracker, false);
             value = DirectoryHelper.InvokeAccountForest <ADRawEntry>(latencyTracker, () => session.FindUniqueEntryByNetID(accessor.Puid, null, UserBasedAnchorMailbox.ADRawEntryPropertySet, "d:\\dbs\\sh\\e16df\\0212_214120_0\\cmd\\1g\\sources\\Dev\\Cafe\\src\\HttpProxy\\Misc\\LiveIdBasicHelper.cs", 92, "GetCallerAdEntry"), requestContext.Logger, session);
         }
         requestContext.HttpContext.Items[Constants.CallerADRawEntryKeyName] = value;
     }
     return((ADRawEntry)requestContext.HttpContext.Items[Constants.CallerADRawEntryKeyName]);
 }
示例#5
0
 public void Init(HttpApplication application)
 {
     Diagnostics.SendWatsonReportOnUnhandledException(delegate()
     {
         LatencyTracker latencyTracker = new LatencyTracker();
         latencyTracker.StartTracking(LatencyTrackerKey.ProxyModuleInitLatency, false);
         Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug <ProtocolType>((long)this.GetHashCode(), "[ProxyModule::Init]: Init called.  Protocol type: {0}", HttpProxyGlobals.ProtocolType);
         if (application == null)
         {
             string message = "[ProxyModule::Init]: ProxyModule.Init called with null HttpApplication context.";
             Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.BriefTracer.TraceError((long)this.GetHashCode(), message);
             throw new ArgumentNullException("application", message);
         }
         this.PfdTracer                     = new PfdTracer(0, this.GetHashCode());
         application.BeginRequest          += this.OnBeginRequest;
         application.AuthenticateRequest   += this.OnAuthenticateRequest;
         application.PostAuthorizeRequest  += this.OnPostAuthorizeRequest;
         application.PreSendRequestHeaders += this.OnPreSendRequestHeaders;
         application.EndRequest            += this.OnEndRequest;
         if (Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
         {
             Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug <ProtocolType, long>((long)this.GetHashCode(), "[ProxyModule::Init]: Protocol type: {0}, InitLatency {1}", HttpProxyGlobals.ProtocolType, latencyTracker.GetCurrentLatency(LatencyTrackerKey.ProxyModuleInitLatency));
         }
     });
 }
示例#6
0
        private void OnPostAuthorizeRequest(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContext     httpContext     = httpApplication.Context;

            Diagnostics.SendWatsonReportOnUnhandledException(delegate()
            {
                if (Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
                {
                    Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug((long)this.GetHashCode(), "[ProxyModule::OnPostAuthorizeRequest]: Method {0}; Url {1}; Username {2}; Context {3};", new object[]
                    {
                        httpContext.Request.HttpMethod,
                        httpContext.Request.Url,
                        (httpContext.User == null) ? string.Empty : httpContext.User.Identity.GetSafeName(true),
                        httpContext.GetTraceContext()
                    });
                }
                this.OnPostAuthorizeInternal(httpApplication);
                LatencyTracker latencyTracker = LatencyTracker.FromHttpContext(httpContext);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext), ServiceLatencyMetadata.HttpPipelineLatency, latencyTracker.GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency));
                long currentLatency = latencyTracker.GetCurrentLatency(LatencyTrackerKey.AuthenticationLatency);
                PerfCounters.UpdateMovingAveragePerformanceCounter(PerfCounters.HttpProxyCountersInstance.MovingAverageAuthenticationLatency, currentLatency);
                latencyTracker.StartTracking(LatencyTrackerKey.ModuleToHandlerSwitchingLatency, false);
            }, new Diagnostics.LastChanceExceptionHandler(RequestDetailsLogger.LastChanceExceptionHandler));
        }
示例#7
0
        // Token: 0x060003E3 RID: 995 RVA: 0x00016A28 File Offset: 0x00014C28
        internal static IRecipientSession GetRecipientSessionFromPartition(LatencyTracker latencyTracker, string partitionId, RequestDetailsLogger logger)
        {
            if (latencyTracker == null)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            if (string.IsNullOrEmpty(partitionId))
            {
                throw new ArgumentNullException("partitionId");
            }
            ADSessionSettings adsessionSettings = null;
            PartitionId       partitionIdObject = null;

            if ((Utilities.IsPartnerHostedOnly || GlobalConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).MultiTenancy.Enabled) && PartitionId.TryParse(partitionId, ref partitionIdObject))
            {
                try
                {
                    adsessionSettings = DirectoryHelper.CreateADSessionSettingsWithDiagnostics(() => ADSessionSettings.FromAllTenantsPartitionId(partitionIdObject), logger, latencyTracker, true);
                }
                catch (CannotResolvePartitionException ex)
                {
                    if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(2))
                    {
                        ExTraceGlobals.VerboseTracer.TraceWarning <string, CannotResolvePartitionException>(0L, "[DirectoryHelper::GetRecipientSessionFromPartition] Caught CannotResolvePartitionException when resolving partition by partition ID {0}. Exception details: {1}.", partitionId, ex);
                    }
                }
            }
            if (adsessionSettings == null)
            {
                adsessionSettings = ADSessionSettings.FromRootOrgScopeSet();
            }
            return(DirectoryHelper.CreateSession(adsessionSettings));
        }
 public void Remove(string key, IRequestContext requestContext)
 {
     this.innerCache.Remove(key);
     if (HttpProxySettings.AnchorMailboxSharedCacheEnabled.Value)
     {
         long   latency  = 0L;
         string diagInfo = null;
         LatencyTracker.GetLatency <bool>(() => this.sharedCacheClient.TryRemove(key, requestContext.ActivityId, out diagInfo), out latency);
         requestContext.LogSharedCacheCall(latency, diagInfo);
     }
 }
 public void Add(string key, AnchorMailboxCacheEntry entry, DateTime valueTimestamp, IRequestContext requestContext, bool addToSharedCache)
 {
     this.innerCache.TryInsertLimitedSliding(key, entry, AnchorMailboxCache.AnchorMailboxCacheAbsoluteTimeout, AnchorMailboxCache.AnchorMailboxCacheSlidingTimeout);
     if (HttpProxySettings.AnchorMailboxSharedCacheEnabled.Value && addToSharedCache)
     {
         long   latency  = 0L;
         string diagInfo = null;
         LatencyTracker.GetLatency <bool>(() => this.sharedCacheClient.TryInsert(key, entry, valueTimestamp, requestContext.ActivityId, out diagInfo), out latency);
         requestContext.LogSharedCacheCall(latency, diagInfo);
     }
     this.UpdateCacheSizeCounter();
 }
示例#10
0
        // Token: 0x0600017B RID: 379 RVA: 0x00007C0C File Offset: 0x00005E0C
        private ADObjectId GetRandomDatabasesFromForest(string resourceForestFqdn)
        {
            if (HttpProxySettings.LocalForestDatabaseEnabled.Value && Utilities.IsLocalForest(resourceForestFqdn))
            {
                return(LocalForestDatabaseProvider.Instance.GetRandomDatabase());
            }
            List <ADObjectId> list = null;

            if (!TargetForestAnchorMailbox.resourceForestToDatabaseMap.TryGetValue(resourceForestFqdn, out list) || list == null || list.Count <= 0)
            {
                object obj = TargetForestAnchorMailbox.forestDatabaseLock;
                lock (obj)
                {
                    if (!TargetForestAnchorMailbox.resourceForestToDatabaseMap.TryGetValue(resourceForestFqdn, out list) || list == null || list.Count <= 0)
                    {
                        list = new List <ADObjectId>();
                        PartitionId partitionId = new PartitionId(resourceForestFqdn);
                        ITopologyConfigurationSession resourceForestSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(2, ADSessionSettings.FromAccountPartitionRootOrgScopeSet(partitionId), 306, "GetRandomDatabasesFromForest", "d:\\dbs\\sh\\e16df\\0212_214120_0\\cmd\\1g\\sources\\Dev\\Cafe\\src\\HttpProxy\\AnchorMailbox\\TargetForestAnchorMailbox.cs");
                        SortBy sortBy = new SortBy(ADObjectSchema.WhenCreatedUTC, 0);
                        List <PropertyDefinition> databaseSchema = new List <PropertyDefinition>
                        {
                            ADObjectSchema.Id
                        };
                        long latency = 0L;
                        ADPagedReader <ADRawEntry> latency2 = LatencyTracker.GetLatency <ADPagedReader <ADRawEntry> >(() => resourceForestSession.FindPagedADRawEntry(resourceForestSession.ConfigurationNamingContext, 2, TargetForestAnchorMailbox.DatabaseQueryFilter, sortBy, TargetForestAnchorMailbox.DatabasesToLoadPerForest.Value, databaseSchema, "d:\\dbs\\sh\\e16df\\0212_214120_0\\cmd\\1g\\sources\\Dev\\Cafe\\src\\HttpProxy\\AnchorMailbox\\TargetForestAnchorMailbox.cs", 323, "GetRandomDatabasesFromForest"), out latency);
                        base.RequestContext.LatencyTracker.HandleResourceLatency(latency);
                        if (latency2 != null)
                        {
                            foreach (ADRawEntry adrawEntry in latency2)
                            {
                                list.Add(adrawEntry.Id);
                            }
                        }
                        if (list.Count > 0)
                        {
                            TargetForestAnchorMailbox.resourceForestToDatabaseMap[resourceForestFqdn] = list;
                            if (list.Count < TargetForestAnchorMailbox.MinimumDatabasesForEffectiveLoadBalancing.Value)
                            {
                                base.RequestContext.Logger.AppendGenericError("TooFewDbsForLoadBalancing", string.Format("DbCount:{0}/Forest:{1}", list.Count, resourceForestFqdn));
                            }
                        }
                    }
                }
            }
            if (list != null && list.Count > 0)
            {
                int index = TargetForestAnchorMailbox.seededRand.Next(0, list.Count);
                return(list[index]);
            }
            return(null);
        }
 public void Remove(Guid database, IRequestContext requestContext)
 {
     this.serversCache.Remove(database);
     if (HttpProxySettings.MailboxServerLocatorSharedCacheEnabled.Value)
     {
         long   latency  = 0L;
         string diagInfo = null;
         LatencyTracker.GetLatency <bool>(() => this.sharedCacheClient.TryRemove(database.ToString(), requestContext.ActivityId, out diagInfo), out latency);
         if (requestContext != null)
         {
             requestContext.LogSharedCacheCall(latency, diagInfo);
         }
     }
 }
示例#12
0
        internal static IRecipientSession GetRecipientSessionFromOrganizationId(LatencyTracker latencyTracker, OrganizationId organizationId)
        {
            if (latencyTracker == null)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            if (organizationId == null)
            {
                organizationId = OrganizationId.ForestWideOrgId;
            }
            ADSessionSettings sessionSettings = DirectoryHelper.ExecuteFunctionAndUpdateMovingAveragePerformanceCounter <ADSessionSettings>(PerfCounters.HttpProxyCountersInstance.MovingAverageTenantLookupLatency, () => DirectoryHelper.InvokeGls <ADSessionSettings>(latencyTracker, () => ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(organizationId)));

            return(DirectoryHelper.CreateSession(sessionSettings));
        }
示例#13
0
        private void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContext     httpContext     = httpApplication.Context;

            Diagnostics.SendWatsonReportOnUnhandledException(delegate()
            {
                LatencyTracker latencyTracker = new LatencyTracker();
                latencyTracker.StartTracking(LatencyTrackerKey.ProxyModuleLatency, false);
                AspNetHelper.AddTimestampHeaderIfNecessary(httpContext.Request.Headers, "X-FrontEnd-Begin");
                if (Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
                {
                    Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug <string, Uri, int>((long)this.GetHashCode(), "[ProxyModule::OnBeginRequest]: Method {0}; Url {1}; Context {2};", httpContext.Request.HttpMethod, httpContext.Request.Url, httpContext.GetHashCode());
                }
                if (HealthCheckResponder.Instance.IsHealthCheckRequest(httpContext))
                {
                    HealthCheckResponder.Instance.CheckHealthStateAndRespond(httpContext);
                    return;
                }
                RequestDetailsLogger requestDetailsLogger = RequestDetailsLoggerBase <RequestDetailsLogger> .InitializeRequestLogger();
                requestDetailsLogger.LogCurrentTime("BeginRequest");
                httpContext.Items[Constants.TraceContextKey] = httpContext.GetHashCode();
                httpContext.Items[Constants.LatencyTrackerContextKeyName] = latencyTracker;
                requestDetailsLogger.ActivityScope.UpdateFromMessage(httpContext.Request);
                requestDetailsLogger.ActivityScope.SerializeTo(httpContext.Response);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SetCurrent(httpContext, requestDetailsLogger);
                httpContext.Items[typeof(ActivityScope)] = requestDetailsLogger.ActivityScope;
                httpContext.Items[Constants.RequestIdHttpContextKeyName] = requestDetailsLogger.ActivityScope.ActivityId;
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, HttpProxyMetadata.Protocol, HttpProxyGlobals.ProtocolType);
                requestDetailsLogger.SafeLogUriData(httpContext.Request.Url);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, ServiceCommonMetadata.HttpMethod, httpContext.Request.HttpMethod);
                string requestCorrelationId = AspNetHelper.GetRequestCorrelationId(httpContext);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestDetailsLogger, "CorrelationID", requestCorrelationId);
                httpContext.Response.AppendToLog(Constants.CorrelationIdKeyForIISLogs + requestCorrelationId + ";");
                string cookieValueAndSetIfNull = ClientIdCookie.GetCookieValueAndSetIfNull(httpContext);
                httpContext.Response.AppendToLog(string.Format("&{0}={1}", "ClientId", cookieValueAndSetIfNull));
                UrlUtilities.SaveOriginalRequestHostSchemePortToContext(httpContext);
                try
                {
                    this.OnBeginRequestInternal(httpApplication);
                }
                catch (Exception ex)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericError(requestDetailsLogger, "OnBeginRequestInternal", ex.ToString());
                    requestDetailsLogger.AsyncCommit(false);
                    throw;
                }
            }, new Diagnostics.LastChanceExceptionHandler(RequestDetailsLogger.LastChanceExceptionHandler));
        }
示例#14
0
        private static T ExecuteFunctionAndUpdateMovingAveragePerformanceCounter <T>(ExPerformanceCounter performanceCounter, Func <T> operationToTrack)
        {
            long newValue = 0L;
            T    latency;

            try
            {
                latency = LatencyTracker.GetLatency <T>(operationToTrack, out newValue);
            }
            finally
            {
                PerfCounters.UpdateMovingAveragePerformanceCounter(performanceCounter, newValue);
            }
            return(latency);
        }
示例#15
0
        private ADObjectId GetRandomDatabasesFromForest(string resourceForestFqdn)
        {
            List <ADObjectId> list = null;
            bool flag = TargetForestAnchorMailbox.resourceForestToDatabaseMap.TryGetValue(resourceForestFqdn, out list);

            if (!flag || list == null || list.Count <= 0)
            {
                lock (TargetForestAnchorMailbox.forestDatabaseLock)
                {
                    flag = TargetForestAnchorMailbox.resourceForestToDatabaseMap.TryGetValue(resourceForestFqdn, out list);
                    if (!flag || list == null || list.Count <= 0)
                    {
                        list = new List <ADObjectId>();
                        PartitionId partitionId = new PartitionId(resourceForestFqdn);
                        ITopologyConfigurationSession resourceForestSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromAccountPartitionRootOrgScopeSet(partitionId), 318, "GetRandomDatabasesFromForest", "f:\\15.00.1497\\sources\\dev\\cafe\\src\\HttpProxy\\AnchorMailbox\\TargetForestAnchorMailbox.cs");
                        SortBy sortBy = new SortBy(ADObjectSchema.WhenCreatedUTC, SortOrder.Ascending);
                        List <PropertyDefinition> databaseSchema = new List <PropertyDefinition>
                        {
                            ADObjectSchema.Id
                        };
                        long latency = 0L;
                        ADPagedReader <ADRawEntry> latency2 = LatencyTracker.GetLatency <ADPagedReader <ADRawEntry> >(() => resourceForestSession.FindPagedADRawEntry(resourceForestSession.ConfigurationNamingContext, QueryScope.SubTree, TargetForestAnchorMailbox.DatabaseQueryFilter, sortBy, TargetForestAnchorMailbox.DatabasesToLoadPerForest.Value, databaseSchema), out latency);
                        base.RequestContext.LatencyTracker.HandleResourceLatency(latency);
                        if (latency2 != null)
                        {
                            foreach (ADRawEntry adrawEntry in latency2)
                            {
                                list.Add(adrawEntry.Id);
                            }
                        }
                        if (list.Count > 0)
                        {
                            TargetForestAnchorMailbox.resourceForestToDatabaseMap[resourceForestFqdn] = list;
                            if (list.Count < TargetForestAnchorMailbox.MinimumDatabasesForEffectiveLoadBalancing.Value)
                            {
                                base.RequestContext.Logger.AppendGenericError("TooFewDbsForLoadBalancing", string.Format("DbCount:{0}/Forest:{1}", list.Count, resourceForestFqdn));
                            }
                        }
                    }
                }
            }
            if (list != null && list.Count > 0)
            {
                int index = TargetForestAnchorMailbox.seededRand.Next(0, list.Count);
                return(list[index]);
            }
            return(null);
        }
示例#16
0
        internal static T InvokeGls <T>(LatencyTracker latencyTracker, Func <T> glsCall)
        {
            if (latencyTracker == null)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            if (glsCall == null)
            {
                throw new ArgumentNullException("glsCall");
            }
            long latency  = 0L;
            T    latency2 = LatencyTracker.GetLatency <T>(() => glsCall(), out latency);

            latencyTracker.HandleGlsLatency(latency);
            return(latency2);
        }
 private void Add(Guid database, MailboxServerCacheEntry entry, Guid initiatingRequestId, IRequestContext requestContext, bool addToSharedCache = true)
 {
     ExTraceGlobals.VerboseTracer.TraceDebug <Guid, BackEndServer, bool>((long)this.GetHashCode(), "[MailboxServerCache::Add]: Adding database {0} with server {1} to cache. addToSharedCache={2}", database, entry.BackEndServer, addToSharedCache);
     this.serversCache.TryInsertAbsolute(database, entry, MailboxServerCache.MailboxServerCacheAbsoluteTimeout);
     if (HttpProxySettings.MailboxServerLocatorSharedCacheEnabled.Value && addToSharedCache)
     {
         long   latency  = 0L;
         string diagInfo = null;
         LatencyTracker.GetLatency <bool>(() => this.sharedCacheClient.TryInsert(database.ToString(), entry, entry.LastRefreshTime, initiatingRequestId, out diagInfo), out latency);
         if (requestContext != null)
         {
             requestContext.LogSharedCacheCall(latency, diagInfo);
         }
     }
     LocalSiteMailboxServerCache.Instance.Add(database, entry.BackEndServer, entry.ResourceForest);
 }
        // Token: 0x060002B8 RID: 696 RVA: 0x0000D928 File Offset: 0x0000BB28
        private string InvokeMserv(string userAddress)
        {
            int       currentSitePartnerId = HttpProxyGlobals.LocalSite.Member.PartnerId;
            string    text = null;
            long      num  = 0L;
            Exception ex   = null;

            try
            {
                text = LatencyTracker.GetLatency <string>(() => EdgeSyncMservConnector.GetRedirectServer(DatacenterRedirectStrategy.PodRedirectTemplate.Value, userAddress, currentSitePartnerId, DatacenterRedirectStrategy.PodSiteStartRange.Value, DatacenterRedirectStrategy.PodSiteEndRange.Value, false, true), out num);
            }
            catch (MServTransientException ex)
            {
            }
            catch (MServPermanentException ex)
            {
            }
            catch (InvalidOperationException ex)
            {
            }
            catch (LocalizedException ex)
            {
            }
            finally
            {
                this.RequestContext.Logger.AppendGenericInfo("MservLatency", num);
            }
            string message = string.Format("Failed to look up MSERV for address {0}.", userAddress);

            if (ex != null)
            {
                if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(3))
                {
                    ExTraceGlobals.VerboseTracer.TraceError <int, string, Exception>((long)this.GetHashCode(), "[DatacenterRedirectStrategy::InvokeMserv]: Context {0}. Failed to look up MSERV for address {1}. Error: {2}", this.TraceContext, userAddress, ex);
                }
                throw new HttpProxyException(HttpStatusCode.InternalServerError, 2002, message, ex);
            }
            if (string.IsNullOrEmpty(text))
            {
                if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(3))
                {
                    ExTraceGlobals.VerboseTracer.TraceError <int, string>((long)this.GetHashCode(), "[DatacenterRedirectStrategy::InvokeMserv]: Context {0}. MSERV did not return redirect server for address {1}.", this.TraceContext, userAddress);
                }
                throw new HttpProxyException(HttpStatusCode.InternalServerError, 2002, message);
            }
            return(text);
        }
示例#19
0
        // Token: 0x0600017A RID: 378 RVA: 0x00007B84 File Offset: 0x00005D84
        private string GetResourceForestFqdnByAcceptedDomainName(string tenantAcceptedDomain)
        {
            string resourceForestFqdn;

            if (!TargetForestAnchorMailbox.domainToResourceForestMap.TryGetValue(tenantAcceptedDomain, ref resourceForestFqdn))
            {
                long latency = 0L;
                resourceForestFqdn = LatencyTracker.GetLatency <string>(delegate()
                {
                    resourceForestFqdn = ADAccountPartitionLocator.GetResourceForestFqdnByAcceptedDomainName(tenantAcceptedDomain);
                    return(resourceForestFqdn);
                }, out latency);
                TargetForestAnchorMailbox.domainToResourceForestMap.TryInsertAbsolute(tenantAcceptedDomain, resourceForestFqdn, TargetForestAnchorMailbox.DomainForestAbsoluteTimeout.Value);
                base.RequestContext.LatencyTracker.HandleGlsLatency(latency);
            }
            return(resourceForestFqdn);
        }
示例#20
0
        internal static IRecipientSession GetTenantRecipientSessionByMSAUserNetID(LatencyTracker latencyTracker, string msaUserNetID, bool ignoreCannotResolveMSAUserNetIDException, bool requestForestWideDomainControllerAffinityByUserId)
        {
            if (latencyTracker == null)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            NetID netID;

            if (!NetID.TryParse(msaUserNetID, out netID))
            {
                throw new ArgumentException("msaUserNetID");
            }
            ADSessionSettings sessionSettings = null;

            if (!Utilities.IsPartnerHostedOnly)
            {
                if (!VariantConfiguration.InvariantNoFlightingSnapshot.Global.WindowsLiveID.Enabled)
                {
                    goto IL_AE;
                }
            }
            try
            {
                sessionSettings = DirectoryHelper.CreateADTenantSessionSettingsByMSAUserNetID(latencyTracker, msaUserNetID);
                goto IL_B4;
            }
            catch (CannotResolveMSAUserNetIDException ex)
            {
                if (!ignoreCannotResolveMSAUserNetIDException)
                {
                    ExTraceGlobals.VerboseTracer.TraceWarning <string, CannotResolveMSAUserNetIDException>(0L, "[DirectoryHelper::GetTenantRecipientSessionByMSAUserNetID] Caught CannotResolveMSAUserNetIDException when trying to get tenant recipient session by MSA user NetID for {0}. Exception details: {1}.", msaUserNetID, ex);
                    throw new HttpProxyException(HttpStatusCode.NotFound, HttpProxySubErrorCode.UserNotFound, ex.Message, ex);
                }
                ExTraceGlobals.VerboseTracer.TraceWarning <string, CannotResolveMSAUserNetIDException>(0L, "[DirectoryHelper::GetTenantRecipientSessionByMSAUserNetID] Caught CannotResolveMSAUserNetIDException when trying to get tenant recipient session by MSA user NetID for {0}. Exception details: {1}.", msaUserNetID, ex);
                return(null);
            }
            catch (CannotResolveExternalDirectoryOrganizationIdException ex2)
            {
                throw new HttpProxyException(HttpStatusCode.NotFound, HttpProxySubErrorCode.DomainNotFound, ex2.Message, ex2);
            }
IL_AE:
            sessionSettings = ADSessionSettings.FromRootOrgScopeSet();
IL_B4:
            return(DirectoryHelper.CreateSession(sessionSettings, msaUserNetID, requestForestWideDomainControllerAffinityByUserId));
        }
示例#21
0
        protected virtual void OnPostAuthorizeInternal(HttpApplication httpApplication)
        {
            HttpContext context = httpApplication.Context;

            if (NativeProxyHelper.CanNativeProxyHandleRequest(context))
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(context), "ProxyRequestHandler", "NativeHttpProxy");

                return;
            }
            IHttpHandler httpHandler;

            if (context.Request.IsAuthenticated)
            {
                httpHandler = this.SelectHandlerForAuthenticatedRequest(context);
            }
            else
            {
                httpHandler = this.SelectHandlerForUnauthenticatedRequest(context);
            }
            if (httpHandler != null)
            {
                if (Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
                {
                    Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug <Type, object>((long)this.GetHashCode(), "[ProxyModule::OnPostAuthorizeInternal]: The selected HttpHandler is {0}; Context {1};", httpHandler.GetType(), context.Items[Constants.TraceContextKey]);
                }
                PerfCounters.HttpProxyCountersInstance.TotalRequests.Increment();
                if (httpHandler is ProxyRequestHandler)
                {
                    ((ProxyRequestHandler)httpHandler).Run(context);
                }
                else
                {
                    context.RemapHandler(httpHandler);
                }
                long currentLatency = LatencyTracker.FromHttpContext(context).GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency);
                if (currentLatency > 100L)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(context), "RemapHandler", currentLatency);
                }
            }
        }
示例#22
0
        internal static ADRawEntry InvokeAccountForest(LatencyTracker latencyTracker, Func <ADRawEntry> activeDirectoryFunction)
        {
            if (latencyTracker == null)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            if (activeDirectoryFunction == null)
            {
                throw new ArgumentNullException("activeDirectoryFunction");
            }
            long       latency  = 0L;
            ADRawEntry latency2 = LatencyTracker.GetLatency <ADRawEntry>(() => activeDirectoryFunction(), out latency);

            latencyTracker.HandleAccountLatency(latency);
            if (latency2 != null)
            {
                string originatingServer = latency2.OriginatingServer;
            }
            return(latency2);
        }
示例#23
0
        internal static MailboxDatabase[] InvokeResourceForest(LatencyTracker latencyTracker, Func <MailboxDatabase[]> activeDirectoryFunction)
        {
            if (latencyTracker == null)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            if (activeDirectoryFunction == null)
            {
                throw new ArgumentNullException("activeDirectoryFunction");
            }
            long latency = 0L;

            MailboxDatabase[] latency2 = LatencyTracker.GetLatency <MailboxDatabase[]>(() => activeDirectoryFunction(), out latency);
            latencyTracker.HandleResourceLatency(latency);
            if (latency2 != null && latency2.Length > 0)
            {
                string originatingServer = latency2[0].OriginatingServer;
            }
            return(latency2);
        }
示例#24
0
        private void OnAuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContext     httpContext     = httpApplication.Context;

            Diagnostics.SendWatsonReportOnUnhandledException(delegate()
            {
                LatencyTracker latencyTracker = LatencyTracker.FromHttpContext(httpContext);
                latencyTracker.StartTracking(LatencyTrackerKey.AuthenticationLatency, false);
                if (Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
                {
                    Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug <string, Uri, object>((long)this.GetHashCode(), "[ProxyModule::OnAuthenticateRequest]: Method {0}; Url {1}; Context {2};", httpContext.Request.HttpMethod, httpContext.Request.Url, httpContext.Items[Constants.TraceContextKey]);
                }
                this.OnAuthenticateInternal(httpApplication);
                long currentLatency = LatencyTracker.FromHttpContext(httpContext).GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency);
                if (currentLatency > 100L)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext), "OnAuthenticate", currentLatency);
                }
            }, new Diagnostics.LastChanceExceptionHandler(RequestDetailsLogger.LastChanceExceptionHandler));
        }
示例#25
0
 // Token: 0x060003E7 RID: 999 RVA: 0x00016C9C File Offset: 0x00014E9C
 internal static IRecipientSession GetRecipientSessionFromOrganizationId(LatencyTracker latencyTracker, OrganizationId organizationId, RequestDetailsLogger logger)
 {
     if (latencyTracker == null)
     {
         throw new ArgumentNullException("latencyTracker");
     }
     if (organizationId == null)
     {
         organizationId = OrganizationId.ForestWideOrgId;
     }
     Func <ADSessionSettings> < > 9__1;
     return(DirectoryHelper.CreateSession(DirectoryHelper.ExecuteFunctionAndUpdateMovingAveragePerformanceCounter <ADSessionSettings>(PerfCounters.HttpProxyCountersInstance.MovingAverageTenantLookupLatency, delegate
     {
         LatencyTracker latencyTracker2 = latencyTracker;
         Func <ADSessionSettings> glsCall;
         if ((glsCall = < > 9__1) == null)
         {
             glsCall = (< > 9__1 = (() => ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(organizationId)));
         }
         return DirectoryHelper.InvokeGls <ADSessionSettings>(latencyTracker2, glsCall, logger);
     })));
示例#26
0
 private static ADRawEntry GetCallerAdEntry(HttpContext httpContext)
 {
     if (!httpContext.Items.Contains(Constants.CallerADRawEntryKeyName))
     {
         CommonAccessToken commonAccessToken = httpContext.Items["Item-CommonAccessToken"] as CommonAccessToken;
         if (commonAccessToken == null)
         {
             throw new InvalidOperationException("CAT token not present - cannot lookup LiveIdBasic user's AD entry.");
         }
         ADRawEntry               value          = null;
         LatencyTracker           latencyTracker = (LatencyTracker)httpContext.Items[Constants.LatencyTrackerContextKeyName];
         LiveIdBasicTokenAccessor accessor       = LiveIdBasicTokenAccessor.Attach(commonAccessToken);
         if (accessor.TokenType == AccessTokenType.LiveIdBasic)
         {
             ExTraceGlobals.VerboseTracer.TraceDebug <string, string>(0L, "[Extensions::GetFullCallerIdentity] Calling AD to convert PUID {0} for LiveIdMemberName {1} to SID to construct GenericSidIdentity.", accessor.Puid, accessor.LiveIdMemberName);
             ITenantRecipientSession session = DirectoryHelper.GetTenantRecipientSessionFromSmtpOrLiveId(latencyTracker, accessor.LiveIdMemberName, false);
             value = DirectoryHelper.InvokeAccountForest(latencyTracker, () => session.FindUniqueEntryByNetID(accessor.Puid, null, UserBasedAnchorMailbox.ADRawEntryPropertySet));
         }
         httpContext.Items[Constants.CallerADRawEntryKeyName] = value;
     }
     return((ADRawEntry)httpContext.Items[Constants.CallerADRawEntryKeyName]);
 }
示例#27
0
        internal static IRecipientSession GetRecipientSessionFromDomain(LatencyTracker latencyTracker, string domain, bool ignoreCannotResolveTenantNameException = false)
        {
            if (latencyTracker == null)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            if (string.IsNullOrEmpty(domain))
            {
                throw new ArgumentNullException("domain");
            }
            ADSessionSettings sessionSettings = null;

            if (!Utilities.IsPartnerHostedOnly)
            {
                if (!VariantConfiguration.InvariantNoFlightingSnapshot.Global.WindowsLiveID.Enabled)
                {
                    goto IL_7F;
                }
            }
            try
            {
                sessionSettings = DirectoryHelper.CreateADSessionSettingsFromDomain(latencyTracker, domain);
                goto IL_85;
            }
            catch (CannotResolveTenantNameException ex)
            {
                ExTraceGlobals.VerboseTracer.TraceWarning <string, CannotResolveTenantNameException>(0L, "[DirectoryHelper::GetRecipientSessionFromDomain] Caught CannotResolveTenantNameException when resolving tenant by domain {0}. Exception details: {1}.", domain, ex);
                if (!ignoreCannotResolveTenantNameException)
                {
                    throw new HttpProxyException(HttpStatusCode.NotFound, HttpProxySubErrorCode.DomainNotFound, ex.Message, ex);
                }
                return(null);
            }
IL_7F:
            sessionSettings = ADSessionSettings.FromRootOrgScopeSet();
IL_85:
            return(DirectoryHelper.CreateSession(sessionSettings));
        }
示例#28
0
        private void OnEndRequest(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContext     httpContext     = httpApplication.Context;

            Diagnostics.SendWatsonReportOnUnhandledException(delegate()
            {
                LatencyTracker latencyTracker = LatencyTracker.FromHttpContext(httpContext);
                RequestDetailsLogger current  = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext);
                int traceContext = httpContext.GetTraceContext();
                if (HttpProxyGlobals.ProtocolType != ProtocolType.Mapi)
                {
                    OwaProxyRequestHandler.TryAddUnAuthenticatedPLTRequestPostDataToUriQueryOfIISLog(httpContext);
                }
                if (httpContext.Response != null && current != null)
                {
                    httpContext.Response.AppendToLog(Constants.RequestIdKeyForIISLogs + current.ActivityId.ToString() + ";");
                }
                if (HealthCheckResponder.Instance.IsHealthCheckRequest(httpContext))
                {
                    return;
                }
                if (httpContext.Response.StatusCode == 404 && httpContext.Response.SubStatusCode == 13)
                {
                    httpContext.Response.StatusCode = 507;
                }
                if (Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
                {
                    Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug((long)this.GetHashCode(), "[ProxyModule::OnEndRequest]: Method {0}; Url {1}; Username {2}; Context {3};", new object[]
                    {
                        httpContext.Request.HttpMethod,
                        httpContext.Request.Url,
                        (httpContext.User == null) ? string.Empty : httpContext.User.Identity.GetSafeName(true),
                        traceContext
                    });
                }
                if (latencyTracker != null)
                {
                    long currentLatency = latencyTracker.GetCurrentLatency(LatencyTrackerKey.HandlerToModuleSwitchingLatency);
                    if (currentLatency >= 0L)
                    {
                        RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(current, HttpProxyMetadata.HandlerToModuleSwitchingLatency, currentLatency);
                    }
                }
                ProxyRequestHandler proxyRequestHandler = httpContext.CurrentHandler as ProxyRequestHandler;
                if (proxyRequestHandler != null && !proxyRequestHandler.IsDisposed)
                {
                    current.AppendGenericInfo("DisposeProxyRequestHandler", "ProxyModule::OnEndRequest");
                    proxyRequestHandler.Dispose();
                }
                string value = httpContext.Items["AnonymousRequestFilterModule"] as string;
                if (!string.IsNullOrEmpty(value))
                {
                    current.AppendGenericInfo("AnonymousRequestFilterModule", value);
                }
                try
                {
                    this.OnEndRequestInternal(httpApplication);
                }
                finally
                {
                    if (current != null && !current.IsDisposed)
                    {
                        IActivityScope activityScope = current.ActivityScope;
                        if (activityScope != null)
                        {
                            if (!string.IsNullOrEmpty(activityScope.TenantId))
                            {
                                httpContext.Items["AuthenticatedUserOrganization"] = activityScope.TenantId;
                            }
                            ProxyModule.FinalizeRequestLatencies(httpContext, current, activityScope, latencyTracker, traceContext);
                        }
                        current.LogCurrentTime("EndRequest");
                        current.AsyncCommit(false);
                    }
                    if (Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
                    {
                        Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug(0L, "[ProxyModule::OnEndRequest]: Method {0}; Url {1}; OnEndRequestLatency {2}; Context {3};", new object[]
                        {
                            httpContext.Request.HttpMethod,
                            httpContext.Request.Url,
                            (latencyTracker != null) ? latencyTracker.GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency).ToString() : "Unknown",
                            traceContext
                        });
                    }
                }
            }, new Diagnostics.LastChanceExceptionHandler(RequestDetailsLogger.LastChanceExceptionHandler));
        }
示例#29
0
        private IHttpHandler SelectHandlerForUnauthenticatedRequest(HttpContext httpContext)
        {
            IHttpHandler result;

            try
            {
                IHttpHandler httpHandler = null;
                if (HttpProxyGlobals.ProtocolType == ProtocolType.Autodiscover)
                {
                    if (httpContext.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
                    {
                        if (ProtocolHelper.IsOAuthMetadataRequest(httpContext.Request.Url.AbsolutePath))
                        {
                            httpHandler = new AuthMetadataHttpHandler(httpContext);
                        }
                        else if (ProtocolHelper.IsAutodiscoverV2Request(httpContext.Request.Url.AbsolutePath))
                        {
                            httpHandler = new AutodiscoverProxyRequestHandler();
                        }
                    }
                    else
                    {
                        httpHandler = new AutodiscoverProxyRequestHandler();
                    }
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Ews)
                {
                    string httpMethod = httpContext.Request.HttpMethod;
                    if (!httpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase) && !httpMethod.Equals("HEAD", StringComparison.OrdinalIgnoreCase))
                    {
                        httpHandler = new EwsProxyRequestHandler();
                    }
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Ecp)
                {
                    if (EDiscoveryExportToolProxyRequestHandler.IsEDiscoveryExportToolProxyRequest(httpContext.Request))
                    {
                        httpHandler = new EDiscoveryExportToolProxyRequestHandler();
                    }
                    else if (BEResourceRequestHandler.CanHandle(httpContext.Request))
                    {
                        httpHandler = new BEResourceRequestHandler();
                    }
                    else if (EcpProxyRequestHandler.IsCrossForestDelegatedRequest(httpContext.Request))
                    {
                        httpHandler = new EcpProxyRequestHandler
                        {
                            IsCrossForestDelegated = true
                        };
                    }
                    else if (!httpContext.Request.Path.StartsWith("/ecp/auth/", StringComparison.OrdinalIgnoreCase) && !httpContext.Request.Path.Equals("/ecp/ping.ecp", StringComparison.OrdinalIgnoreCase))
                    {
                        httpHandler = new Return401RequestHandler();
                    }
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.RpcHttp)
                {
                    httpHandler = new RpcHttpRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Xrop)
                {
                    httpHandler = new XRopProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.E4e)
                {
                    httpHandler = new E4eProxyRequestHandler();
                }
                else if (AnonymousCalendarProxyRequestHandler.IsAnonymousCalendarRequest(httpContext.Request))
                {
                    httpHandler = new AnonymousCalendarProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Owa && WopiRequestPathHandler.IsWopiRequest(httpContext.Request, AuthCommon.IsFrontEnd))
                {
                    httpHandler = new WopiProxyRequestHandler();
                }
                else if (OwaExtensibilityProxyRequestHandler.IsOwaExtensibilityRequest(httpContext.Request))
                {
                    httpHandler = new OwaExtensibilityProxyRequestHandler();
                }
                else if (OwaCobrandingRedirProxyRequestHandler.IsCobrandingRedirRequest(httpContext.Request))
                {
                    httpHandler = new OwaCobrandingRedirProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Owa && OwaResourceProxyRequestHandler.CanHandle(httpContext.Request))
                {
                    httpHandler = new OwaResourceProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.PowerShellGateway)
                {
                    httpHandler = new PsgwProxyRequestHandler();
                }
                result = httpHandler;
            }
            finally
            {
                long currentLatency = LatencyTracker.FromHttpContext(httpContext).GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency);
                if (currentLatency > 100L)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext), "SelectHandler", currentLatency);
                }
            }
            return(result);
        }
示例#30
0
        private IHttpHandler SelectHandlerForAuthenticatedRequest(HttpContext httpContext)
        {
            IHttpHandler result;

            try
            {
                IHttpHandler httpHandler;
                if (HttpProxyGlobals.ProtocolType == ProtocolType.Mapi)
                {
                    httpHandler = new MapiProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Ecp)
                {
                    if (SiteMailboxCreatingProxyRequestHandler.IsSiteMailboxCreatingProxyRequest(httpContext.Request))
                    {
                        httpHandler = new SiteMailboxCreatingProxyRequestHandler();
                    }
                    else if (EDiscoveryExportToolProxyRequestHandler.IsEDiscoveryExportToolProxyRequest(httpContext.Request))
                    {
                        httpHandler = new EDiscoveryExportToolProxyRequestHandler();
                    }
                    else if (BEResourceRequestHandler.CanHandle(httpContext.Request))
                    {
                        httpHandler = new BEResourceRequestHandler();
                    }
                    else
                    {
                        httpHandler = new EcpProxyRequestHandler();
                    }
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Autodiscover)
                {
                    httpHandler = new AutodiscoverProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Ews)
                {
                    if (EwsUserPhotoProxyRequestHandler.IsUserPhotoRequest(httpContext.Request))
                    {
                        httpHandler = new EwsUserPhotoProxyRequestHandler();
                    }
                    else if (EwsODataProxyRequestHandler.IsODataRequest(httpContext.Request))
                    {
                        httpHandler = new EwsODataProxyRequestHandler();
                    }
                    else if (MrsProxyRequestHandler.IsMrsRequest(httpContext.Request))
                    {
                        httpHandler = new MrsProxyRequestHandler();
                    }
                    else if (MessageTrackingRequestHandler.IsMessageTrackingRequest(httpContext.Request))
                    {
                        httpHandler = new MessageTrackingRequestHandler();
                    }
                    else
                    {
                        httpHandler = new EwsProxyRequestHandler();
                    }
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.RpcHttp)
                {
                    if (RpcHttpRequestHandler.CanHandleRequest(httpContext.Request))
                    {
                        httpHandler = new RpcHttpRequestHandler();
                    }
                    else
                    {
                        httpHandler = new RpcHttpProxyRequestHandler();
                    }
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Eas)
                {
                    httpHandler = new EasProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Oab)
                {
                    httpHandler = new OabProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.PowerShell || HttpProxyGlobals.ProtocolType == ProtocolType.PowerShellLiveId)
                {
                    httpHandler = new RemotePowerShellProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.ReportingWebService)
                {
                    httpHandler = new ReportingWebServiceProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Psws)
                {
                    httpHandler = new PswsProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Xrop)
                {
                    httpHandler = new XRopProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.Owa)
                {
                    string absolutePath = httpContext.Request.Url.AbsolutePath;
                    if (OWAUserPhotoProxyRequestHandler.IsUserPhotoRequest(httpContext.Request))
                    {
                        httpHandler = new OWAUserPhotoProxyRequestHandler();
                    }
                    else if (absolutePath.EndsWith("service.svc", StringComparison.OrdinalIgnoreCase) || absolutePath.IndexOf("/service.svc/", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        httpHandler = new EwsJsonProxyRequestHandler();
                    }
                    else if (absolutePath.EndsWith("ev.owa2", StringComparison.OrdinalIgnoreCase))
                    {
                        httpHandler = new OwaOeh2ProxyRequestHandler();
                    }
                    else if (absolutePath.EndsWith("speech.reco", StringComparison.OrdinalIgnoreCase))
                    {
                        httpHandler = new SpeechRecoProxyRequestHandler();
                    }
                    else if (absolutePath.EndsWith("lang.owa", StringComparison.OrdinalIgnoreCase))
                    {
                        httpHandler = new OwaLanguagePostProxyRequestHandler();
                    }
                    else if (absolutePath.EndsWith("ev.owa", StringComparison.OrdinalIgnoreCase) && httpContext.Request.RawUrl.IndexOf("ns=EwsProxy", StringComparison.OrdinalIgnoreCase) > 0)
                    {
                        httpHandler = new EwsProxyRequestHandler(true);
                    }
                    else
                    {
                        httpHandler = new OwaProxyRequestHandler();
                    }
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.PushNotifications)
                {
                    httpHandler = new PushNotificationsProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.OutlookService)
                {
                    httpHandler = new OutlookServiceProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.SnackyService)
                {
                    httpHandler = new SnackyServiceProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == ProtocolType.E4e)
                {
                    httpHandler = new E4eProxyRequestHandler();
                }
                else
                {
                    if (HttpProxyGlobals.ProtocolType != ProtocolType.O365SuiteService)
                    {
                        throw new InvalidOperationException("Unknown protocol type " + HttpProxyGlobals.ProtocolType);
                    }
                    httpHandler = new O365SuiteServiceProxyRequestHandler();
                }
                result = httpHandler;
            }
            finally
            {
                long currentLatency = LatencyTracker.FromHttpContext(httpContext).GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency);
                if (currentLatency > 100L)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext), "SelectHandler", currentLatency);
                }
            }
            return(result);
        }