Exemple #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);
        }
Exemple #2
0
        internal static string GetDiagnosticsInfo(HttpContext context)
        {
            RequestDetailsLogger current = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(context);

            Guid           guid          = Guid.Empty;
            IActivityScope activityScope = null;

            if (current != null)
            {
                guid          = current.ActivityId;
                activityScope = current.ActivityScope;
            }
            string text = string.Format("[ClientAccessServer={0},BackEndServer={1},RequestId={2},TimeStamp={3}] ", new object[]
            {
                Environment.MachineName,
                (activityScope == null) ? "UnKown" : activityScope.GetProperty(HttpProxyMetadata.TargetServer),
                guid,
                DateTime.UtcNow
            });
            string text2 = string.Empty;

            if (context != null)
            {
                text2 = WinRMInfo.GetFailureCategoryInfo(context);
            }
            if (!string.IsNullOrEmpty(text2))
            {
                text += string.Format("[FailureCategory={0}] ", text2);
            }
            ExTraceGlobals.VerboseTracer.TraceDebug <string>(0L, "[WinRMHelper::GetDiagnosticsInfo] diagnosticsInfo = {0}.", text);
            return(text);
        }
Exemple #3
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));
        }
Exemple #4
0
        // Token: 0x06000731 RID: 1841 RVA: 0x0002A46C File Offset: 0x0002866C
        protected override void OnPostAuthorizeInternal(HttpApplication httpApplication)
        {
            if (ExTraceGlobals.HttpModuleTracer.IsTraceEnabled(7))
            {
                ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[RpsHttpProxyModule::OnPostAuthorizeInternal] Enter");
            }
            RequestDetailsLogger current = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpApplication.Context);

            if (current != null)
            {
                Dictionary <Enum, string> authValues = ServiceCommonMetadataPublisher.GetAuthValues(new HttpContextWrapper(httpApplication.Context), false);
                if (authValues.ContainsKey(8))
                {
                    RequestMonitor.Instance.Log(current.ActivityId, 3, authValues[8]);
                }
                if (authValues.ContainsKey(5))
                {
                    RequestMonitor.Instance.Log(current.ActivityId, 4, authValues[5]);
                }
            }
            base.OnPostAuthorizeInternal(httpApplication);
            if (ExTraceGlobals.HttpModuleTracer.IsTraceEnabled(7))
            {
                ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[RpsHttpProxyModule::OnPostAuthorizeInternal] Exit");
            }
        }
Exemple #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);
     }
 }
        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);
        }
Exemple #7
0
        internal void LogElapsedTimeAsLatency(RequestDetailsLogger logger, LatencyTrackerKey trackerKey, HttpProxyMetadata protocolLogKey)
        {
            long currentLatency = this.GetCurrentLatency(trackerKey);

            if (currentLatency >= 0L)
            {
                logger.UpdateLatency(protocolLogKey, (double)currentLatency);
            }
        }
Exemple #8
0
 private void Application_End(object sender, EventArgs e)
 {
     Diagnostics.Logger.LogEvent(FrontEndHttpProxyEventLogConstants.Tuple_ApplicationShutdown, null, new object[]
     {
         HttpProxyGlobals.ProtocolType
     });
     RequestDetailsLogger.FlushQueuedFileWrites();
     SettingOverrideSync.Instance.Stop();
 }
 private void SetResponseHeaders(RequestDetailsLogger logger, HttpContext httpContext)
 {
     if (logger != null && !logger.IsDisposed && logger.ShouldSendDebugResponseHeaders())
     {
         ServiceCommonMetadataPublisher.PublishMetadata();
         if (httpContext != null)
         {
             logger.PushDebugInfoToResponseHeaders(httpContext);
         }
     }
 }
Exemple #10
0
 // Token: 0x060005F3 RID: 1523 RVA: 0x00021354 File Offset: 0x0001F554
 private static void InspectNativeProxyFatalError(HttpResponse httpResponse, RequestDetailsLogger requestLogger)
 {
     if (!HttpProxySettings.DiagnosticsEnabled.Value)
     {
         string text = httpResponse.Headers[NativeProxyHelper.NativeProxyStatusHeaders.ProxyErrorHResult];
         if (!string.IsNullOrEmpty(text))
         {
             string arg  = httpResponse.Headers[NativeProxyHelper.NativeProxyStatusHeaders.ProxyErrorLabel];
             string arg2 = httpResponse.Headers[NativeProxyHelper.NativeProxyStatusHeaders.ProxyErrorMessage];
             RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericError(requestLogger, "ProxyError", string.Format("[{0}] [{1}] {2}", text, arg, arg2));
         }
     }
 }
        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;
        }
        protected override void OnEndRequestInternal(HttpApplication httpApplication)
        {
            ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[RpsHttpProxyModule::OnEndRequestInternal] Enter");
            HttpContext          context = httpApplication.Context;
            RequestDetailsLogger current = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(context);

            if (current != null)
            {
                RequestMonitor.Instance.UnRegisterRequest(current.ActivityId);
            }
            base.OnEndRequestInternal(httpApplication);
            ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[RpsHttpProxyModule::OnEndRequestInternal] Exit");
        }
Exemple #13
0
        private void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContext     httpContext     = httpApplication.Context;

            Diagnostics.SendWatsonReportOnUnhandledException(delegate()
            {
                LatencyTracker latencyTracker = new LatencyTracker();
                latencyTracker.StartTracking(LatencyTrackerKey.ProxyModuleLatency, false);
                AspNetHelper.AddTimestampHeaderIfNecessary(httpContext.Request.Headers, "X-FrontEnd-Begin");
                if (Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
                {
                    Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug <string, Uri, int>((long)this.GetHashCode(), "[ProxyModule::OnBeginRequest]: Method {0}; Url {1}; Context {2};", httpContext.Request.HttpMethod, httpContext.Request.Url, httpContext.GetHashCode());
                }
                if (HealthCheckResponder.Instance.IsHealthCheckRequest(httpContext))
                {
                    HealthCheckResponder.Instance.CheckHealthStateAndRespond(httpContext);
                    return;
                }
                RequestDetailsLogger requestDetailsLogger = RequestDetailsLoggerBase <RequestDetailsLogger> .InitializeRequestLogger();
                requestDetailsLogger.LogCurrentTime("BeginRequest");
                httpContext.Items[Constants.TraceContextKey] = httpContext.GetHashCode();
                httpContext.Items[Constants.LatencyTrackerContextKeyName] = latencyTracker;
                requestDetailsLogger.ActivityScope.UpdateFromMessage(httpContext.Request);
                requestDetailsLogger.ActivityScope.SerializeTo(httpContext.Response);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SetCurrent(httpContext, requestDetailsLogger);
                httpContext.Items[typeof(ActivityScope)] = requestDetailsLogger.ActivityScope;
                httpContext.Items[Constants.RequestIdHttpContextKeyName] = requestDetailsLogger.ActivityScope.ActivityId;
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, HttpProxyMetadata.Protocol, HttpProxyGlobals.ProtocolType);
                requestDetailsLogger.SafeLogUriData(httpContext.Request.Url);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(requestDetailsLogger, ServiceCommonMetadata.HttpMethod, httpContext.Request.HttpMethod);
                string requestCorrelationId = AspNetHelper.GetRequestCorrelationId(httpContext);
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(requestDetailsLogger, "CorrelationID", requestCorrelationId);
                httpContext.Response.AppendToLog(Constants.CorrelationIdKeyForIISLogs + requestCorrelationId + ";");
                string cookieValueAndSetIfNull = ClientIdCookie.GetCookieValueAndSetIfNull(httpContext);
                httpContext.Response.AppendToLog(string.Format("&{0}={1}", "ClientId", cookieValueAndSetIfNull));
                UrlUtilities.SaveOriginalRequestHostSchemePortToContext(httpContext);
                try
                {
                    this.OnBeginRequestInternal(httpApplication);
                }
                catch (Exception ex)
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericError(requestDetailsLogger, "OnBeginRequestInternal", ex.ToString());
                    requestDetailsLogger.AsyncCommit(false);
                    throw;
                }
            }, new Diagnostics.LastChanceExceptionHandler(RequestDetailsLogger.LastChanceExceptionHandler));
        }
Exemple #14
0
        // Token: 0x060005FA RID: 1530 RVA: 0x00021B74 File Offset: 0x0001FD74
        private void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContext     httpContext     = httpApplication.Context;

            CheckpointTracker.GetOrCreate(httpContext.Items).Add(FrontEndHttpProxyCheckpoints.ProxyModulePreSendRequestHeaders);
            Diagnostics.SendWatsonReportOnUnhandledException(delegate()
            {
                if (httpContext != null && httpContext.Response != null && httpContext.Response.Headers != null)
                {
                    AspNetHelper.AddTimestampHeaderIfNecessary(httpContext.Response.Headers, "X-FrontEnd-End");
                    RequestDetailsLogger current = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext);
                    if (current != null && !current.IsDisposed)
                    {
                        this.SetResponseHeaders(current, httpContext);
                    }
                    if (Extensions.IsProbeRequest(Extensions.GetHttpRequestBase(httpContext.Request)) && !RequestFailureContext.IsSetInResponse(SharedHttpContextWrapper.GetWrapper(httpContext).Response))
                    {
                        RequestFailureContext requestFailureContext = null;
                        if (httpContext.Items.Contains(RequestFailureContext.HttpContextKeyName))
                        {
                            requestFailureContext = (RequestFailureContext)httpContext.Items[RequestFailureContext.HttpContextKeyName];
                        }
                        else if (httpContext.Response.StatusCode >= 400 && httpContext.Response.StatusCode < 600)
                        {
                            LiveIdAuthResult?liveIdAuthResult = null;
                            LiveIdAuthResult value;
                            if (httpContext.Items.Contains("LiveIdBasicAuthResult") && Enum.TryParse <LiveIdAuthResult>((string)httpContext.Items["LiveIdBasicAuthResult"], true, out value))
                            {
                                liveIdAuthResult = new LiveIdAuthResult?(value);
                            }
                            requestFailureContext = new RequestFailureContext(1, httpContext.Response.StatusCode, httpContext.Response.StatusDescription, string.Empty, null, null, liveIdAuthResult);
                        }
                        if (requestFailureContext != null)
                        {
                            requestFailureContext.UpdateResponse(SharedHttpContextWrapper.GetWrapper(httpContext).Response);
                        }
                    }
                    ProxyRequestHandler proxyRequestHandler = httpContext.CurrentHandler as ProxyRequestHandler;
                    if (proxyRequestHandler != null)
                    {
                        proxyRequestHandler.ResponseHeadersSent = true;
                    }
                }
            }, new Diagnostics.LastChanceExceptionHandler(RequestDetailsLogger.LastChanceExceptionHandler));
        }
Exemple #15
0
        // Token: 0x0600046E RID: 1134 RVA: 0x00018BF0 File Offset: 0x00016DF0
        internal static string GetDiagnosticsInfo(HttpContext context)
        {
            RequestDetailsLogger current = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(context);

            Guid           guid          = Guid.Empty;
            IActivityScope activityScope = null;

            if (current != null)
            {
                guid          = current.ActivityId;
                activityScope = current.ActivityScope;
            }
            string text = string.Format("[ClientAccessServer={0},BackEndServer={1},RequestId={2},TimeStamp={3}] ", new object[]
            {
                Environment.MachineName,
                (activityScope == null) ? "UnKnown" : activityScope.GetProperty(13),
                guid,
                DateTime.UtcNow
            });
            string text2 = string.Empty;

            if (context != null)
            {
                text2 = WinRMInfo.GetFailureCategoryInfo(context);
            }
            if (!string.IsNullOrEmpty(text2))
            {
                text += string.Format("[FailureCategory={0}] ", text2);
            }
            string text3 = context.Response.Headers["X-BasicAuthToOAuthConversionDiagnostics"];

            if (!string.IsNullOrWhiteSpace(text3))
            {
                text += string.Format("BasicAuthToOAuthConversionDiagnostics={0}", text3);
            }
            if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1))
            {
                ExTraceGlobals.VerboseTracer.TraceDebug <string>(0L, "[WinRMHelper::GetDiagnosticsInfo] diagnosticsInfo = {0}.", text);
            }
            return(text);
        }
        internal static string ParseIdentifier(Match match, string pattern, RequestDetailsLogger logger)
        {
            string result = null;

            try
            {
                result = match.Result(pattern);
            }
            catch (FormatException ex)
            {
                logger.AppendGenericError("Regex Exception", string.Format("Parsing {0} - {1}", match.ToString(), ex.ToString()));
            }
            catch (OverflowException ex2)
            {
                logger.AppendGenericError("Regex Exception", string.Format("Parsing {0} - {1}", match.ToString(), ex2.ToString()));
            }
            catch (ArgumentException ex3)
            {
                logger.AppendGenericError("Regex Exception", string.Format("Parsing {0} - {1}", match.ToString(), ex3.ToString()));
            }
            return(result);
        }
        internal static Match TryMatch(Regex regex, string data, RequestDetailsLogger logger)
        {
            Match result = null;

            try
            {
                result = regex.Match(data);
            }
            catch (FormatException ex)
            {
                logger.AppendGenericError("Regex Exception", string.Format("Matching regex {0} - {1}", regex.ToString(), ex.ToString()));
            }
            catch (OverflowException ex2)
            {
                logger.AppendGenericError("Regex Exception", string.Format("Matching regex {0} - {1}", regex.ToString(), ex2.ToString()));
            }
            catch (ArgumentException ex3)
            {
                logger.AppendGenericError("Regex Exception", string.Format("Matching regex {0} - {1}", regex.ToString(), ex3.ToString()));
            }
            return(result);
        }
Exemple #18
0
        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)
            {
                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))
            {
                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)
            {
                RequestDetailsLogger logger = this.RequestContext.Logger;
                RequestDetailsLoggerBase <RequestDetailsLogger> .SafeAppendGenericInfo(logger, "WinRMFaultMessage", winRMFaultMessage);
                WinRMInfo.SetWSManFailureCategory(context.Response.Headers, winRMFaultMessage);
            }))
            {
                WinRMHelper.SetDiagnosticsInfoWrittenFlag(context.Response.Headers);
                return(true);
            }
            return(false);
        }
Exemple #19
0
        // Token: 0x0600072F RID: 1839 RVA: 0x0002A2C0 File Offset: 0x000284C0
        protected override void OnBeginRequestInternal(HttpApplication httpApplication)
        {
            if (ExTraceGlobals.HttpModuleTracer.IsTraceEnabled(7))
            {
                ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[RpsHttpProxyModule::OnBeginRequestInternal] Enter");
            }
            HttpContext          context = httpApplication.Context;
            RequestDetailsLogger current = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(context);

            if (current != null)
            {
                RequestMonitor.Instance.RegisterRequest(current.ActivityId);
                string text = context.Request.Headers["Authorization"];
                byte[] bytes;
                byte[] array;
                string text2;
                if (!string.IsNullOrEmpty(text) && LiveIdBasicAuthModule.ParseCredentials(context, text, false, ref bytes, ref array, ref text2))
                {
                    string      text3 = Encoding.UTF8.GetString(bytes).Trim();
                    SmtpAddress smtpAddress;
                    smtpAddress..ctor(text3);
                    RequestMonitor.Instance.Log(current.ActivityId, 3, text3);
                    RequestMonitor.Instance.Log(current.ActivityId, 4, smtpAddress.Domain);
                    context.Items[Constants.WLIDMemberName] = text3;
                    if (ExTraceGlobals.HttpModuleTracer.IsTraceEnabled(1))
                    {
                        ExTraceGlobals.HttpModuleTracer.TraceDebug <string>((long)this.GetHashCode(), "[RpsHttpProxyModule::OnBeginRequestInternal] LiveIdMember={0}", text3);
                    }
                }
            }
            base.OnBeginRequestInternal(httpApplication);
            if (ExTraceGlobals.HttpModuleTracer.IsTraceEnabled(7))
            {
                ExTraceGlobals.HttpModuleTracer.TraceFunction((long)this.GetHashCode(), "[RpsHttpProxyModule::OnBeginRequestInternal] Exit");
            }
        }
        // Token: 0x060003E3 RID: 995 RVA: 0x00016A28 File Offset: 0x00014C28
        internal static IRecipientSession GetRecipientSessionFromPartition(LatencyTracker latencyTracker, string partitionId, RequestDetailsLogger logger)
        {
            if (latencyTracker == null)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            if (string.IsNullOrEmpty(partitionId))
            {
                throw new ArgumentNullException("partitionId");
            }
            ADSessionSettings adsessionSettings = null;
            PartitionId       partitionIdObject = null;

            if ((Utilities.IsPartnerHostedOnly || GlobalConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).MultiTenancy.Enabled) && PartitionId.TryParse(partitionId, ref partitionIdObject))
            {
                try
                {
                    adsessionSettings = DirectoryHelper.CreateADSessionSettingsWithDiagnostics(() => ADSessionSettings.FromAllTenantsPartitionId(partitionIdObject), logger, latencyTracker, true);
                }
                catch (CannotResolvePartitionException ex)
                {
                    if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(2))
                    {
                        ExTraceGlobals.VerboseTracer.TraceWarning <string, CannotResolvePartitionException>(0L, "[DirectoryHelper::GetRecipientSessionFromPartition] Caught CannotResolvePartitionException when resolving partition by partition ID {0}. Exception details: {1}.", partitionId, ex);
                    }
                }
            }
            if (adsessionSettings == null)
            {
                adsessionSettings = ADSessionSettings.FromRootOrgScopeSet();
            }
            return(DirectoryHelper.CreateSession(adsessionSettings));
        }
Exemple #21
0
        private void OnEndRequest(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContext     httpContext     = httpApplication.Context;

            Diagnostics.SendWatsonReportOnUnhandledException(delegate()
            {
                LatencyTracker latencyTracker = LatencyTracker.FromHttpContext(httpContext);
                RequestDetailsLogger current  = RequestDetailsLoggerBase <RequestDetailsLogger> .GetCurrent(httpContext);
                int traceContext = httpContext.GetTraceContext();
                if (HttpProxyGlobals.ProtocolType != ProtocolType.Mapi)
                {
                    OwaProxyRequestHandler.TryAddUnAuthenticatedPLTRequestPostDataToUriQueryOfIISLog(httpContext);
                }
                if (httpContext.Response != null && current != null)
                {
                    httpContext.Response.AppendToLog(Constants.RequestIdKeyForIISLogs + current.ActivityId.ToString() + ";");
                }
                if (HealthCheckResponder.Instance.IsHealthCheckRequest(httpContext))
                {
                    return;
                }
                if (httpContext.Response.StatusCode == 404 && httpContext.Response.SubStatusCode == 13)
                {
                    httpContext.Response.StatusCode = 507;
                }
                if (Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
                {
                    Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug((long)this.GetHashCode(), "[ProxyModule::OnEndRequest]: Method {0}; Url {1}; Username {2}; Context {3};", new object[]
                    {
                        httpContext.Request.HttpMethod,
                        httpContext.Request.Url,
                        (httpContext.User == null) ? string.Empty : httpContext.User.Identity.GetSafeName(true),
                        traceContext
                    });
                }
                if (latencyTracker != null)
                {
                    long currentLatency = latencyTracker.GetCurrentLatency(LatencyTrackerKey.HandlerToModuleSwitchingLatency);
                    if (currentLatency >= 0L)
                    {
                        RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(current, HttpProxyMetadata.HandlerToModuleSwitchingLatency, currentLatency);
                    }
                }
                ProxyRequestHandler proxyRequestHandler = httpContext.CurrentHandler as ProxyRequestHandler;
                if (proxyRequestHandler != null && !proxyRequestHandler.IsDisposed)
                {
                    current.AppendGenericInfo("DisposeProxyRequestHandler", "ProxyModule::OnEndRequest");
                    proxyRequestHandler.Dispose();
                }
                string value = httpContext.Items["AnonymousRequestFilterModule"] as string;
                if (!string.IsNullOrEmpty(value))
                {
                    current.AppendGenericInfo("AnonymousRequestFilterModule", value);
                }
                try
                {
                    this.OnEndRequestInternal(httpApplication);
                }
                finally
                {
                    if (current != null && !current.IsDisposed)
                    {
                        IActivityScope activityScope = current.ActivityScope;
                        if (activityScope != null)
                        {
                            if (!string.IsNullOrEmpty(activityScope.TenantId))
                            {
                                httpContext.Items["AuthenticatedUserOrganization"] = activityScope.TenantId;
                            }
                            ProxyModule.FinalizeRequestLatencies(httpContext, current, activityScope, latencyTracker, traceContext);
                        }
                        current.LogCurrentTime("EndRequest");
                        current.AsyncCommit(false);
                    }
                    if (Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.IsTraceEnabled(TraceType.DebugTrace))
                    {
                        Microsoft.Exchange.Diagnostics.Components.HttpProxy.ExTraceGlobals.VerboseTracer.TraceDebug(0L, "[ProxyModule::OnEndRequest]: Method {0}; Url {1}; OnEndRequestLatency {2}; Context {3};", new object[]
                        {
                            httpContext.Request.HttpMethod,
                            httpContext.Request.Url,
                            (latencyTracker != null) ? latencyTracker.GetCurrentLatency(LatencyTrackerKey.ProxyModuleLatency).ToString() : "Unknown",
                            traceContext
                        });
                    }
                }
            }, new Diagnostics.LastChanceExceptionHandler(RequestDetailsLogger.LastChanceExceptionHandler));
        }
Exemple #22
0
        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(TraceType.DebugTrace))
            {
                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(TraceType.DebugTrace))
                {
                    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), "f:\\15.00.1497\\sources\\dev\\cafe\\src\\HttpProxy\\DownLevelServerManager\\DownLevelServerManager.cs", "GetClientAccessServiceFromList", 767);
                    if (serviceType != null)
                    {
                        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);
                    }
                    ExTraceGlobals.VerboseTracer.TraceError <string>((long)this.GetHashCode(), "[DownLevelServerManager::GetClientAccessServiceFromList]: Back end server {0} cannot be found by ServiceDiscovery.", currentServer.BackEndServer.Fqdn);
                }
                else
                {
                    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);

            ExTraceGlobals.VerboseTracer.TraceError <string>((long)this.GetHashCode(), "[DownLevelServerManager::GetClientAccessServiceFromList]: {0}", text2);
            throw new NoAvailableDownLevelBackEndException(text2);
        }
Exemple #23
0
 // Token: 0x060002C3 RID: 707 RVA: 0x0000DDE8 File Offset: 0x0000BFE8
 internal static void SafeSet(this RequestDetailsLogger logger, Enum key, object value)
 {
     RequestDetailsLoggerBase <RequestDetailsLogger> .SafeSetLogger(logger, key, value);
 }
Exemple #24
0
        public BackEndServer GetDownLevelClientAccessServer <ServiceType>(AnchorMailbox anchorMailbox, BackEndServer mailboxServer, ClientAccessType clientAccessType, RequestDetailsLogger logger, bool calculateRedirectUrl, out Uri redirectUrl) where ServiceType : HttpService
        {
            if (anchorMailbox == null)
            {
                throw new ArgumentNullException("anchorMailbox");
            }
            if (mailboxServer == null)
            {
                throw new ArgumentNullException("mailboxServer");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            if (!DownLevelServerManager.IsApplicable)
            {
                throw new HttpProxyException(HttpStatusCode.NotFound, HttpProxySubErrorCode.EndpointNotFound, string.Format("{0} does not support down level server proxy.", HttpProxyGlobals.ProtocolType));
            }
            redirectUrl = null;
            if (mailboxServer.Version < Server.E14MinVersion)
            {
                ExTraceGlobals.VerboseTracer.TraceDebug <int, int, string>((long)this.GetHashCode(), "[DownLevelServerManager::GetDownLevelClientAccessServer]: Found mailbox server version {0}, which was pre-E14 minimum version {1}, so returning mailbox server FQDN {2}", mailboxServer.Version, Server.E14MinVersion, mailboxServer.Fqdn);
                return(mailboxServer);
            }
            ServiceTopology currentLegacyServiceTopology = ServiceTopology.GetCurrentLegacyServiceTopology("f:\\15.00.1497\\sources\\dev\\cafe\\src\\HttpProxy\\DownLevelServerManager\\DownLevelServerManager.cs", "GetDownLevelClientAccessServer", 393);
            Site            site   = currentLegacyServiceTopology.GetSite(mailboxServer.Fqdn, "f:\\15.00.1497\\sources\\dev\\cafe\\src\\HttpProxy\\DownLevelServerManager\\DownLevelServerManager.cs", "GetDownLevelClientAccessServer", 394);
            ServiceType     result = this.GetClientAccessServiceInSite <ServiceType>(currentLegacyServiceTopology, anchorMailbox, site, clientAccessType, (ServiceType service) => service.ServerVersionNumber >= Server.E14MinVersion && service.ServerVersionNumber < Server.E15MinVersion, logger);

            if (calculateRedirectUrl && !Utilities.IsPartnerHostedOnly && !VariantConfiguration.InvariantNoFlightingSnapshot.Cafe.NoCrossSiteRedirect.Enabled && result != null && !string.IsNullOrEmpty(result.ServerFullyQualifiedDomainName))
            {
                Site member = HttpProxyGlobals.LocalSite.Member;
                if (!member.DistinguishedName.Equals(result.Site.DistinguishedName))
                {
                    HttpService httpService = currentLegacyServiceTopology.FindAny <ServiceType>(ClientAccessType.External, (ServiceType externalService) => externalService != null && externalService.ServerFullyQualifiedDomainName.Equals(result.ServerFullyQualifiedDomainName, StringComparison.OrdinalIgnoreCase), "f:\\15.00.1497\\sources\\dev\\cafe\\src\\HttpProxy\\DownLevelServerManager\\DownLevelServerManager.cs", "GetDownLevelClientAccessServer", 419);
                    if (httpService != null)
                    {
                        redirectUrl = httpService.Url;
                    }
                }
            }
            return(new BackEndServer(result.ServerFullyQualifiedDomainName, result.ServerVersionNumber));
        }
Exemple #25
0
        private ServiceType GetClientAccessServiceInSite <ServiceType>(ServiceTopology topology, AnchorMailbox anchorMailbox, Site targetSite, ClientAccessType clientAccessType, Predicate <ServiceType> otherFilter, RequestDetailsLogger logger) where ServiceType : HttpService
        {
            Dictionary <string, List <DownLevelServerStatusEntry> > downLevelServerMap = this.GetDownLevelServerMap();
            List <DownLevelServerStatusEntry> serverList = null;

            if (!downLevelServerMap.TryGetValue(targetSite.DistinguishedName, out serverList))
            {
                string text = string.Format("Unable to find site {0} in the down level server map.", targetSite.DistinguishedName);
                ExTraceGlobals.VerboseTracer.TraceError <string>((long)this.GetHashCode(), "[DownLevelServerManager::GetClientAccessServiceInSite]: {0}", text);
                ThreadPool.QueueUserWorkItem(delegate(object o)
                {
                    this.RefreshServerMap(true);
                });
                throw new NoAvailableDownLevelBackEndException(text);
            }
            return(this.GetClientAccessServiceFromList <ServiceType>(serverList, topology, anchorMailbox, targetSite, clientAccessType, otherFilter, logger, DownLevelServerManager.DownlevelExchangeServerVersion.Exchange2010));
        }
Exemple #26
0
        public BackEndServer GetDownLevelClientAccessServerWithPreferredServer <ServiceType>(AnchorMailbox anchorMailbox, string preferredCasServerFqdn, ClientAccessType clientAccessType, RequestDetailsLogger logger, int destinationVersion) where ServiceType : HttpService
        {
            Predicate <ServiceType> predicate  = null;
            Predicate <ServiceType> predicate2 = null;

            if (anchorMailbox == null)
            {
                throw new ArgumentNullException("anchorMailbox");
            }
            if (string.IsNullOrEmpty(preferredCasServerFqdn))
            {
                throw new ArgumentException("preferredCasServerFqdn cannot be empty!");
            }
            ServiceTopology currentLegacyServiceTopology = ServiceTopology.GetCurrentLegacyServiceTopology("f:\\15.00.1497\\sources\\dev\\cafe\\src\\HttpProxy\\DownLevelServerManager\\DownLevelServerManager.cs", "GetDownLevelClientAccessServerWithPreferredServer", 253);
            Site            site = currentLegacyServiceTopology.GetSite(preferredCasServerFqdn, "f:\\15.00.1497\\sources\\dev\\cafe\\src\\HttpProxy\\DownLevelServerManager\\DownLevelServerManager.cs", "GetDownLevelClientAccessServerWithPreferredServer", 254);
            Dictionary <string, List <DownLevelServerStatusEntry> > downLevelServerMap = this.GetDownLevelServerMap();
            List <DownLevelServerStatusEntry> list = null;

            if (!downLevelServerMap.TryGetValue(site.DistinguishedName, out list))
            {
                string text = string.Format("Unable to find site {0} in the down level server map.", site.DistinguishedName);
                ExTraceGlobals.VerboseTracer.TraceError <string>((long)this.GetHashCode(), "[DownLevelServerManager::GetDownLevelClientAccessServerWithPreferredServer]: {0}", text);
                ThreadPool.QueueUserWorkItem(delegate(object o)
                {
                    this.RefreshServerMap(true);
                });
                throw new NoAvailableDownLevelBackEndException(text);
            }
            DownLevelServerStatusEntry downLevelServerStatusEntry = list.Find((DownLevelServerStatusEntry backend) => preferredCasServerFqdn.Equals(backend.BackEndServer.Fqdn, StringComparison.OrdinalIgnoreCase));

            if (downLevelServerStatusEntry == null)
            {
                string text2 = string.Format("Unable to find preferred server {0} in the back end server map.", preferredCasServerFqdn);
                ExTraceGlobals.VerboseTracer.TraceError <string>((long)this.GetHashCode(), "[DownLevelServerManager::GetDownLevelClientAccessServerWithPreferredServer]: {0}", text2);
                throw new NoAvailableDownLevelBackEndException(text2);
            }
            if (downLevelServerStatusEntry.IsHealthy)
            {
                ExTraceGlobals.VerboseTracer.TraceDebug <DownLevelServerStatusEntry>((long)this.GetHashCode(), "[DownLevelServerManager::GetDownLevelClientAccessServerWithPreferredServer]: The preferred server {0} is healthy.", downLevelServerStatusEntry);
                return(downLevelServerStatusEntry.BackEndServer);
            }
            ServiceType serviceType = default(ServiceType);

            if (destinationVersion < Server.E14MinVersion)
            {
                try
                {
                    List <DownLevelServerStatusEntry> serverList = list;
                    ServiceTopology topology   = currentLegacyServiceTopology;
                    Site            targetSite = site;
                    if (predicate == null)
                    {
                        predicate = ((ServiceType service) => service.ServerVersionNumber >= Server.E2007MinVersion && service.ServerVersionNumber < Server.E14MinVersion);
                    }
                    serviceType = this.GetClientAccessServiceFromList <ServiceType>(serverList, topology, anchorMailbox, targetSite, clientAccessType, predicate, logger, DownLevelServerManager.DownlevelExchangeServerVersion.Exchange2007);
                }
                catch (NoAvailableDownLevelBackEndException)
                {
                    ExTraceGlobals.VerboseTracer.TraceError((long)this.GetHashCode(), "[DownLevelServerManager::GetDownLevelClientAccessServerWithPreferredServer]: No E12 CAS could be found for E12 destination. Looking for E14 CAS.");
                }
            }
            if (serviceType == null)
            {
                List <DownLevelServerStatusEntry> serverList2 = list;
                ServiceTopology topology2   = currentLegacyServiceTopology;
                Site            targetSite2 = site;
                if (predicate2 == null)
                {
                    predicate2 = ((ServiceType service) => service.ServerVersionNumber >= Server.E14MinVersion && service.ServerVersionNumber < Server.E15MinVersion);
                }
                serviceType = this.GetClientAccessServiceFromList <ServiceType>(serverList2, topology2, anchorMailbox, targetSite2, clientAccessType, predicate2, logger, DownLevelServerManager.DownlevelExchangeServerVersion.Exchange2010);
            }
            return(new BackEndServer(serviceType.ServerFullyQualifiedDomainName, serviceType.ServerVersionNumber));
        }
        // Token: 0x060003E4 RID: 996 RVA: 0x00016AEC File Offset: 0x00014CEC
        internal static IRecipientSession GetRecipientSessionFromSmtpOrLiveId(string smtpOrLiveId, RequestDetailsLogger logger, LatencyTracker latencyTracker, bool ignoreCannotResolveTenantNameException = false)
        {
            if (string.IsNullOrEmpty(smtpOrLiveId))
            {
                throw new ArgumentNullException("smtpOrLiveId");
            }
            ADSessionSettings adsessionSettings = null;

            if ((Utilities.IsPartnerHostedOnly || GlobalConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).WindowsLiveID.Enabled) && SmtpAddress.IsValidSmtpAddress(smtpOrLiveId))
            {
                adsessionSettings = DirectoryHelper.CreateADSessionSettingsWithDiagnostics(() => ADSessionSettings.FromTenantRecipientSmtpAddress(new SmtpAddress(smtpOrLiveId), 2), logger, latencyTracker, ignoreCannotResolveTenantNameException);
            }
            if (adsessionSettings == null)
            {
                adsessionSettings = ADSessionSettings.FromRootOrgScopeSet();
            }
            return(DirectoryHelper.CreateSession(adsessionSettings));
        }
        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);
            }
        }
        // Token: 0x060003E5 RID: 997 RVA: 0x00016B70 File Offset: 0x00014D70
        internal static IRecipientSession GetBusinessTenantRecipientSessionFromDomain(string domain, RequestDetailsLogger logger, LatencyTracker latencyTracker)
        {
            if (string.IsNullOrEmpty(domain))
            {
                throw new ArgumentNullException("domain");
            }
            ADSessionSettings sessionSettings;

            if (Utilities.IsPartnerHostedOnly || GlobalConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).WindowsLiveID.Enabled)
            {
                sessionSettings = DirectoryHelper.CreateADSessionSettingsWithDiagnostics(() => ADSessionSettings.FromBusinessTenantAcceptedDomain(domain), logger, latencyTracker, false);
            }
            else
            {
                sessionSettings = ADSessionSettings.FromRootOrgScopeSet();
            }
            return(DirectoryHelper.CreateSession(sessionSettings));
        }
        // Token: 0x060003E6 RID: 998 RVA: 0x00016BE8 File Offset: 0x00014DE8
        internal static IRecipientSession GetRecipientSessionFromExternalDirectoryOrganizationId(LatencyTracker latencyTracker, Guid externalOrgId, RequestDetailsLogger logger)
        {
            if (latencyTracker == null)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            if (externalOrgId == Guid.Empty)
            {
                throw new ArgumentNullException("latencyTracker");
            }
            ADSessionSettings sessionSettings = null;

            if (Utilities.IsPartnerHostedOnly || GlobalConfiguration.GetSnapshot(MachineSettingsContext.Local, null, null).WindowsLiveID.Enabled)
            {
                try
                {
                    sessionSettings = DirectoryHelper.CreateADSessionSettingsWithDiagnostics(() => ADSessionSettings.FromExternalDirectoryOrganizationId(externalOrgId), logger, latencyTracker, false);
                    goto IL_8F;
                }
                catch (CannotResolveExternalDirectoryOrganizationIdException ex)
                {
                    throw new HttpProxyException(HttpStatusCode.NotFound, 3009, ex.Message, ex);
                }
            }
            sessionSettings = ADSessionSettings.FromRootOrgScopeSet();
IL_8F:
            return(DirectoryHelper.CreateSession(sessionSettings));
        }