Example #1
0
        protected override void OnEndRequestInternal(HttpApplication httpApplication)
        {
            HttpRequest          request  = httpApplication.Context.Request;
            HttpResponse         response = httpApplication.Context.Response;
            RequestDetailsLogger current  = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpApplication.Context);

            if (httpApplication.Context.Items[Constants.RequestCompletedHttpContextKeyName] == null && !UrlUtilities.IsIntegratedAuthUrl(request.Url) && !UrlUtilities.IsOwaMiniUrl(request.Url) && (response.StatusCode == 401 || (HttpProxyGlobals.ProtocolType == ProtocolType.Ecp && (response.StatusCode == 403 || response.StatusCode == 404))))
            {
                FbaModule.LogonReason reason = FbaModule.LogonReason.None;
                if (request.Headers["Authorization"] != null)
                {
                    reason = FbaModule.LogonReason.InvalidCredentials;
                }
                bool flag = request.Url.AbsolutePath.Equals("/owa/auth.owa", StringComparison.OrdinalIgnoreCase);
                if (request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase) || flag)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "NoCookies", "302 - GET/E14AuthPost");

                    this.RedirectToFbaLogon(httpApplication, reason);
                }
                else if (request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "NoCookies", "440 - POST");

                    this.Send440Response(httpApplication, true);
                }
                else
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "NoCookies", "440 - " + request.HttpMethod);

                    this.Send440Response(httpApplication, false);
                }
            }
            base.OnEndRequestInternal(httpApplication);
        }
Example #2
0
        protected override byte[] GetUpdatedBufferToSend(ArraySegment <byte> buffer)
        {
            try
            {
                byte[] result;
                string text;
                if (this.TryGetUpdatedBufferToSend(buffer, out result, out text))
                {
                    ExTraceGlobals.VerboseTracer.TraceDebug <int>((long)this.GetHashCode(), "[RpsOutDataResponseStreamProxy::GetUpdatedBufferToSend] Context={0}, Buffer updated.", base.RequestContext.TraceContext);
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(base.RequestContext.Logger, "FriendlyError", "StreamProxy");

                    return(result);
                }
                if (text != null)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(base.RequestContext.Logger, "FriendlyError", text);
                }
            }
            catch (Exception ex)
            {
                Diagnostics.ReportException(ex, FrontEndHttpProxyEventLogConstants.Tuple_InternalServerError, null, "Exception from RpsOutDataResponseStreamProxy::GetUpdatedBufferToSend event: {0}");
                RequestDetailsLogger logger = base.RequestContext.Logger;
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericError(logger, "GetUpdatedBufferToSendException", ex.ToString());
            }
            return(base.GetUpdatedBufferToSend(buffer));
        }
        // Token: 0x060006FB RID: 1787 RVA: 0x000292BC File Offset: 0x000274BC
        private WinRMInfo ParseWinRMInfo(Stream stream)
        {
            WinRMInfo winRMInfo;
            string    text;

            if (new WinRMParser(base.TraceContext).TryParseStream(stream, out winRMInfo, out text))
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(base.Logger, 21, winRMInfo.Action);

                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(base.Logger, "CommandId", winRMInfo.CommandId);

                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(base.Logger, "SessionId", winRMInfo.SessionId);

                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(base.Logger, "ShellId", winRMInfo.ShellId);

                if (!"http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate".Equals(winRMInfo.SignalCode, StringComparison.OrdinalIgnoreCase))
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(base.Logger, "SignalCode", winRMInfo.SignalCode);
                }
            }
            else
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(base.Logger, 21, text);
            }
            return(winRMInfo);
        }
        // Token: 0x060006F3 RID: 1779 RVA: 0x00028E60 File Offset: 0x00027060
        protected override void ExposeExceptionToClientResponse(Exception ex)
        {
            if (!WinRMHelper.FriendlyErrorEnabled.Value)
            {
                base.ExposeExceptionToClientResponse(ex);
                return;
            }
            if (ex is WebException)
            {
                WebException ex2 = (WebException)ex;
                if (WinRMHelper.IsPingRequest(ex2))
                {
                    if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
                    {
                        ExTraceGlobals.VerboseTracer.TraceDebug <int>((long)this.GetHashCode(), "[RemotePowerShellProxyRequestHandler::ExposeExceptionToClientResponse]: Context={0}, Ping found.", base.TraceContext);
                    }
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(base.Logger, 21, "Ping");

                    base.ClientResponse.Headers["X-RemotePS-Ping"] = "Ping";
                    return;
                }
                if (WinRMHelper.CouldBePingRequest(ex2))
                {
                    if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
                    {
                        ExTraceGlobals.VerboseTracer.TraceDebug <int>((long)this.GetHashCode(), "[RemotePowerShellProxyRequestHandler::ExposeExceptionToClientResponse]: Context={0}, Could be Ping request.", base.TraceContext);
                    }
                    base.ClientResponse.Headers["X-RemotePS-Ping"] = "Possible-Ping";
                    return;
                }
                if (ex2.Status != WebExceptionStatus.ProtocolError)
                {
                    WinRMInfo.SetFailureCategoryInfo(base.ClientResponse.Headers, 3, ex2.Status.ToString());
                }
                if (ex2.Response != null)
                {
                    string text = ex2.Response.Headers["X-BasicAuthToOAuthConversionDiagnostics"];
                    if (!string.IsNullOrWhiteSpace(text))
                    {
                        base.ClientResponse.Headers["X-BasicAuthToOAuthConversionDiagnostics"] = text + " ";
                    }
                }
            }
            if (ex is HttpProxyException && !string.IsNullOrWhiteSpace(ex.Message) && !WinRMHelper.DiagnosticsInfoHasBeenWritten(base.ClientResponse.Headers))
            {
                WinRMInfo.SetFailureCategoryInfo(base.ClientResponse.Headers, 3, ex.GetType().Name);
                string diagnosticsInfo = WinRMHelper.GetDiagnosticsInfo(base.HttpContext);
                if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
                {
                    ExTraceGlobals.VerboseTracer.TraceDebug <int, string>((long)this.GetHashCode(), "[RemotePowerShellProxyRequestHandler::ExposeExceptionToClientResponse]: Context={0}, Write Message {1} to client response.", base.TraceContext, ex.Message);
                }
                WinRMHelper.SetDiagnosticsInfoWrittenFlag(base.ClientResponse.Headers);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(base.Logger, "FriendlyError", "ExposeException");

                base.ClientResponse.Write(diagnosticsInfo + ex.Message);
                return;
            }
            base.ExposeExceptionToClientResponse(ex);
        }
Example #5
0
 internal void LogElapsedTime(RequestDetailsLogger logger, string latencyName)
 {
     if (HttpProxySettings.DetailedLatencyTracingEnabled.Value)
     {
         long currentLatency = this.GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency);
         RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(logger, latencyName, currentLatency);
     }
 }
Example #6
0
        private static void FinalizeRequestLatencies(HttpContext httpContext, RequestDetailsLogger requestDetailsLogger, IActivityScope activityScope, LatencyTracker tracker, int traceContext)
        {
            if (tracker == null)
            {
                return;
            }
            if (requestDetailsLogger == null)
            {
                throw new ArgumentNullException("requestDetailsLogger");
            }
            if (activityScope == null)
            {
                throw new ArgumentNullException("activityScope");
            }
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            long num = tracker.GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency);

            if (num >= 0L)
            {
                long num2 = 0L;
                long.TryParse(activityScope.GetProperty(ServiceLatencyMetadata.HttpPipelineLatency), out num2);
                long num3 = 0L;
                bool flag = requestDetailsLogger.TryGetLatency(HttpProxyMetadata.BackendProcessingLatency, out num3);
                long num4 = requestDetailsLogger.GetLatency(HttpProxyMetadata.ClientRequestStreamingLatency, 0L) + requestDetailsLogger.GetLatency(HttpProxyMetadata.BackendRequestStreamingLatency, 0L) + num3 + requestDetailsLogger.GetLatency(HttpProxyMetadata.BackendResponseStreamingLatency, 0L) + requestDetailsLogger.GetLatency(HttpProxyMetadata.ClientResponseStreamingLatency, 0L);
                long num5 = num - num4;
                PerfCounters.UpdateMovingAveragePerformanceCounter(PerfCounters.HttpProxyCountersInstance.MovingAverageCasLatency, num5);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, HttpProxyMetadata.HttpProxyOverhead, num5);

                long num6 = num5 - num2;
                if (flag)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, HttpProxyMetadata.RoutingLatency, Math.Max(num6, 0L));

                    string property = activityScope.GetProperty(HttpProxyMetadata.TargetServer);
                    if (PerfCounters.RoutingLatenciesEnabled && !string.IsNullOrEmpty(property))
                    {
                        string empty = string.Empty;
                        Utilities.TryGetSiteNameFromServerFqdn(property, out empty);
                        PercentilePerfCounters.UpdateRoutingLatencyPerfCounter(empty, (double)num6);
                        PerfCounters.GetHttpProxyPerSiteCountersInstance(empty).TotalProxyWithLatencyRequests.Increment();
                    }
                }
                long val = num6 - requestDetailsLogger.GetLatency(HttpProxyMetadata.BackendRequestInitLatency, 0L) - requestDetailsLogger.GetLatency(HttpProxyMetadata.BackendResponseInitLatency, 0L);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, HttpProxyMetadata.CoreLatency, Math.Max(val, 0L));

                long currentLatency = tracker.GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency);
                long num7           = currentLatency - num;
                num = currentLatency;
                if (num7 > 5L)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestDetailsLogger, "TotalRequestTimeDelta", num7);
                }
            }
            RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, HttpProxyMetadata.TotalRequestTime, num);
        }
Example #7
0
        public static void LogSharedCacheCall(this IRequestContext requestContext, long latency, string diagnostics)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }
            requestContext.LatencyTracker.HandleSharedCacheLatency(latency);
            RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestContext.Logger, "SharedCache", diagnostics);

            PerfCounters.UpdateMovingAveragePerformanceCounter(PerfCounters.HttpProxyCountersInstance.MovingAverageSharedCacheLatency, latency);
        }
        // Token: 0x060001F3 RID: 499 RVA: 0x00009988 File Offset: 0x00007B88
        private ServiceType GetClientAccessServiceFromList <ServiceType>(List <DownLevelServerStatusEntry> serverList, ServiceTopology topology, AnchorMailbox anchorMailbox, Site targetSite, ClientAccessType clientAccessType, Predicate <ServiceType> otherFilter, RequestDetailsLogger logger, DownLevelServerManager.DownlevelExchangeServerVersion targetDownlevelExchangeServerVersion) where ServiceType : HttpService
        {
            string text     = anchorMailbox.ToCookieKey();
            int    hashCode = HttpProxyBackEndHelper.GetHashCode(text);

            serverList = this.GetFilteredServerListByVersion(serverList, targetDownlevelExchangeServerVersion);
            int[] shuffledList = DownLevelServerManager.GetShuffledList(serverList.Count, hashCode);
            if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
            {
                ExTraceGlobals.VerboseTracer.TraceDebug <string, int, string>((long)this.GetHashCode(), "[DownLevelServerManager::GetClientAccessServiceFromList]: HashKey: {0}, HashCode: {1}, Anchor mailbox {2}.", text, hashCode, anchorMailbox.ToString());
            }
            for (int i = 0; i < shuffledList.Length; i++)
            {
                int num = shuffledList[i];
                DownLevelServerStatusEntry currentServer = serverList[num];
                if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
                {
                    ExTraceGlobals.VerboseTracer.TraceDebug <string, int, bool>((long)this.GetHashCode(), "[DownLevelServerManager::GetClientAccessServiceFromList]: Back end server {0} is selected by current index {1}. IsHealthy = {2}", currentServer.BackEndServer.Fqdn, num, currentServer.IsHealthy);
                }
                if (currentServer.IsHealthy)
                {
                    ServiceType serviceType = topology.FindAny <ServiceType>(clientAccessType, (ServiceType service) => service != null && service.ServerFullyQualifiedDomainName.Equals(currentServer.BackEndServer.Fqdn, StringComparison.OrdinalIgnoreCase) && !service.IsOutOfService && otherFilter(service), "d:\\dbs\\sh\\e16df\\0212_214120_0\\cmd\\1g\\sources\\Dev\\Cafe\\src\\HttpProxy\\DownLevelServerManager\\DownLevelServerManager.cs", "GetClientAccessServiceFromList", 799);
                    if (serviceType != null)
                    {
                        if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
                        {
                            ExTraceGlobals.VerboseTracer.TraceDebug <Uri, string>((long)this.GetHashCode(), "[DownLevelServerManager::GetClientAccessServiceFromList]: Found service {0} matching back end server {1}.", serviceType.Url, currentServer.BackEndServer.Fqdn);
                        }
                        RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(logger, "DownLevelTargetRandomHashing", string.Format("{0}/{1}", i, serverList.Count));

                        return(serviceType);
                    }
                    if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(3))
                    {
                        ExTraceGlobals.VerboseTracer.TraceError <string>((long)this.GetHashCode(), "[DownLevelServerManager::GetClientAccessServiceFromList]: Back end server {0} cannot be found by ServiceDiscovery.", currentServer.BackEndServer.Fqdn);
                    }
                }
                else if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(2))
                {
                    ExTraceGlobals.VerboseTracer.TraceWarning <string>((long)this.GetHashCode(), "[DownLevelServerManager::GetClientAccessServiceFromList]: Back end server {0} is marked as unhealthy.", currentServer.BackEndServer.Fqdn);
                }
            }
            RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(logger, "DownLevelTargetRandomHashingFailure", string.Format("{0}", serverList.Count));

            this.TriggerServerMapRefreshIfNeeded(topology, serverList);
            string text2 = string.Format("Unable to find proper back end service for {0} in site {1}.", anchorMailbox, targetSite.DistinguishedName);

            if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(3))
            {
                ExTraceGlobals.VerboseTracer.TraceError <string>((long)this.GetHashCode(), "[DownLevelServerManager::GetClientAccessServiceFromList]: {0}", text2);
            }
            throw new NoAvailableDownLevelBackEndException(text2);
        }
        private void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpContext  httpContext = HttpContext.Current;
            HttpResponse response    = httpContext.Response;

            if (response != null)
            {
                RequestDetailsLogger current = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext);

                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "OnPreSendRequestHeaders.ContentType", response.ContentType);
            }
            HttpContext.Current.Items["X-HeaderPreSent"] = true;
        }
Example #10
0
        internal static void SafeAppendGenericInfo(string key, string value)
        {
            if (!LoggerSettings.LogEnabled)
            {
                return;
            }
            if (LoggerSettings.IsPowerShellWebService)
            {
                RequestDetailsLoggerBase <PswsLogger> .SafeAppendGenericInfo(RequestDetailsLoggerBase <PswsLogger> .Current, key, value);

                return;
            }
            RequestDetailsLoggerBase <RpsHttpLogger> .SafeAppendGenericInfo(RequestDetailsLoggerBase <RpsHttpLogger> .Current, key, value);
        }
Example #11
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));
        }
Example #12
0
        protected override void UpdateOrInvalidateAnchorMailboxCache(Guid mdbGuid, string resourceForest)
        {
            if (this.originalAnchorMailboxFromExplicitLogon != null && this.originalAnchorMailboxFromExplicitLogon != base.AnchoredRoutingTarget.AnchorMailbox && !string.IsNullOrEmpty(resourceForest))
            {
                ExTraceGlobals.VerboseTracer.TraceDebug <AnchorMailbox, Guid>((long)this.GetHashCode(), "[OwaProxyRequestHandler::UpdateOrInvalidateAnchorMailboxCache]: Updating anchor mailbox cache for original anchor mailbox {0}, mapping to Mailbox Database {1}.", this.originalAnchorMailboxFromExplicitLogon, mdbGuid);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(base.Logger, "UpdateAnchorMbxCache", string.Format("{0}~{1}~{2}", this.originalAnchorMailboxFromExplicitLogon, mdbGuid, resourceForest));

                this.originalAnchorMailboxFromExplicitLogon.UpdateCache(new AnchorMailboxCacheEntry
                {
                    Database = new ADObjectId(mdbGuid, resourceForest)
                });
                return;
            }
            base.UpdateOrInvalidateAnchorMailboxCache(mdbGuid, resourceForest);
        }
Example #13
0
        // Token: 0x06000234 RID: 564 RVA: 0x0000AEE8 File Offset: 0x000090E8
        public bool TryGet(Guid database, IRequestContext requestContext, out MailboxServerCacheEntry cacheEntry)
        {
            cacheEntry = null;
            PerfCounters.HttpProxyCacheCountersInstance.BackEndServerLocalCacheHitsRateBase.Increment();
            PerfCounters.HttpProxyCacheCountersInstance.BackEndServerOverallCacheHitsRateBase.Increment();
            PerfCounters.IncrementMovingPercentagePerformanceCounterBase(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerLocalCacheHitsRate);
            PerfCounters.IncrementMovingPercentagePerformanceCounterBase(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerOverallCacheHitsRate);
            string key  = database.ToString();
            bool   flag = this.TryGetFromInMemoryCache(key, out cacheEntry);

            if (flag)
            {
                if (MailboxServerCache.IsE14ServerStale(cacheEntry))
                {
                    this.Remove(database, requestContext);
                    return(false);
                }
                PerfCounters.HttpProxyCacheCountersInstance.BackEndServerLocalCacheHitsRate.Increment();
                PerfCounters.UpdateMovingPercentagePerformanceCounter(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerLocalCacheHitsRate);
            }
            else
            {
                SharedCacheDiagnostics sharedCacheDiagnostics = null;
                flag = this.TryGetFromSharedCache(key, out cacheEntry, out sharedCacheDiagnostics);
                MailboxServerCache.LogSharedCacheDiagnostics(requestContext, sharedCacheDiagnostics);
                if (flag && this.TryAddToInMemoryCache(key, cacheEntry))
                {
                    this.UpdateInMemoryCacheSizeCounter();
                }
            }
            if (flag)
            {
                PerfCounters.HttpProxyCacheCountersInstance.BackEndServerOverallCacheHitsRate.Increment();
                PerfCounters.UpdateMovingPercentagePerformanceCounter(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerOverallCacheHitsRate);
                if (MailboxServerCache.InMemoryCacheEnabled.Value && MailboxServerCache.InternalRefreshEnabled.Value && cacheEntry.IsDueForRefresh(MailboxServerCache.GetRefreshInterval(cacheEntry.BackEndServer)))
                {
                    this.RegisterRefresh(new DatabaseWithForest(database, cacheEntry.ResourceForest, requestContext.ActivityId));
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestContext.Logger, "ServerLocatorRefresh", database);

                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestContext.Logger, "RefreshingCacheEntry", cacheEntry.ToString());
                }
            }
            return(flag);
        }
Example #14
0
        internal static void SafeAppendGenericInfo(Guid cmdletUniqueId, string key, string value)
        {
            if (!LoggerSettings.LogEnabled)
            {
                return;
            }
            if (LoggerHelper.IsPswsNormalRequest)
            {
                RequestDetailsLoggerBase <PswsLogger> .SafeAppendGenericInfo(RequestDetailsLoggerBase <PswsLogger> .Current, key, value);

                return;
            }
            RpsCmdletLoggerBuffer rpsCmdletLoggerBuffer = RpsCmdletLoggerBuffer.Get(cmdletUniqueId);

            if (rpsCmdletLoggerBuffer != null)
            {
                rpsCmdletLoggerBuffer.AppendGenericInfo(key, value);
            }
        }
Example #15
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);
                }
            }
        }
Example #16
0
        // Token: 0x06000237 RID: 567 RVA: 0x0000B090 File Offset: 0x00009290
        public void Remove(Guid database, IRequestContext requestContext)
        {
            string key = database.ToString();

            if (this.TryRemoveFromInMemoryCache(key))
            {
                this.UpdateInMemoryCacheSizeCounter();
            }
            SharedCacheDiagnostics sharedCacheDiagnostics;

            if (this.TryRemoveFromSharedCache(key, out sharedCacheDiagnostics))
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestContext.Logger, "SharedCache", "MailboxServerCacheEntryRemovalSuccess");
            }
            else
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericError(requestContext.Logger, "SharedCache", "MailboxServerCacheEntryRemovalFailure");
            }
            MailboxServerCache.LogSharedCacheDiagnostics(requestContext, sharedCacheDiagnostics);
        }
        // Token: 0x06000380 RID: 896 RVA: 0x00013F04 File Offset: 0x00012104
        private bool TryGetUpdatedBufferToSend(ArraySegment <byte> buffer, out byte[] updatedBuffer, out string failureHint)
        {
            HttpContext context = base.RequestContext.HttpContext;

            updatedBuffer = null;
            failureHint   = null;
            if (context.Response == null)
            {
                failureHint = "Response Null";
                return(false);
            }
            int statusCode = context.Response.StatusCode;

            if (statusCode < 400)
            {
                if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
                {
                    ExTraceGlobals.VerboseTracer.TraceDebug <int, int>((long)this.GetHashCode(), "[RpsOutDataResponseStreamProxy::TryGetUpdatedBufferToSend] Context={0}, StatusCode={1}.", base.RequestContext.TraceContext, statusCode);
                }
                return(false);
            }
            if (WinRMHelper.DiagnosticsInfoHasBeenWritten(context.Response.Headers))
            {
                if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
                {
                    ExTraceGlobals.VerboseTracer.TraceDebug <int>((long)this.GetHashCode(), "[RpsOutDataResponseStreamProxy::TryGetUpdatedBufferToSend] Context={0}, diagnostics info has been written.", base.RequestContext.TraceContext);
                }
                failureHint = "BeenWritten";
                return(false);
            }
            if (WinRMHelper.TryInsertDiagnosticsInfo(buffer, () => WinRMHelper.GetDiagnosticsInfo(context), out updatedBuffer, out failureHint, delegate(string winRMFaultMessage)
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(this.RequestContext.Logger, "WinRMFaultMessage", winRMFaultMessage);
                WinRMInfo.SetWSManFailureCategory(context.Response.Headers, winRMFaultMessage);
            }))
            {
                WinRMHelper.SetDiagnosticsInfoWrittenFlag(context.Response.Headers);
                return(true);
            }
            return(false);
        }
Example #18
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));
        }
Example #19
0
        // Token: 0x06000218 RID: 536 RVA: 0x0000A8E0 File Offset: 0x00008AE0
        public void Remove(string key, IRequestContext requestContext)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (this.TryRemoveFromInMemoryCache(key))
            {
                this.UpdateInMemoryCacheSizeCounter();
            }
            SharedCacheDiagnostics sharedCacheDiagnostics;

            if (this.TryRemoveFromSharedCache(key, out sharedCacheDiagnostics))
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestContext.Logger, "SharedCache", "AMCacheRemovalSuccess");
            }
            else
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericError(requestContext.Logger, "SharedCache", "AMCacheRemovalFailure");
            }
            AnchorMailboxCache.LogSharedCacheDiagnostics(requestContext, sharedCacheDiagnostics);
        }
        private static bool ShouldBlockConnection(HttpContext httpContext, OwaIdentity logonIdentity)
        {
            if (!VariantConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).OwaServer.OwaClientAccessRulesEnabled.Enabled)
            {
                return(false);
            }
            RequestDetailsLogger logger = OwaApplication.GetRequestDetailsLogger;
            Action <ClientAccessRulesEvaluationContext> blockLoggerDelegate = delegate(ClientAccessRulesEvaluationContext context)
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(logger, ClientAccessRulesConstants.ClientAccessRuleName, context.CurrentRule.Name);
            };
            Action <double> latencyLoggerDelegate = delegate(double latency)
            {
                if (latency > 50.0)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(logger, ClientAccessRulesConstants.ClientAccessRulesLatency, latency);
                }
            };
            OWAMiniRecipient owaminiRecipient          = logonIdentity.GetOWAMiniRecipient();
            string           usernameFromIdInformation = ClientAccessRulesUtils.GetUsernameFromIdInformation(owaminiRecipient.WindowsLiveID, owaminiRecipient.MasterAccountSid, owaminiRecipient.Sid, owaminiRecipient.ObjectId);

            return(ClientAccessRulesUtils.ShouldBlockConnection(logonIdentity.UserOrganizationId, usernameFromIdInformation, ClientAccessProtocol.OutlookWebApp, ClientAccessRulesUtils.GetRemoteEndPointFromContext(httpContext), httpContext.Request.IsAuthenticatedByAdfs() ? ClientAccessAuthenticationMethod.AdfsAuthentication : ClientAccessAuthenticationMethod.BasicAuthentication, owaminiRecipient, blockLoggerDelegate, latencyLoggerDelegate));
        }
Example #21
0
        // Token: 0x060005FB RID: 1531 RVA: 0x00021BD8 File Offset: 0x0001FDD8
        private void OnEndRequest(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContext     httpContext     = httpApplication.Context;

            CheckpointTracker.GetOrCreate(httpContext.Items).Add(FrontEndHttpProxyCheckpoints.ProxyModuleEndRequest);
            Diagnostics.SendWatsonReportOnUnhandledException(delegate()
            {
                if (!HostHeaderValidator.HasValidHostHeaderStatusDescription(new HttpContextWrapper(httpContext).Response) || httpContext.Items["AutodiscoverRedirectModule"] != null)
                {
                    return;
                }
                LatencyTracker latencyTracker = LatencyTracker.FromHttpContext(httpContext);
                RequestDetailsLogger current  = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext), GuardedSharedCacheExecution.Default.Key, GuardedSharedCacheExecution.Default.Guard.GetCurrentValue());
                int traceContext = httpContext.GetTraceContext();
                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 (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
                {
                    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 : IIdentityExtensions.GetSafeName(httpContext.User.Identity, true),
                        traceContext
                    });
                }
                if (latencyTracker != null)
                {
                    long currentLatency = latencyTracker.GetCurrentLatency(LatencyTrackerKey.HandlerToModuleSwitchingLatency);
                    if (currentLatency >= 0L)
                    {
                        RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(current, 5, currentLatency);
                    }
                }
                ProxyRequestHandler proxyRequestHandler = httpContext.CurrentHandler as ProxyRequestHandler;
                if (proxyRequestHandler != null && !proxyRequestHandler.IsDisposed)
                {
                    current.AppendGenericInfo("DisposeProxyRequestHandler", "ProxyModule::OnEndRequest");
                    proxyRequestHandler.Dispose();
                }
                ProxyModule.InspectNativeProxyFatalError(httpContext.Response, current);
                string text = httpContext.Items["AnonymousRequestFilterModule"] as string;
                if (!string.IsNullOrEmpty(text))
                {
                    current.AppendGenericInfo("AnonymousRequestFilterModule", text);
                }
                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");
                        RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(current, 0, DateTime.UtcNow);
                        current.AsyncCommit(false, NativeProxyHelper.WasProxiedByNativeProxyHandler(SharedHttpContextWrapper.GetWrapper(httpContext)));
                    }
                    if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
                    {
                        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));
        }
Example #22
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);
        }
Example #23
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);
        }
Example #24
0
        private void ParseCadataCookies(HttpApplication httpApplication)
        {
            HttpContext          context  = httpApplication.Context;
            HttpRequest          request  = context.Request;
            HttpResponse         response = context.Response;
            RequestDetailsLogger current  = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(context);

            string text = null;

            if (request.Cookies["cadata"] != null && request.Cookies["cadata"].Value != null)
            {
                text = request.Cookies["cadata"].Value;
            }
            string text2 = null;

            if (request.Cookies["cadataKey"] != null && request.Cookies["cadataKey"].Value != null)
            {
                text2 = request.Cookies["cadataKey"].Value;
            }
            string text3 = null;

            if (request.Cookies["cadataIV"] != null && request.Cookies["cadataIV"].Value != null)
            {
                text3 = request.Cookies["cadataIV"].Value;
            }
            string text4 = null;

            if (request.Cookies["cadataSig"] != null && request.Cookies["cadataSig"].Value != null)
            {
                text4 = request.Cookies["cadataSig"].Value;
            }
            string text5 = null;

            if (request.Cookies["cadataTTL"] != null && request.Cookies["cadataTTL"].Value != null)
            {
                text5 = request.Cookies["cadataTTL"].Value;
            }
            if (text == null || text2 == null || text3 == null || text4 == null || text5 == null)
            {
                return;
            }
            byte[] array  = null;
            byte[] array2 = null;
            PerfCounters.HttpProxyCacheCountersInstance.FbaModuleKeyCacheHitsRateBase.Increment();
            FbaModule.KeyCache.TryGetValue(text2, out array);
            FbaModule.KeyCache.TryGetValue(text3, out array2);
            if (array != null && array2 != null)
            {
                PerfCounters.HttpProxyCacheCountersInstance.FbaModuleKeyCacheHitsRate.Increment();
                goto IL_362;
            }
            string text6 = null;
            RSACryptoServiceProvider rsacryptoServiceProvider;

            try
            {
                X509Certificate2 sslCertificate = FbaModule.GetSslCertificate(request);
                rsacryptoServiceProvider = (sslCertificate.PrivateKey as RSACryptoServiceProvider);
                if (rsacryptoServiceProvider != null)
                {
                    byte[] rgb     = Convert.FromBase64String(text4);
                    byte[] bytes   = rsacryptoServiceProvider.Decrypt(rgb, true);
                    string @string = Encoding.Unicode.GetString(bytes);
                    if (string.Compare(@string, "Fba Rocks!", StringComparison.Ordinal) != 0)
                    {
                        text6 = "does not match the SSL certificate on the Cafe web-site on another server in this Cafe array";
                    }
                }
                else
                {
                    text6 = "does not contain RSACryptoServiceProvider";
                    if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
                    {
                        ExTraceGlobals.VerboseTracer.TraceDebug((long)this.GetHashCode(), "[FbaModule::ParseCadataCookies] Certificate:{0},Name:{1},Thumbprint:{2},PrivateKeyKey.(Exchange/Signature)Algorighm:{3} has no RSACryptoServiceProvider", new object[]
                        {
                            sslCertificate.Subject,
                            sslCertificate.FriendlyName,
                            sslCertificate.Thumbprint,
                            (sslCertificate.PrivateKey == null) ? "NULL" : (sslCertificate.PrivateKey.KeyExchangeAlgorithm + "/" + sslCertificate.PrivateKey.SignatureAlgorithm)
                        });
                    }
                }
            }
            catch (CryptographicException arg)
            {
                ExTraceGlobals.VerboseTracer.TraceDebug <CryptographicException>((long)this.GetHashCode(), "[FbaModule::ParseCadataCookies] Received CryptographicException {0} decrypting cadataSig", arg);
                return;
            }
            if (text6 == null)
            {
                byte[] rgb2 = Convert.FromBase64String(text2);
                byte[] rgb3 = Convert.FromBase64String(text3);
                try
                {
                    array  = rsacryptoServiceProvider.Decrypt(rgb2, true);
                    array2 = rsacryptoServiceProvider.Decrypt(rgb3, true);
                }
                catch (CryptographicException arg2)
                {
                    ExTraceGlobals.VerboseTracer.TraceDebug <CryptographicException>((long)this.GetHashCode(), "[FbaModule::ParseCadataCookies] Received CryptographicException {0} decrypting symKey/symIV", arg2);
                    return;
                }
                this.cadataKeyString = text2;
                this.cadataIVString  = text3;
                this.symKey          = array;
                this.symIV           = array2;
                goto IL_362;
            }
            ExTraceGlobals.VerboseTracer.TraceError <string, string>((long)this.GetHashCode(), "[FbaModule::ParseCadataCookies] {0} {1}", "Error in validating Cadata signature. This most likely indicates that the SSL certifcate on the Cafe web-site on this server ", text6);
            return;

IL_362:
            using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider())
            {
                aesCryptoServiceProvider.Key = array;
                aesCryptoServiceProvider.IV  = array2;
                using (ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateDecryptor())
                {
                    byte[] array3 = Convert.FromBase64String(text5);
                    byte[] array4 = null;
                    try
                    {
                        array4 = cryptoTransform.TransformFinalBlock(array3, 0, array3.Length);
                    }
                    catch (CryptographicException arg3)
                    {
                        ExTraceGlobals.VerboseTracer.TraceDebug <CryptographicException>((long)this.GetHashCode(), "[FbaModule::ParseCadataCookies] Received CryptographicException {0} transforming TTL", arg3);
                        return;
                    }
                    if (array4.Length < 1)
                    {
                        ExTraceGlobals.VerboseTracer.TraceDebug((long)this.GetHashCode(), "[FbaModule::ParseCadataCookies] TTL length was less than 1.");
                        return;
                    }
                    long ticks = BitConverter.ToInt64(array4, 0);
                    int  num   = (int)array4[8];
                    bool flag  = (num & 4) == 4;
                    context.Items["Flags"] = num;
                    ExDateTime t      = new ExDateTime(ExTimeZone.UtcTimeZone, ticks);
                    ExDateTime utcNow = ExDateTime.UtcNow;
                    if (t < utcNow)
                    {
                        if (request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
                        {
                            if (request.QueryString.ToString().StartsWith("oeh=1&", StringComparison.OrdinalIgnoreCase))
                            {
                                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "LoginTimeout", "440 - GET/OEH");

                                this.Send440Response(httpApplication, false);
                            }
                            else
                            {
                                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "LoginTimeout", "302 - GET/Timeout");

                                this.RedirectToFbaLogon(httpApplication, FbaModule.LogonReason.Timeout);
                            }
                        }
                        else if (request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
                        {
                            RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "LoginTimeout", "440 - POST");

                            this.Send440Response(httpApplication, true);
                        }
                        else
                        {
                            RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "LoginTimeout", "440 - " + request.HttpMethod);

                            this.Send440Response(httpApplication, false);
                        }
                        return;
                    }
                    FbaModule.DetermineKeyIntervalsIfNecessary();
                    ExDateTime t2 = t.AddTicks(-2L * (flag ? FbaModule.fbaPrivateKeyReissueInterval.Ticks : FbaModule.fbaPublicKeyReissueInterval.Ticks));
                    if (t2 < utcNow && OwaAuthenticationHelper.IsOwaUserActivityRequest(request))
                    {
                        FbaModule.SetCadataTtlCookie(aesCryptoServiceProvider, num, request, response);
                    }
                }
                using (ICryptoTransform cryptoTransform2 = aesCryptoServiceProvider.CreateDecryptor())
                {
                    byte[] array5 = Convert.FromBase64String(text);
                    byte[] bytes2 = null;
                    try
                    {
                        bytes2 = cryptoTransform2.TransformFinalBlock(array5, 0, array5.Length);
                    }
                    catch (CryptographicException arg4)
                    {
                        ExTraceGlobals.VerboseTracer.TraceDebug <CryptographicException>((long)this.GetHashCode(), "[FbaModule::ParseCadataCookies] Received CryptographicException {0} transforming auth", arg4);
                        return;
                    }
                    string string2 = Encoding.Unicode.GetString(bytes2);
                    request.Headers["Authorization"] = string2;
                }
            }
        }
        public bool TryGet(Guid database, IRequestContext requestContext, out BackEndServer backEndServer)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }
            backEndServer = null;
            PerfCounters.HttpProxyCacheCountersInstance.BackEndServerLocalCacheHitsRateBase.Increment();
            PerfCounters.HttpProxyCacheCountersInstance.BackEndServerOverallCacheHitsRateBase.Increment();
            PerfCounters.IncrementMovingPercentagePerformanceCounterBase(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerLocalCacheHitsRate);
            PerfCounters.IncrementMovingPercentagePerformanceCounterBase(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerOverallCacheHitsRate);
            MailboxServerCacheEntry mailboxServerCacheEntry = null;
            bool flag  = false;
            bool flag2 = this.serversCache.TryGetValue(database, out mailboxServerCacheEntry);

            if (flag2)
            {
                if (MailboxServerCache.IsE14ServerStale(mailboxServerCacheEntry))
                {
                    this.Remove(database, requestContext);
                    return(false);
                }
                backEndServer = mailboxServerCacheEntry.BackEndServer;
                PerfCounters.HttpProxyCacheCountersInstance.BackEndServerLocalCacheHitsRate.Increment();
                PerfCounters.UpdateMovingPercentagePerformanceCounter(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerLocalCacheHitsRate);
                if (mailboxServerCacheEntry.IsDueForRefresh(MailboxServerCache.GetRefreshInterval(backEndServer)))
                {
                    flag = true;
                }
            }
            if (HttpProxySettings.MailboxServerLocatorSharedCacheEnabled.Value && (!flag2 || flag))
            {
                MailboxServerCacheEntry sharedCacheEntry = null;
                long   latency  = 0L;
                string diagInfo = null;
                bool   latency2 = LatencyTracker.GetLatency <bool>(() => this.sharedCacheClient.TryGet <MailboxServerCacheEntry>(database.ToString(), requestContext.ActivityId, out sharedCacheEntry, out diagInfo), out latency);
                requestContext.LogSharedCacheCall(latency, diagInfo);
                if (latency2 && (!flag2 || sharedCacheEntry.LastRefreshTime > mailboxServerCacheEntry.LastRefreshTime))
                {
                    this.Add(database, sharedCacheEntry, requestContext, false);
                    mailboxServerCacheEntry = sharedCacheEntry;
                    flag2 = true;
                }
            }
            if (flag2)
            {
                backEndServer = mailboxServerCacheEntry.BackEndServer;
                PerfCounters.HttpProxyCacheCountersInstance.BackEndServerOverallCacheHitsRate.Increment();
                PerfCounters.UpdateMovingPercentagePerformanceCounter(PerfCounters.HttpProxyCacheCountersInstance.MovingPercentageBackEndServerOverallCacheHitsRate);
                if (!this.LazyRefreshDisabled && mailboxServerCacheEntry.IsDueForRefresh(MailboxServerCache.GetRefreshInterval(mailboxServerCacheEntry.BackEndServer)))
                {
                    if (MailboxServerCache.BackgroundServerRefreshEnabled.Value)
                    {
                        this.RegisterRefresh(new DatabaseWithForest(database, mailboxServerCacheEntry.ResourceForest, requestContext.ActivityId));
                    }
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestContext.Logger, "ServerLocatorRefresh", database);

                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestContext.Logger, "RefreshingCacheEntry", mailboxServerCacheEntry.ToString());
                }
            }
            return(flag2);
        }
Example #26
0
        // Token: 0x060005F5 RID: 1525 RVA: 0x00021738 File Offset: 0x0001F938
        private IHttpHandler SelectHandlerForUnauthenticatedRequest(HttpContext httpContext)
        {
            IHttpHandler result;

            try
            {
                if (HttpProxySettings.NeedHandleAsAuthenticatedRequest(httpContext.Request.Headers, httpContext.Request.Cookies, httpContext.SkipAuthorization))
                {
                    result = this.SelectHandlerForAuthenticatedRequest(httpContext);
                }
                else
                {
                    UriBuilder uriBuilder = new UriBuilder(httpContext.Request.Url);
                    string     text       = null;
                    if (UrlUtilities.TryGetExplicitLogonUser(httpContext.Request, ref text))
                    {
                        uriBuilder.Path = UrlUtilities.GetPathWithExplictLogonHint(httpContext.Request.Url, text);
                    }
                    IHttpHandler httpHandler = null;
                    if (HttpProxyGlobals.ProtocolType == 9)
                    {
                        httpHandler = new AutodiscoverProxyRequestHandler();
                    }
                    else if (HttpProxyGlobals.ProtocolType == 2)
                    {
                        if (RequestPathParser.IsEwsUnauthenticatedRequestProxyHandlerAllowed(httpContext.Request))
                        {
                            httpHandler = new EwsProxyRequestHandler();
                        }
                    }
                    else if (HttpProxyGlobals.ProtocolType == 27)
                    {
                        if (RequestPathParser.IsRestUnauthenticatedRequestProxyHandlerAllowed(httpContext.Request))
                        {
                            httpHandler = new RestProxyRequestHandler();
                        }
                    }
                    else if (HttpProxyGlobals.ProtocolType == 1)
                    {
                        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 == 8)
                    {
                        httpHandler = new RpcHttpRequestHandler();
                    }
                    else if (HttpProxyGlobals.ProtocolType == 12)
                    {
                        httpHandler = new XRopProxyRequestHandler();
                    }
                    else if (HttpProxyGlobals.ProtocolType == 15)
                    {
                        httpHandler = new E4eProxyRequestHandler();
                    }
                    else if (AnonymousCalendarProxyRequestHandler.IsAnonymousCalendarRequest(httpContext.Request))
                    {
                        httpHandler = new AnonymousCalendarProxyRequestHandler();
                    }
                    else if (HttpProxyGlobals.ProtocolType == 4 && WopiRequestPathHandler.IsWopiRequest(httpContext.Request.HttpMethod, httpContext.Request.Url, AuthCommon.IsFrontEnd))
                    {
                        httpHandler = new WopiProxyRequestHandler();
                    }
                    else if (OwaExtensibilityProxyRequestHandler.IsOwaExtensibilityRequest(httpContext.Request))
                    {
                        httpHandler = new OwaExtensibilityProxyRequestHandler();
                    }
                    else if (UrlUtilities.IsOwaDownloadRequest(uriBuilder.Uri))
                    {
                        httpHandler = new OwaDownloadProxyRequestHandler();
                    }
                    else if (OwaCobrandingRedirProxyRequestHandler.IsCobrandingRedirRequest(httpContext.Request))
                    {
                        httpHandler = new OwaCobrandingRedirProxyRequestHandler();
                    }
                    else if (HttpProxyGlobals.ProtocolType == 4 && OwaResourceProxyRequestHandler.CanHandle(httpContext.Request))
                    {
                        httpHandler = new OwaResourceProxyRequestHandler();
                    }
                    else if (HttpProxyGlobals.ProtocolType == 19)
                    {
                        httpHandler = new PsgwProxyRequestHandler();
                    }
                    else if (HttpProxyGlobals.ProtocolType == 21)
                    {
                        httpHandler = new MailboxDeliveryProxyRequestHandler();
                    }
                    else if (HttpProxyGlobals.ProtocolType == 22)
                    {
                        httpHandler = new ComplianceServiceProxyRequestHandler();
                    }
                    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);
        }
Example #27
0
        private GetGroupResponse GetPDLData()
        {
            GetGroupResponse getGroupResponse = new GetGroupResponse();
            MailboxSession   mailboxIdentityMailboxSession = base.CallContext.SessionCache.GetMailboxIdentityMailboxSession();
            ItemId           sourceId     = this.itemId;
            IdAndSession     idAndSession = null;

            if (this.parentFolderid != null && this.parentFolderid.BaseFolderId != null)
            {
                IdAndSession idAndSession2 = base.GetIdAndSession(this.parentFolderid.BaseFolderId);
                if (idAndSession2 != null && idAndSession2.Session.IsPublicFolderSession)
                {
                    idAndSession = idAndSession2;
                }
            }
            if (IdConverter.EwsIdIsConversationId(this.itemId.Id))
            {
                try
                {
                    Persona persona;
                    if (idAndSession != null)
                    {
                        persona = Persona.LoadFromPersonaId(idAndSession.Session, null, this.itemId, Persona.FullPersonaShape, null, idAndSession.Id);
                    }
                    else
                    {
                        persona = Persona.LoadFromPersonIdWithGalAggregation(mailboxIdentityMailboxSession, IdConverter.EwsIdToPersonId(this.itemId.Id), Persona.FullPersonaShape, null);
                    }
                    if (persona.Attributions.Length > 0)
                    {
                        sourceId = persona.Attributions[0].SourceId;
                        for (int i = 1; i < persona.Attributions.Length; i++)
                        {
                            StoreId storeId = IdConverter.EwsIdToMessageStoreObjectId(persona.Attributions[i].SourceId.Id);
                            using (Item item = Item.Bind(mailboxIdentityMailboxSession, storeId, new PropertyDefinition[]
                            {
                                ContactSchema.PersonId
                            }))
                            {
                                item.OpenAsReadWrite();
                                item[ContactSchema.PersonId] = PersonId.CreateNew();
                                item.Save(SaveMode.NoConflictResolution);
                            }
                        }
                        RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLogger.Current, "UnlinkDupedPDLs", "Success");
                    }
                    else
                    {
                        ExTraceGlobals.GetGroupTracer.TraceError((long)this.hashCode, "ItemId is PersonaId but Persona has no linked contacts (attributions array is empty).");
                        RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLogger.Current, "UnlinkDupedPDLs", "Skipped");
                    }
                }
                catch (LocalizedException arg)
                {
                    ExTraceGlobals.GetGroupTracer.TraceError <LocalizedException>((long)this.hashCode, "Failed to unlink PDLs: {0}", arg);
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLogger.Current, "UnlinkDupedPDLs", "Failed");
                }
            }
            IdAndSession idAndSession3 = base.IdConverter.ConvertItemIdToIdAndSessionReadOnly(sourceId);
            StoreSession storeSession;

            if (idAndSession != null)
            {
                storeSession = idAndSession.Session;
            }
            else
            {
                storeSession = ((idAndSession3.Session as MailboxSession) ?? base.CallContext.SessionCache.GetMailboxIdentityMailboxSession());
            }
            using (DistributionList distributionList = DistributionList.Bind(storeSession, idAndSession3.Id))
            {
                if (distributionList == null)
                {
                    this.WriteDebugTrace("No PDL was found");
                    return(getGroupResponse);
                }
                PersonId personId = (PersonId)distributionList[ContactSchema.PersonId];
                getGroupResponse.PersonaId = IdConverter.PersonaIdFromPersonId(storeSession.MailboxGuid, personId);
                if (!distributionList.GetValueOrDefault <bool>(ItemSchema.ConversationIndexTracking, false))
                {
                    try
                    {
                        distributionList.OpenAsReadWrite();
                        distributionList[ItemSchema.ConversationIndexTracking] = true;
                        distributionList.Save(SaveMode.NoConflictResolution);
                        RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLogger.Current, "SetConversationIndexTracking", "Success");
                    }
                    catch (LocalizedException arg2)
                    {
                        ExTraceGlobals.GetGroupTracer.TraceError <LocalizedException>((long)this.hashCode, "Failed to set ConversationIndexTracking on PDL: {0}", arg2);
                        RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(RequestDetailsLogger.Current, "SetConversationIndexTracking", "Failed");
                    }
                }
                if (!this.IsMembersInResultSet)
                {
                    return(getGroupResponse);
                }
                int count = distributionList.Count;
                getGroupResponse.MembersCount = count;
                this.WriteDebugTrace("Total PDL members count is " + count);
                if (this.paging.Offset < 0 || count <= this.paging.Offset)
                {
                    this.WriteDebugTrace(string.Format("Provided offset is out of range - members count is {0}, offset is {1}.", count, this.paging.Offset));
                    return(getGroupResponse);
                }
                distributionList.Sort(this.PDlMembersComparer);
                List <Persona>           list       = new List <Persona>();
                List <string>            list2      = new List <string>();
                Dictionary <string, int> dictionary = new Dictionary <string, int>();
                int num = Math.Min(count, this.paging.Offset + this.paging.MaxRows);
                for (int j = this.paging.Offset; j < num; j++)
                {
                    DistributionListMember distributionListMember = distributionList[j];
                    if (distributionListMember.Participant == null)
                    {
                        if (num < count)
                        {
                            num++;
                        }
                        getGroupResponse.MembersCount--;
                    }
                    else
                    {
                        bool    flag     = false;
                        Persona persona2 = GetGroupCommand.CreatePersonaFromDistributionListMember(mailboxIdentityMailboxSession, distributionListMember, out flag);
                        if (flag)
                        {
                            list2.Add(persona2.EmailAddress.EmailAddress);
                            dictionary.Add(persona2.EmailAddress.EmailAddress, list.Count);
                        }
                        list.Add(persona2);
                    }
                }
                if (list2.Count > 0)
                {
                    IRecipientSession     galscopedADRecipientSession = base.CallContext.ADRecipientSessionContext.GetGALScopedADRecipientSession(base.CallContext.EffectiveCaller.ClientSecurityContext);
                    Result <ADRawEntry>[] array = galscopedADRecipientSession.FindByLegacyExchangeDNs(list2.ToArray(), new PropertyDefinition[]
                    {
                        ADObjectSchema.Id,
                        ADRecipientSchema.DisplayName,
                        ADRecipientSchema.PrimarySmtpAddress,
                        ADRecipientSchema.RecipientType,
                        ADRecipientSchema.RecipientTypeDetails,
                        ADRecipientSchema.LegacyExchangeDN
                    });
                    foreach (Result <ADRawEntry> result in array)
                    {
                        if (result.Data != null)
                        {
                            Persona personaFromADObject = GetGroupCommand.GetPersonaFromADObject(result.Data);
                            string  key = result.Data[ADRecipientSchema.LegacyExchangeDN] as string;
                            int     num2;
                            if (dictionary.ContainsKey(key) && dictionary.TryGetValue(key, out num2) && num2 >= 0)
                            {
                                list[num2] = personaFromADObject;
                            }
                        }
                    }
                }
                list.Sort(this.PersonaComparer);
                Persona[] array3 = new Persona[list.Count];
                list.CopyTo(0, array3, 0, list.Count);
                getGroupResponse.Members = array3;
                this.WriteDebugTrace("PDL members count loaded in the response is " + getGroupResponse.Members.Length);
            }
            return(getGroupResponse);
        }
        private void OnEndRequest(object sender, EventArgs e)
        {
            HttpContext  httpContext = HttpContext.Current;
            HttpResponse response    = httpContext.Response;

            if (response == null)
            {
                return;
            }
            RequestDetailsLogger current = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext);

            RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "OnEndRequest.Start.ContentType", response.ContentType);

            if (response.Headers["X-RemotePS-RevisedAction"] != null)
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(current, HttpProxyMetadata.ProtocolAction, response.Headers["X-RemotePS-RevisedAction"]);
            }
            bool flag = httpContext.Items.Contains("X-HeaderPreSent") && (bool)httpContext.Items["X-HeaderPreSent"];

            if (flag)
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "FriendlyError", "Skip-HeaderPreSent");

                return;
            }
            try
            {
                int statusCode = response.StatusCode;
                int num;
                if (WinRMHelper.TryConvertStatusCode(statusCode, out num))
                {
                    ExTraceGlobals.VerboseTracer.TraceDebug <int, int>((long)this.GetHashCode(), "[RpsFriendlyErrorModule::OnEndRequest]: Convert status code from {0} to {1}.", statusCode, num);
                    response.StatusCode = num;
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(current, ServiceCommonMetadata.HttpStatus, statusCode);
                }
                if (statusCode >= 400 && !"Ping".Equals(response.Headers["X-RemotePS-Ping"], StringComparison.OrdinalIgnoreCase) && !"Possible-Ping".Equals(response.Headers["X-RemotePS-Ping"], StringComparison.OrdinalIgnoreCase))
                {
                    response.ContentType = "application/soap+xml;charset=UTF-8";
                    if (!WinRMHelper.DiagnosticsInfoHasBeenWritten(response.Headers))
                    {
                        string diagnosticsInfo = WinRMHelper.GetDiagnosticsInfo(httpContext);
                        ExTraceGlobals.VerboseTracer.TraceDebug <int, string>((long)this.GetHashCode(), "[RpsFriendlyErrorModule::OnEndRequest]: Original Status Code: {0}, Append diagnostics info: {1}.", statusCode, diagnosticsInfo);
                        if (statusCode == 401)
                        {
                            response.Output.Write(diagnosticsInfo + HttpProxyStrings.ErrorAccessDenied);
                        }
                        else
                        {
                            response.Output.Write(diagnosticsInfo);
                        }
                        RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "FriendlyError", "HttpModule");
                    }
                }
            }
            catch (Exception ex)
            {
                ExTraceGlobals.VerboseTracer.TraceError <Exception>((long)this.GetHashCode(), "[RpsFriendlyErrorModule::OnEndRequest]: Exception = {0}", ex);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericError(current, "RpsFriendlyErrorModule.OnEndRequest", ex.Message);
            }
            finally
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(current, "OnEndRequest.End.ContentType", response.ContentType);
            }
        }
Example #29
0
        // Token: 0x060005F4 RID: 1524 RVA: 0x000213C0 File Offset: 0x0001F5C0
        private IHttpHandler SelectHandlerForAuthenticatedRequest(HttpContext httpContext)
        {
            IHttpHandler result;

            try
            {
                IHttpHandler httpHandler;
                if (HttpProxyGlobals.ProtocolType == 14)
                {
                    httpHandler = new MapiProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 1)
                {
                    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 == 9)
                {
                    httpHandler = new AutodiscoverProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 2)
                {
                    if (EwsUserPhotoProxyRequestHandler.IsUserPhotoRequest(httpContext.Request))
                    {
                        httpHandler = new EwsUserPhotoProxyRequestHandler();
                    }
                    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 == 27)
                {
                    httpHandler = new RestProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 8)
                {
                    if (RpcHttpRequestHandler.CanHandleRequest(httpContext.Request))
                    {
                        httpHandler = new RpcHttpRequestHandler();
                    }
                    else
                    {
                        httpHandler = new RpcHttpProxyRequestHandler();
                    }
                }
                else if (HttpProxyGlobals.ProtocolType == null)
                {
                    httpHandler = new EasProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 3)
                {
                    httpHandler = new OabProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 6 || HttpProxyGlobals.ProtocolType == 7)
                {
                    httpHandler = new RemotePowerShellProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 10)
                {
                    httpHandler = new ReportingWebServiceProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 11)
                {
                    httpHandler = new PswsProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 12)
                {
                    httpHandler = new XRopProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 4)
                {
                    string absolutePath = httpContext.Request.Url.AbsolutePath;
                    if (OWAUserPhotoProxyRequestHandler.IsUserPhotoRequest(httpContext.Request))
                    {
                        httpHandler = new OWAUserPhotoProxyRequestHandler();
                    }
                    else if (RequestPathParser.IsOwaEwsJsonRequest(absolutePath))
                    {
                        httpHandler = new EwsJsonProxyRequestHandler();
                    }
                    else if (RequestPathParser.IsOwaOeh2Request(absolutePath))
                    {
                        httpHandler = new OwaOeh2ProxyRequestHandler();
                    }
                    else if (RequestPathParser.IsOwaSpeechRecoRequest(absolutePath))
                    {
                        httpHandler = new SpeechRecoProxyRequestHandler();
                    }
                    else if (RequestPathParser.IsOwaLanguagePostRequest(absolutePath))
                    {
                        httpHandler = new OwaLanguagePostProxyRequestHandler();
                    }
                    else if (RequestPathParser.IsOwaE14ProxyRequest(absolutePath, httpContext.Request.RawUrl))
                    {
                        httpHandler = new EwsProxyRequestHandler(true);
                    }
                    else if (AuthenticatedWopiRequestPathHandler.IsAuthenticatedWopiRequest(httpContext.Request, AuthCommon.IsFrontEnd))
                    {
                        httpHandler = new AuthenticatedWopiProxyRequestHandler();
                    }
                    else
                    {
                        httpHandler = new OwaProxyRequestHandler();
                    }
                }
                else if (HttpProxyGlobals.ProtocolType == 13)
                {
                    httpHandler = new PushNotificationsProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 16)
                {
                    httpHandler = new OutlookServiceProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 17)
                {
                    httpHandler = new SnackyServiceProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 18)
                {
                    httpHandler = new MicroServiceProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 15)
                {
                    httpHandler = new E4eProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 20)
                {
                    httpHandler = new O365SuiteServiceProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 21)
                {
                    httpHandler = new MailboxDeliveryProxyRequestHandler();
                }
                else if (HttpProxyGlobals.ProtocolType == 22)
                {
                    httpHandler = new ComplianceServiceProxyRequestHandler();
                }
                else
                {
                    if (HttpProxyGlobals.ProtocolType != 24)
                    {
                        throw new InvalidOperationException("Unknown protocol type " + HttpProxyGlobals.ProtocolType);
                    }
                    httpHandler = new LogExportProxyHandler();
                }
                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);
        }
Example #30
0
        // Token: 0x060005F2 RID: 1522 RVA: 0x00021190 File Offset: 0x0001F390
        private static void FinalizeRequestLatencies(HttpContext httpContext, RequestDetailsLogger requestDetailsLogger, IActivityScope activityScope, LatencyTracker tracker, int traceContext)
        {
            if (tracker == null)
            {
                return;
            }
            if (requestDetailsLogger == null)
            {
                throw new ArgumentNullException("requestDetailsLogger");
            }
            if (activityScope == null)
            {
                throw new ArgumentNullException("activityScope");
            }
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            HttpContextBase wrapper = SharedHttpContextWrapper.GetWrapper(httpContext);
            long            num     = tracker.GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency);

            if (num >= 0L)
            {
                long num2 = 0L;
                long.TryParse(activityScope.GetProperty(6), out num2);
                long num3 = 0L;
                bool flag = requestDetailsLogger.TryGetLatency(37, ref num3);
                long num4 = requestDetailsLogger.GetLatency(34, 0L) + requestDetailsLogger.GetLatency(36, 0L) + num3 + requestDetailsLogger.GetLatency(39, 0L) + requestDetailsLogger.GetLatency(40, 0L);
                long num5 = num - num4;
                if (!NativeProxyHelper.WasProxiedByNativeProxyHandler(wrapper))
                {
                    PerfCounters.UpdateMovingAveragePerformanceCounter(PerfCounters.HttpProxyCountersInstance.MovingAverageCasLatency, num5);
                }
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, 43, num5);

                long num6 = num5 - num2;
                if (flag)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, 42, Math.Max(num6, 0L));

                    string property = activityScope.GetProperty(13);
                    if (PerfCounters.RoutingLatenciesEnabled && !string.IsNullOrEmpty(property))
                    {
                        string empty = string.Empty;
                        Utilities.TryExtractForestFqdnFromServerFqdn(property, ref empty);
                        PercentilePerfCounters.UpdateRoutingLatencyPerfCounter(empty, (double)num6);
                        PerfCounters.GetHttpProxyPerForestCountersInstance(empty).TotalProxyWithLatencyRequests.Increment();
                    }
                }
                long val = num6 - requestDetailsLogger.GetLatency(35, 0L) - requestDetailsLogger.GetLatency(38, 0L);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, 41, Math.Max(val, 0L));

                long currentLatency = tracker.GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency);
                long num7           = currentLatency - num;
                num = currentLatency;
                if (num7 > 5L)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestDetailsLogger, "TotalRequestTimeDelta", num7);
                }
            }
            RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, 16, num);
        }