From 8311e6b5165af48f0cb0cb87bd74b41ab280efb6 Mon Sep 17 00:00:00 2001 From: justcoding121 Date: Tue, 20 Nov 2018 12:00:14 -0500 Subject: [PATCH 1/5] #522 fix Uwp startup --- src/Titanium.Web.Proxy/Helpers/RunTime.cs | 41 +++++++++++++++++++++++ src/Titanium.Web.Proxy/ProxyServer.cs | 6 ++-- src/Titanium.Web.Proxy/RequestHandler.cs | 1 - 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/src/Titanium.Web.Proxy/Helpers/RunTime.cs b/src/Titanium.Web.Proxy/Helpers/RunTime.cs index d34dd45f6..43d14a88a 100644 --- a/src/Titanium.Web.Proxy/Helpers/RunTime.cs +++ b/src/Titanium.Web.Proxy/Helpers/RunTime.cs @@ -1,4 +1,6 @@ using System; +using System.Runtime.InteropServices; +using System.Text; #if NETSTANDARD2_0 using System.Runtime.InteropServices; #endif @@ -53,6 +55,7 @@ public static class RunTime #else public static bool IsWindows => !IsLinux && !IsMac; #endif + public static bool IsUwpOnWindows => IsWindows && UwpHelper.IsRunningAsUwp(); #if NETSTANDARD2_0 public static bool IsMac => isRunningOnMac; @@ -60,5 +63,43 @@ public static class RunTime public static bool IsMac => isRunningOnMonoMac.Value; #endif + //https://github.com/qmatteoq/DesktopBridgeHelpers/blob/master/DesktopBridge.Helpers/Helpers.cs + private class UwpHelper + { + const long APPMODEL_ERROR_NO_PACKAGE = 15700L; + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + static extern int GetCurrentPackageFullName(ref int packageFullNameLength, StringBuilder packageFullName); + + internal static bool IsRunningAsUwp() + { + if (IsWindows7OrLower) + { + return false; + } + else + { + int length = 0; + var sb = new StringBuilder(0); + int result = GetCurrentPackageFullName(ref length, sb); + + sb = new StringBuilder(length); + result = GetCurrentPackageFullName(ref length, sb); + + return result != APPMODEL_ERROR_NO_PACKAGE; + } + } + + private static bool IsWindows7OrLower + { + get + { + int versionMajor = Environment.OSVersion.Version.Major; + int versionMinor = Environment.OSVersion.Version.Minor; + double version = versionMajor + (double)versionMinor / 10; + return version <= 6.1; + } + } + } } } diff --git a/src/Titanium.Web.Proxy/ProxyServer.cs b/src/Titanium.Web.Proxy/ProxyServer.cs index 1cefb41e6..510194c1f 100644 --- a/src/Titanium.Web.Proxy/ProxyServer.cs +++ b/src/Titanium.Web.Proxy/ProxyServer.cs @@ -102,7 +102,7 @@ public ProxyServer(string rootCertificateName, string rootCertificateIssuerName, ProxyEndPoints = new List(); tcpConnectionFactory = new TcpConnectionFactory(this); - if (!RunTime.IsRunningOnMono && RunTime.IsWindows) + if (!RunTime.IsRunningOnMono && RunTime.IsWindows && !RunTime.IsUwpOnWindows) { systemProxySettingsManager = new SystemProxyManager(); } @@ -542,7 +542,7 @@ public void Start() // clear any system proxy settings which is pointing to our own endpoint (causing a cycle) // due to ungracious proxy shutdown before or something else - if (systemProxySettingsManager != null && RunTime.IsWindows) + if (systemProxySettingsManager != null && RunTime.IsWindows && !RunTime.IsUwpOnWindows) { var proxyInfo = systemProxySettingsManager.GetProxyInfoFromRegistry(); if (proxyInfo.Proxies != null) @@ -593,7 +593,7 @@ public void Stop() throw new Exception("Proxy is not running."); } - if (!RunTime.IsRunningOnMono && RunTime.IsWindows) + if (!RunTime.IsRunningOnMono && RunTime.IsWindows && !RunTime.IsUwpOnWindows) { bool setAsSystemProxy = ProxyEndPoints.OfType() .Any(x => x.IsSystemHttpProxy || x.IsSystemHttpsProxy); diff --git a/src/Titanium.Web.Proxy/RequestHandler.cs b/src/Titanium.Web.Proxy/RequestHandler.cs index 97824f04c..13c35a10b 100644 --- a/src/Titanium.Web.Proxy/RequestHandler.cs +++ b/src/Titanium.Web.Proxy/RequestHandler.cs @@ -25,7 +25,6 @@ namespace Titanium.Web.Proxy /// public partial class ProxyServer { - private bool isWindowsAuthenticationEnabledAndSupported => EnableWinAuth && RunTime.IsWindows && !RunTime.IsRunningOnMono; From a7cab15ff5948d8ba4412677879a1bfc7ed40032 Mon Sep 17 00:00:00 2001 From: justcoding121 Date: Tue, 20 Nov 2018 12:43:01 -0500 Subject: [PATCH 2/5] #519 handle change in hostname on ReRequest --- .../ProxyTestController.cs | 6 +- .../MainWindow.xaml.cs | 26 ++-- .../EventArguments/SessionEventArgs.cs | 82 ++++++------- .../EventArguments/SessionEventArgsBase.cs | 26 ++-- .../EventArguments/TunnelConnectEventArgs.cs | 2 +- .../ExplicitClientHandler.cs | 16 +-- src/Titanium.Web.Proxy/Http/HttpWebClient.cs | 34 +++--- src/Titanium.Web.Proxy/Network/ProxyClient.cs | 2 +- .../Network/Tcp/TcpConnectionFactory.cs | 14 +-- .../ProxyAuthorizationHandler.cs | 16 +-- src/Titanium.Web.Proxy/ProxyServer.cs | 2 +- src/Titanium.Web.Proxy/RequestHandler.cs | 111 ++++++++++++------ src/Titanium.Web.Proxy/ResponseHandler.cs | 15 +-- src/Titanium.Web.Proxy/WebSocketHandler.cs | 2 +- src/Titanium.Web.Proxy/WinAuthHandler.cs | 16 +-- .../InterceptionTests.cs | 4 +- 16 files changed, 207 insertions(+), 167 deletions(-) diff --git a/examples/Titanium.Web.Proxy.Examples.Basic/ProxyTestController.cs b/examples/Titanium.Web.Proxy.Examples.Basic/ProxyTestController.cs index 943ea3cc7..309aaaa04 100644 --- a/examples/Titanium.Web.Proxy.Examples.Basic/ProxyTestController.cs +++ b/examples/Titanium.Web.Proxy.Examples.Basic/ProxyTestController.cs @@ -118,7 +118,7 @@ public void Stop() private async Task OnBeforeTunnelConnectRequest(object sender, TunnelConnectSessionEventArgs e) { - string hostname = e.WebSession.Request.RequestUri.Host; + string hostname = e.HttpClient.Request.RequestUri.Host; await WriteToConsole("Tunnel to: " + hostname); if (hostname.Contains("dropbox.com")) @@ -139,7 +139,7 @@ private Task OnBeforeTunnelConnectResponse(object sender, TunnelConnectSessionEv private async Task OnRequest(object sender, SessionEventArgs e) { await WriteToConsole("Active Client Connections:" + ((ProxyServer)sender).ClientConnectionCount); - await WriteToConsole(e.WebSession.Request.Url); + await WriteToConsole(e.HttpClient.Request.Url); // store it in the UserData property // It can be a simple integer, Guid, or any type @@ -191,7 +191,7 @@ private async Task OnResponse(object sender, SessionEventArgs e) { await WriteToConsole("Active Server Connections:" + ((ProxyServer)sender).ServerConnectionCount); - string ext = System.IO.Path.GetExtension(e.WebSession.Request.RequestUri.AbsolutePath); + string ext = System.IO.Path.GetExtension(e.HttpClient.Request.RequestUri.AbsolutePath); //access user data set in request to do something with it //var userData = e.WebSession.UserData as CustomUserData; diff --git a/examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml.cs b/examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml.cs index 803ee3169..9cfe1f611 100644 --- a/examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml.cs +++ b/examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml.cs @@ -122,7 +122,7 @@ public int ServerConnectionCount private async Task ProxyServer_BeforeTunnelConnectRequest(object sender, TunnelConnectSessionEventArgs e) { - string hostname = e.WebSession.Request.RequestUri.Host; + string hostname = e.HttpClient.Request.RequestUri.Host; if (hostname.EndsWith("webex.com")) { e.DecryptSsl = false; @@ -135,7 +135,7 @@ private async Task ProxyServer_BeforeTunnelConnectResponse(object sender, Tunnel { await Dispatcher.InvokeAsync(() => { - if (sessionDictionary.TryGetValue(e.WebSession, out var item)) + if (sessionDictionary.TryGetValue(e.HttpClient, out var item)) { item.Update(); } @@ -147,9 +147,9 @@ private async Task ProxyServer_BeforeRequest(object sender, SessionEventArgs e) SessionListItem item = null; await Dispatcher.InvokeAsync(() => { item = AddSession(e); }); - if (e.WebSession.Request.HasBody) + if (e.HttpClient.Request.HasBody) { - e.WebSession.Request.KeepBody = true; + e.HttpClient.Request.KeepBody = true; await e.GetRequestBody(); } } @@ -159,7 +159,7 @@ private async Task ProxyServer_BeforeResponse(object sender, SessionEventArgs e) SessionListItem item = null; await Dispatcher.InvokeAsync(() => { - if (sessionDictionary.TryGetValue(e.WebSession, out item)) + if (sessionDictionary.TryGetValue(e.HttpClient, out item)) { item.Update(); } @@ -167,9 +167,9 @@ await Dispatcher.InvokeAsync(() => if (item != null) { - if (e.WebSession.Response.HasBody) + if (e.HttpClient.Response.HasBody) { - e.WebSession.Response.KeepBody = true; + e.HttpClient.Response.KeepBody = true; await e.GetResponseBody(); await Dispatcher.InvokeAsync(() => { item.Update(); }); @@ -181,7 +181,7 @@ private async Task ProxyServer_AfterResponse(object sender, SessionEventArgs e) { await Dispatcher.InvokeAsync(() => { - if (sessionDictionary.TryGetValue(e.WebSession, out var item)) + if (sessionDictionary.TryGetValue(e.HttpClient, out var item)) { item.Exception = e.Exception; } @@ -192,7 +192,7 @@ private SessionListItem AddSession(SessionEventArgsBase e) { var item = CreateSessionListItem(e); Sessions.Add(item); - sessionDictionary.Add(e.WebSession, item); + sessionDictionary.Add(e.HttpClient, item); return item; } @@ -203,16 +203,16 @@ private SessionListItem CreateSessionListItem(SessionEventArgsBase e) var item = new SessionListItem { Number = lastSessionNumber, - WebSession = e.WebSession, + WebSession = e.HttpClient, IsTunnelConnect = isTunnelConnect }; - if (isTunnelConnect || e.WebSession.Request.UpgradeToWebSocket) + if (isTunnelConnect || e.HttpClient.Request.UpgradeToWebSocket) { e.DataReceived += (sender, args) => { var session = (SessionEventArgs)sender; - if (sessionDictionary.TryGetValue(session.WebSession, out var li)) + if (sessionDictionary.TryGetValue(session.HttpClient, out var li)) { li.ReceivedDataCount += args.Count; } @@ -221,7 +221,7 @@ private SessionListItem CreateSessionListItem(SessionEventArgsBase e) e.DataSent += (sender, args) => { var session = (SessionEventArgs)sender; - if (sessionDictionary.TryGetValue(session.WebSession, out var li)) + if (sessionDictionary.TryGetValue(session.HttpClient, out var li)) { li.SentDataCount += args.Count; } diff --git a/src/Titanium.Web.Proxy/EventArguments/SessionEventArgs.cs b/src/Titanium.Web.Proxy/EventArguments/SessionEventArgs.cs index 0e0068f27..f4d38dec1 100644 --- a/src/Titanium.Web.Proxy/EventArguments/SessionEventArgs.cs +++ b/src/Titanium.Web.Proxy/EventArguments/SessionEventArgs.cs @@ -53,7 +53,7 @@ public bool ReRequest get => reRequest; set { - if (WebSession.Response.StatusCode == 0) + if (HttpClient.Response.StatusCode == 0) { throw new Exception("Response status code is empty. Cannot request again a request " + "which was never send to server."); } @@ -69,12 +69,12 @@ public bool ReRequest private ICustomStreamReader getStreamReader(bool isRequest) { - return isRequest ? ProxyClient.ClientStream : WebSession.ServerConnection.Stream; + return isRequest ? ProxyClient.ClientStream : HttpClient.Connection.Stream; } private HttpWriter getStreamWriter(bool isRequest) { - return isRequest ? (HttpWriter)ProxyClient.ClientStreamWriter : WebSession.ServerConnection.StreamWriter; + return isRequest ? (HttpWriter)ProxyClient.ClientStreamWriter : HttpClient.Connection.StreamWriter; } /// @@ -82,9 +82,9 @@ private HttpWriter getStreamWriter(bool isRequest) /// private async Task readRequestBodyAsync(CancellationToken cancellationToken) { - WebSession.Request.EnsureBodyAvailable(false); + HttpClient.Request.EnsureBodyAvailable(false); - var request = WebSession.Request; + var request = HttpClient.Request; // If not already read (not cached yet) if (!request.IsBodyRead) @@ -106,7 +106,7 @@ internal async Task ClearResponse(CancellationToken cancellationToken) { // syphon out the response body from server await SyphonOutBodyAsync(false, cancellationToken); - WebSession.Response = new Response(); + HttpClient.Response = new Response(); } internal void OnMultipartRequestPartSent(string boundary, HeaderCollection headers) @@ -126,12 +126,12 @@ internal void OnMultipartRequestPartSent(string boundary, HeaderCollection heade /// private async Task readResponseBodyAsync(CancellationToken cancellationToken) { - if (!WebSession.Request.Locked) + if (!HttpClient.Request.Locked) { throw new Exception("You cannot read the response body before request is made to server."); } - var response = WebSession.Response; + var response = HttpClient.Response; if (!response.HasBody) { return; @@ -178,7 +178,7 @@ private async Task readBodyAsync(bool isRequest, CancellationToken cance /// internal async Task SyphonOutBodyAsync(bool isRequest, CancellationToken cancellationToken) { - var requestResponse = isRequest ? (RequestResponseBase)WebSession.Request : WebSession.Response; + var requestResponse = isRequest ? (RequestResponseBase)HttpClient.Request : HttpClient.Response; if (requestResponse.IsBodyRead || !requestResponse.OriginalHasBody) { return; @@ -197,7 +197,7 @@ internal async Task SyphonOutBodyAsync(bool isRequest, CancellationToken cancell /// internal async Task CopyRequestBodyAsync(HttpWriter writer, TransformationMode transformation, CancellationToken cancellationToken) { - var request = WebSession.Request; + var request = HttpClient.Request; long contentLength = request.ContentLength; @@ -243,7 +243,7 @@ private async Task copyBodyAsync(bool isRequest, bool useOriginalHeaderValues, H { var stream = getStreamReader(isRequest); - var requestResponse = isRequest ? (RequestResponseBase)WebSession.Request : WebSession.Response; + var requestResponse = isRequest ? (RequestResponseBase)HttpClient.Request : HttpClient.Response; bool isChunked = useOriginalHeaderValues? requestResponse.OriginalIsChunked : requestResponse.IsChunked; long contentLength = useOriginalHeaderValues ? requestResponse.OriginalContentLength : requestResponse.ContentLength; @@ -351,12 +351,12 @@ private async Task readUntilBoundaryAsync(ICustomStreamReader reader, long /// The body as bytes. public async Task GetRequestBody(CancellationToken cancellationToken = default) { - if (!WebSession.Request.IsBodyRead) + if (!HttpClient.Request.IsBodyRead) { await readRequestBodyAsync(cancellationToken); } - return WebSession.Request.Body; + return HttpClient.Request.Body; } /// @@ -366,12 +366,12 @@ public async Task GetRequestBody(CancellationToken cancellationToken = d /// The body as string. public async Task GetRequestBodyAsString(CancellationToken cancellationToken = default) { - if (!WebSession.Request.IsBodyRead) + if (!HttpClient.Request.IsBodyRead) { await readRequestBodyAsync(cancellationToken); } - return WebSession.Request.BodyString; + return HttpClient.Request.BodyString; } /// @@ -380,7 +380,7 @@ public async Task GetRequestBodyAsString(CancellationToken cancellationT /// The request body bytes. public void SetRequestBody(byte[] body) { - var request = WebSession.Request; + var request = HttpClient.Request; if (request.Locked) { throw new Exception("You cannot call this function after request is made to server."); @@ -395,12 +395,12 @@ public void SetRequestBody(byte[] body) /// The request body string to set. public void SetRequestBodyString(string body) { - if (WebSession.Request.Locked) + if (HttpClient.Request.Locked) { throw new Exception("You cannot call this function after request is made to server."); } - SetRequestBody(WebSession.Request.Encoding.GetBytes(body)); + SetRequestBody(HttpClient.Request.Encoding.GetBytes(body)); } @@ -411,12 +411,12 @@ public void SetRequestBodyString(string body) /// The resulting bytes. public async Task GetResponseBody(CancellationToken cancellationToken = default) { - if (!WebSession.Response.IsBodyRead) + if (!HttpClient.Response.IsBodyRead) { await readResponseBodyAsync(cancellationToken); } - return WebSession.Response.Body; + return HttpClient.Response.Body; } /// @@ -426,12 +426,12 @@ public async Task GetResponseBody(CancellationToken cancellationToken = /// The string body. public async Task GetResponseBodyAsString(CancellationToken cancellationToken = default) { - if (!WebSession.Response.IsBodyRead) + if (!HttpClient.Response.IsBodyRead) { await readResponseBodyAsync(cancellationToken); } - return WebSession.Response.BodyString; + return HttpClient.Response.BodyString; } /// @@ -440,12 +440,12 @@ public async Task GetResponseBodyAsString(CancellationToken cancellation /// The body bytes to set. public void SetResponseBody(byte[] body) { - if (!WebSession.Request.Locked) + if (!HttpClient.Request.Locked) { throw new Exception("You cannot call this function before request is made to server."); } - var response = WebSession.Response; + var response = HttpClient.Response; response.Body = body; } @@ -455,12 +455,12 @@ public void SetResponseBody(byte[] body) /// The body string to set. public void SetResponseBodyString(string body) { - if (!WebSession.Request.Locked) + if (!HttpClient.Request.Locked) { throw new Exception("You cannot call this function before request is made to server."); } - var bodyBytes = WebSession.Response.Encoding.GetBytes(body); + var bodyBytes = HttpClient.Response.Encoding.GetBytes(body); SetResponseBody(bodyBytes); } @@ -481,7 +481,7 @@ public void Ok(string html, Dictionary headers = null, response.Headers.AddHeaders(headers); } - response.HttpVersion = WebSession.Request.HttpVersion; + response.HttpVersion = HttpClient.Request.HttpVersion; response.Body = response.Encoding.GetBytes(html ?? string.Empty); Respond(response, closeServerConnection); @@ -499,7 +499,7 @@ public void Ok(byte[] result, Dictionary headers = null, { var response = new OkResponse(); response.Headers.AddHeaders(headers); - response.HttpVersion = WebSession.Request.HttpVersion; + response.HttpVersion = HttpClient.Request.HttpVersion; response.Body = result; Respond(response, closeServerConnection); @@ -518,7 +518,7 @@ public void GenericResponse(string html, HttpStatusCode status, Dictionary headers = null, bool closeServerConnection = false) { var response = new GenericResponse(status); - response.HttpVersion = WebSession.Request.HttpVersion; + response.HttpVersion = HttpClient.Request.HttpVersion; response.Headers.AddHeaders(headers); response.Body = response.Encoding.GetBytes(html ?? string.Empty); @@ -537,7 +537,7 @@ public void GenericResponse(byte[] result, HttpStatusCode status, Dictionary headers, bool closeServerConnection = false) { var response = new GenericResponse(status); - response.HttpVersion = WebSession.Request.HttpVersion; + response.HttpVersion = HttpClient.Request.HttpVersion; response.Headers.AddHeaders(headers); response.Body = result; @@ -552,7 +552,7 @@ public void GenericResponse(byte[] result, HttpStatusCode status, public void Redirect(string url, bool closeServerConnection = false) { var response = new RedirectResponse(); - response.HttpVersion = WebSession.Request.HttpVersion; + response.HttpVersion = HttpClient.Request.HttpVersion; response.Headers.AddHeader(KnownHeaders.Location, url); response.Body = emptyData; @@ -567,10 +567,10 @@ public void Redirect(string url, bool closeServerConnection = false) public void Respond(Response response, bool closeServerConnection = false) { //request already send/ready to be sent. - if (WebSession.Request.Locked) + if (HttpClient.Request.Locked) { //response already received from server and ready to be sent to client. - if (WebSession.Response.Locked) + if (HttpClient.Response.Locked) { throw new Exception("You cannot call this function after response is sent to the client."); } @@ -583,21 +583,21 @@ public void Respond(Response response, bool closeServerConnection = false) TerminateServerConnection(); } - response.SetOriginalHeaders(WebSession.Response); + response.SetOriginalHeaders(HttpClient.Response); //response already received from server but not yet ready to sent to client. - WebSession.Response = response; - WebSession.Response.Locked = true; + HttpClient.Response = response; + HttpClient.Response.Locked = true; } //request not yet sent/not yet ready to be sent. else { - WebSession.Request.Locked = true; - WebSession.Request.CancelRequest = true; + HttpClient.Request.Locked = true; + HttpClient.Request.CancelRequest = true; //set new response. - WebSession.Response = response; - WebSession.Response.Locked = true; + HttpClient.Response = response; + HttpClient.Response.Locked = true; } } @@ -607,7 +607,7 @@ public void Respond(Response response, bool closeServerConnection = false) /// public void TerminateServerConnection() { - WebSession.CloseServerConnection = true; + HttpClient.CloseServerConnection = true; } /// diff --git a/src/Titanium.Web.Proxy/EventArguments/SessionEventArgsBase.cs b/src/Titanium.Web.Proxy/EventArguments/SessionEventArgsBase.cs index a64b087b8..cb37f9260 100644 --- a/src/Titanium.Web.Proxy/EventArguments/SessionEventArgsBase.cs +++ b/src/Titanium.Web.Proxy/EventArguments/SessionEventArgsBase.cs @@ -8,6 +8,7 @@ using Titanium.Web.Proxy.Http; using Titanium.Web.Proxy.Models; using Titanium.Web.Proxy.Network; +using Titanium.Web.Proxy.Network.Tcp; namespace Titanium.Web.Proxy.EventArguments { @@ -19,8 +20,9 @@ namespace Titanium.Web.Proxy.EventArguments /// public abstract class SessionEventArgsBase : EventArgs, IDisposable { - internal readonly CancellationTokenSource CancellationTokenSource; + internal TcpServerConnection ServerConnection => HttpClient.Connection; + internal TcpClientConnection ClientConnection => ProxyClient.Connection; protected readonly int bufferSize; protected readonly IBufferPool bufferPool; @@ -50,10 +52,10 @@ protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint, CancellationTokenSource = cancellationTokenSource; ProxyClient = new ProxyClient(); - WebSession = new HttpWebClient(request); + HttpClient = new HttpWebClient(request); LocalEndPoint = endPoint; - WebSession.ProcessId = new Lazy(() => + HttpClient.ProcessId = new Lazy(() => { if (RunTime.IsWindows) { @@ -85,25 +87,27 @@ protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint, /// public object UserData { - get => WebSession.UserData; - set => WebSession.UserData = value; + get => HttpClient.UserData; + set => HttpClient.UserData = value; } /// /// Does this session uses SSL? /// - public bool IsHttps => WebSession.Request.IsHttps; + public bool IsHttps => HttpClient.Request.IsHttps; /// /// Client End Point. /// - public IPEndPoint ClientEndPoint => (IPEndPoint)ProxyClient.ClientConnection.RemoteEndPoint; + public IPEndPoint ClientEndPoint => (IPEndPoint)ProxyClient.Connection.RemoteEndPoint; /// - /// A web session corresponding to a single request/response sequence - /// within a proxy connection. + /// The web client used to communicate with server for this session. /// - public HttpWebClient WebSession { get; } + public HttpWebClient HttpClient { get; } + + [Obsolete("Use HttpClient instead.")] + public HttpWebClient WebSession => HttpClient; /// /// Are we using a custom upstream HTTP(S) proxy? @@ -136,7 +140,7 @@ public virtual void Dispose() DataReceived = null; Exception = null; - WebSession.FinishSession(); + HttpClient.FinishSession(); } /// diff --git a/src/Titanium.Web.Proxy/EventArguments/TunnelConnectEventArgs.cs b/src/Titanium.Web.Proxy/EventArguments/TunnelConnectEventArgs.cs index b54d524a9..47ffd896a 100644 --- a/src/Titanium.Web.Proxy/EventArguments/TunnelConnectEventArgs.cs +++ b/src/Titanium.Web.Proxy/EventArguments/TunnelConnectEventArgs.cs @@ -16,7 +16,7 @@ internal TunnelConnectSessionEventArgs(ProxyServer server, ProxyEndPoint endPoin CancellationTokenSource cancellationTokenSource) : base(server, endPoint, cancellationTokenSource, connectRequest) { - WebSession.ConnectRequest = connectRequest; + HttpClient.ConnectRequest = connectRequest; } /// diff --git a/src/Titanium.Web.Proxy/ExplicitClientHandler.cs b/src/Titanium.Web.Proxy/ExplicitClientHandler.cs index ed1040169..3191fa2db 100644 --- a/src/Titanium.Web.Proxy/ExplicitClientHandler.cs +++ b/src/Titanium.Web.Proxy/ExplicitClientHandler.cs @@ -73,7 +73,7 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect connectArgs = new TunnelConnectSessionEventArgs(this, endPoint, connectRequest, cancellationTokenSource); - connectArgs.ProxyClient.ClientConnection = clientConnection; + connectArgs.ProxyClient.Connection = clientConnection; connectArgs.ProxyClient.ClientStream = clientStream; await endPoint.InvokeBeforeTunnelConnectRequest(this, connectArgs, ExceptionFunc); @@ -83,9 +83,9 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect if (connectArgs.DenyConnect) { - if (connectArgs.WebSession.Response.StatusCode == 0) + if (connectArgs.HttpClient.Response.StatusCode == 0) { - connectArgs.WebSession.Response = new Response + connectArgs.HttpClient.Response = new Response { HttpVersion = HttpHeader.Version11, StatusCode = (int)HttpStatusCode.Forbidden, @@ -94,7 +94,7 @@ private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnect } // send the response - await clientStreamWriter.WriteResponseAsync(connectArgs.WebSession.Response, + await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response, cancellationToken: cancellationToken); return; } @@ -104,7 +104,7 @@ await clientStreamWriter.WriteResponseAsync(connectArgs.WebSession.Response, await endPoint.InvokeBeforeTunnectConnectResponse(this, connectArgs, ExceptionFunc); // send the response - await clientStreamWriter.WriteResponseAsync(connectArgs.WebSession.Response, + await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response, cancellationToken: cancellationToken); return; } @@ -115,7 +115,7 @@ await clientStreamWriter.WriteResponseAsync(connectArgs.WebSession.Response, // Set ContentLength explicitly to properly handle HTTP 1.0 response.ContentLength = 0; response.Headers.FixProxyHeaders(); - connectArgs.WebSession.Response = response; + connectArgs.HttpClient.Response = response; await clientStreamWriter.WriteResponseAsync(response, cancellationToken: cancellationToken); @@ -252,7 +252,7 @@ await clientStreamWriter.WriteResponseAsync(connectArgs.WebSession.Response, } var serverHelloInfo = await SslTools.PeekServerHello(connection.Stream, BufferPool, cancellationToken); - ((ConnectResponse)connectArgs.WebSession.Response).ServerHelloInfo = serverHelloInfo; + ((ConnectResponse)connectArgs.HttpClient.Response).ServerHelloInfo = serverHelloInfo; } await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool, BufferSize, @@ -321,7 +321,7 @@ await Http2Helper.SendHttp2(clientStream, connection.Stream, BufferSize, calledRequestHandler = true; // Now create the request await handleHttpSessionRequest(endPoint, clientConnection, clientStream, clientStreamWriter, - cancellationTokenSource, connectHostname, connectArgs?.WebSession.ConnectRequest, prefetchConnectionTask); + cancellationTokenSource, connectHostname, connectArgs?.HttpClient.ConnectRequest, prefetchConnectionTask); } catch (ProxyException e) { diff --git a/src/Titanium.Web.Proxy/Http/HttpWebClient.cs b/src/Titanium.Web.Proxy/Http/HttpWebClient.cs index 4813d6fab..285df0a6d 100644 --- a/src/Titanium.Web.Proxy/Http/HttpWebClient.cs +++ b/src/Titanium.Web.Proxy/Http/HttpWebClient.cs @@ -17,16 +17,16 @@ namespace Titanium.Web.Proxy.Http /// public class HttpWebClient { - internal HttpWebClient(Request request = null, Response response = null) + internal HttpWebClient(Request request) { Request = request ?? new Request(); - Response = response ?? new Response(); + Response = new Response(); } /// /// Connection to server /// - internal TcpServerConnection ServerConnection { get; set; } + internal TcpServerConnection Connection { get; set; } /// /// Should we close the server connection at the end of this HTTP request/response session. @@ -81,7 +81,7 @@ internal HttpWebClient(Request request = null, Response response = null) internal void SetConnection(TcpServerConnection serverConnection) { serverConnection.LastAccess = DateTime.Now; - ServerConnection = serverConnection; + Connection = serverConnection; } /// @@ -91,11 +91,11 @@ internal void SetConnection(TcpServerConnection serverConnection) internal async Task SendRequest(bool enable100ContinueBehaviour, bool isTransparent, CancellationToken cancellationToken) { - var upstreamProxy = ServerConnection.UpStreamProxy; + var upstreamProxy = Connection.UpStreamProxy; - bool useUpstreamProxy = upstreamProxy != null && ServerConnection.IsHttps == false; + bool useUpstreamProxy = upstreamProxy != null && Connection.IsHttps == false; - var writer = ServerConnection.StreamWriter; + var writer = Connection.StreamWriter; // prepare the request & headers await writer.WriteLineAsync(Request.CreateRequestLine(Request.Method, @@ -106,7 +106,7 @@ await writer.WriteLineAsync(Request.CreateRequestLine(Request.Method, // Send Authentication to Upstream proxy if needed if (!isTransparent && upstreamProxy != null - && ServerConnection.IsHttps == false + && Connection.IsHttps == false && !string.IsNullOrEmpty(upstreamProxy.UserName) && upstreamProxy.Password != null) { @@ -134,7 +134,7 @@ await writer.WriteLineAsync(Request.CreateRequestLine(Request.Method, string httpStatus; try { - httpStatus = await ServerConnection.Stream.ReadLineAsync(cancellationToken); + httpStatus = await Connection.Stream.ReadLineAsync(cancellationToken); if (httpStatus == null) { throw new ServerConnectionException("Server connection was closed."); @@ -153,13 +153,13 @@ await writer.WriteLineAsync(Request.CreateRequestLine(Request.Method, && responseStatusDescription.EqualsIgnoreCase("continue")) { Request.Is100Continue = true; - await ServerConnection.Stream.ReadLineAsync(cancellationToken); + await Connection.Stream.ReadLineAsync(cancellationToken); } else if (responseStatusCode == (int)HttpStatusCode.ExpectationFailed && responseStatusDescription.EqualsIgnoreCase("expectation failed")) { Request.ExpectationFailed = true; - await ServerConnection.Stream.ReadLineAsync(cancellationToken); + await Connection.Stream.ReadLineAsync(cancellationToken); } } } @@ -180,7 +180,7 @@ internal async Task ReceiveResponse(CancellationToken cancellationToken) string httpStatus; try { - httpStatus = await ServerConnection.Stream.ReadLineAsync(cancellationToken); + httpStatus = await Connection.Stream.ReadLineAsync(cancellationToken); if (httpStatus == null) { throw new ServerConnectionException("Server connection was closed."); @@ -193,7 +193,7 @@ internal async Task ReceiveResponse(CancellationToken cancellationToken) if (httpStatus == string.Empty) { - httpStatus = await ServerConnection.Stream.ReadLineAsync(cancellationToken); + httpStatus = await Connection.Stream.ReadLineAsync(cancellationToken); } Response.ParseResponseLine(httpStatus, out var version, out int statusCode, out string statusDescription); @@ -209,7 +209,7 @@ internal async Task ReceiveResponse(CancellationToken cancellationToken) // Read the next line after 100-continue Response.Is100Continue = true; Response.StatusCode = 0; - await ServerConnection.Stream.ReadLineAsync(cancellationToken); + await Connection.Stream.ReadLineAsync(cancellationToken); // now receive response await ReceiveResponse(cancellationToken); @@ -222,7 +222,7 @@ internal async Task ReceiveResponse(CancellationToken cancellationToken) // read next line after expectation failed response Response.ExpectationFailed = true; Response.StatusCode = 0; - await ServerConnection.Stream.ReadLineAsync(cancellationToken); + await Connection.Stream.ReadLineAsync(cancellationToken); // now receive response await ReceiveResponse(cancellationToken); @@ -230,7 +230,7 @@ internal async Task ReceiveResponse(CancellationToken cancellationToken) } // Read the response headers in to unique and non-unique header collections - await HeaderParser.ReadHeaders(ServerConnection.Stream, Response.Headers, cancellationToken); + await HeaderParser.ReadHeaders(Connection.Stream, Response.Headers, cancellationToken); } /// @@ -238,7 +238,7 @@ internal async Task ReceiveResponse(CancellationToken cancellationToken) /// internal void FinishSession() { - ServerConnection = null; + Connection = null; ConnectRequest?.FinishSession(); Request?.FinishSession(); diff --git a/src/Titanium.Web.Proxy/Network/ProxyClient.cs b/src/Titanium.Web.Proxy/Network/ProxyClient.cs index 3611bdd8f..2eae08e5f 100644 --- a/src/Titanium.Web.Proxy/Network/ProxyClient.cs +++ b/src/Titanium.Web.Proxy/Network/ProxyClient.cs @@ -12,7 +12,7 @@ internal class ProxyClient /// /// TcpClient connection used to communicate with client /// - internal TcpClientConnection ClientConnection { get; set; } + internal TcpClientConnection Connection { get; set; } /// /// Holds the stream to client diff --git a/src/Titanium.Web.Proxy/Network/Tcp/TcpConnectionFactory.cs b/src/Titanium.Web.Proxy/Network/Tcp/TcpConnectionFactory.cs index 58daaf078..a69aebf07 100644 --- a/src/Titanium.Web.Proxy/Network/Tcp/TcpConnectionFactory.cs +++ b/src/Titanium.Web.Proxy/Network/Tcp/TcpConnectionFactory.cs @@ -98,10 +98,10 @@ internal async Task GetConnectionCacheKey(ProxyServer server, SessionEve session.CustomUpStreamProxyUsed = customUpStreamProxy; return GetConnectionCacheKey( - session.WebSession.Request.RequestUri.Host, - session.WebSession.Request.RequestUri.Port, + session.HttpClient.Request.RequestUri.Host, + session.HttpClient.Request.RequestUri.Port, isHttps, applicationProtocols, - server, session.WebSession.UpStreamEndPoint ?? server.UpStreamEndPoint, + server, session.HttpClient.UpStreamEndPoint ?? server.UpStreamEndPoint, customUpStreamProxy ?? (isHttps ? server.UpStreamHttpsProxy : server.UpStreamHttpProxy)); } @@ -148,11 +148,11 @@ internal async Task GetServerConnection(ProxyServer server, session.CustomUpStreamProxyUsed = customUpStreamProxy; return await GetServerConnection( - session.WebSession.Request.RequestUri.Host, - session.WebSession.Request.RequestUri.Port, - session.WebSession.Request.HttpVersion, + session.HttpClient.Request.RequestUri.Host, + session.HttpClient.Request.RequestUri.Port, + session.HttpClient.Request.HttpVersion, isHttps, applicationProtocols, isConnect, - server, session, session.WebSession.UpStreamEndPoint ?? server.UpStreamEndPoint, + server, session, session.HttpClient.UpStreamEndPoint ?? server.UpStreamEndPoint, customUpStreamProxy ?? (isHttps ? server.UpStreamHttpsProxy : server.UpStreamHttpProxy), noCache, cancellationToken); } diff --git a/src/Titanium.Web.Proxy/ProxyAuthorizationHandler.cs b/src/Titanium.Web.Proxy/ProxyAuthorizationHandler.cs index ed26b65f5..eda4602f8 100644 --- a/src/Titanium.Web.Proxy/ProxyAuthorizationHandler.cs +++ b/src/Titanium.Web.Proxy/ProxyAuthorizationHandler.cs @@ -26,14 +26,14 @@ private async Task checkAuthorization(SessionEventArgsBase session) return true; } - var httpHeaders = session.WebSession.Request.Headers; + var httpHeaders = session.HttpClient.Request.Headers; try { var header = httpHeaders.GetFirstHeader(KnownHeaders.ProxyAuthorization); if (header == null) { - session.WebSession.Response = createAuthentication407Response("Proxy Authentication Required"); + session.HttpClient.Response = createAuthentication407Response("Proxy Authentication Required"); return false; } @@ -42,7 +42,7 @@ private async Task checkAuthorization(SessionEventArgsBase session) if (headerValueParts.Length != 2) { // Return not authorized - session.WebSession.Response = createAuthentication407Response("Proxy Authentication Invalid"); + session.HttpClient.Response = createAuthentication407Response("Proxy Authentication Invalid"); return false; } @@ -57,7 +57,7 @@ private async Task checkAuthorization(SessionEventArgsBase session) if (result.Result == ProxyAuthenticationResult.ContinuationNeeded) { - session.WebSession.Response = createAuthentication407Response("Proxy Authentication Invalid", result.Continuation); + session.HttpClient.Response = createAuthentication407Response("Proxy Authentication Invalid", result.Continuation); return false; } @@ -73,7 +73,7 @@ private async Task checkAuthorization(SessionEventArgsBase session) httpHeaders)); // Return not authorized - session.WebSession.Response = createAuthentication407Response("Proxy Authentication Invalid"); + session.HttpClient.Response = createAuthentication407Response("Proxy Authentication Invalid"); return false; } } @@ -83,7 +83,7 @@ private async Task authenticateUserBasic(SessionEventArgsBase session, str if (!headerValueParts[0].EqualsIgnoreCase(KnownHeaders.ProxyAuthorizationBasic)) { // Return not authorized - session.WebSession.Response = createAuthentication407Response("Proxy Authentication Invalid"); + session.HttpClient.Response = createAuthentication407Response("Proxy Authentication Invalid"); return false; } @@ -92,7 +92,7 @@ private async Task authenticateUserBasic(SessionEventArgsBase session, str if (colonIndex == -1) { // Return not authorized - session.WebSession.Response = createAuthentication407Response("Proxy Authentication Invalid"); + session.HttpClient.Response = createAuthentication407Response("Proxy Authentication Invalid"); return false; } @@ -101,7 +101,7 @@ private async Task authenticateUserBasic(SessionEventArgsBase session, str bool authenticated = await ProxyBasicAuthenticateFunc(session, username, password); if (!authenticated) { - session.WebSession.Response = createAuthentication407Response("Proxy Authentication Invalid"); + session.HttpClient.Response = createAuthentication407Response("Proxy Authentication Invalid"); } return authenticated; diff --git a/src/Titanium.Web.Proxy/ProxyServer.cs b/src/Titanium.Web.Proxy/ProxyServer.cs index 510194c1f..f477734b6 100644 --- a/src/Titanium.Web.Proxy/ProxyServer.cs +++ b/src/Titanium.Web.Proxy/ProxyServer.cs @@ -679,7 +679,7 @@ private void validateEndPointAsSystemProxy(ExplicitProxyEndPoint endPoint) /// The external proxy as task result. private Task getSystemUpStreamProxy(SessionEventArgsBase sessionEventArgs) { - var proxy = systemProxyResolver.GetProxy(sessionEventArgs.WebSession.Request.RequestUri); + var proxy = systemProxyResolver.GetProxy(sessionEventArgs.HttpClient.Request.RequestUri); return Task.FromResult(proxy); } diff --git a/src/Titanium.Web.Proxy/RequestHandler.cs b/src/Titanium.Web.Proxy/RequestHandler.cs index 13c35a10b..47e5fe801 100644 --- a/src/Titanium.Web.Proxy/RequestHandler.cs +++ b/src/Titanium.Web.Proxy/RequestHandler.cs @@ -15,6 +15,7 @@ using Titanium.Web.Proxy.Helpers; using Titanium.Web.Proxy.Http; using Titanium.Web.Proxy.Models; +using Titanium.Web.Proxy.Network; using Titanium.Web.Proxy.Network.Tcp; using Titanium.Web.Proxy.Shared; @@ -71,8 +72,8 @@ private async Task handleHttpSessionRequest(ProxyEndPoint endPoint, TcpClientCon var args = new SessionEventArgs(this, endPoint, cancellationTokenSource) { - ProxyClient = { ClientConnection = clientConnection }, - WebSession = { ConnectRequest = connectRequest } + ProxyClient = { Connection = clientConnection }, + HttpClient = { ConnectRequest = connectRequest } }; try @@ -83,7 +84,7 @@ private async Task handleHttpSessionRequest(ProxyEndPoint endPoint, TcpClientCon out var version); // Read the request headers in to unique and non-unique header collections - await HeaderParser.ReadHeaders(clientStream, args.WebSession.Request.Headers, + await HeaderParser.ReadHeaders(clientStream, args.HttpClient.Request.Headers, cancellationToken); Uri httpRemoteUri; @@ -100,7 +101,7 @@ await HeaderParser.ReadHeaders(clientStream, args.WebSession.Request.Headers, } else { - string host = args.WebSession.Request.Host ?? httpsConnectHostname; + string host = args.HttpClient.Request.Host ?? httpsConnectHostname; string hostAndPath = host; if (httpUrl.StartsWith("/")) { @@ -119,7 +120,7 @@ await HeaderParser.ReadHeaders(clientStream, args.WebSession.Request.Headers, } } - var request = args.WebSession.Request; + var request = args.HttpClient.Request; request.RequestUri = httpRemoteUri; request.OriginalUrl = httpUrl; @@ -136,7 +137,7 @@ await HeaderParser.ReadHeaders(clientStream, args.WebSession.Request.Headers, await invokeBeforeResponse(args); // send the response - await clientStreamWriter.WriteResponseAsync(args.WebSession.Response, + await clientStreamWriter.WriteResponseAsync(args.HttpClient.Response, cancellationToken: cancellationToken); return; } @@ -161,7 +162,7 @@ await clientStreamWriter.WriteResponseAsync(args.WebSession.Response, // If user requested interception do it await invokeBeforeRequest(args); - var response = args.WebSession.Response; + var response = args.HttpClient.Response; if (request.CancelRequest) { @@ -197,49 +198,51 @@ await clientStreamWriter.WriteResponseAsync(args.WebSession.Response, connection = null; } - //a connection generator task with captured parameters via closure. - Func> generator = () => - tcpConnectionFactory.GetServerConnection(this, args, isConnect: false, - applicationProtocol:clientConnection.NegotiatedApplicationProtocol, - noCache: false, cancellationToken: cancellationToken); - - //for connection pool, retry fails until cache is exhausted. - var result = await retryPolicy().ExecuteAsync(async (serverConnection) => + RetryResult result; + if (request.UpgradeToWebSocket) { - args.TimeLine["Connection Ready"] = DateTime.Now; - - // if upgrading to websocket then relay the request without reading the contents - if (request.UpgradeToWebSocket) + //a connection generator task with captured parameters via closure. + Func> generator = () => + tcpConnectionFactory.GetServerConnection(this, args, isConnect: false, + applicationProtocol: clientConnection.NegotiatedApplicationProtocol, + noCache: false, cancellationToken: cancellationToken); + + //for connection pool, retry fails until cache is exhausted. + result = await retryPolicy().ExecuteAsync(async (serverConnection) => { + args.TimeLine["Connection Ready"] = DateTime.Now; + + // if upgrading to websocket then relay the request without reading the contents await handleWebSocketUpgrade(httpCmd, args, request, response, clientStream, clientStreamWriter, serverConnection, cancellationTokenSource, cancellationToken); closeServerConnection = true; return false; - } - - // construct the web request that we are going to issue on behalf of the client. - await handleHttpSessionRequest(serverConnection, args); - return true; - }, generator, connection); + }, generator, connection); + } + else + { + result = await handleHttpSessionRequest(args, connection, + clientConnection.NegotiatedApplicationProtocol, cancellationToken); + } //update connection to latest used connection = result.LatestConnection; //throw if exception happened - if(!result.IsSuccess) + if (!result.IsSuccess) { throw result.Exception; } - if(!result.Continue) + if (!result.Continue) { return; } //user requested - if (args.WebSession.CloseServerConnection) + if (args.HttpClient.CloseServerConnection) { closeServerConnection = true; return; @@ -262,7 +265,7 @@ await handleWebSocketUpgrade(httpCmd, args, request, //between sessions without using it. //Do not release authenticated connections for performance reasons. //Otherwise it will keep authenticating per session. - if (EnableConnectionPool && connection!=null + if (EnableConnectionPool && connection != null && !connection.IsWinAuthenticated) { await tcpConnectionFactory.Release(connection); @@ -297,6 +300,38 @@ await tcpConnectionFactory.Release(connection, } } + private async Task handleHttpSessionRequest(SessionEventArgs args, + TcpServerConnection connection, + SslApplicationProtocol protocol, + CancellationToken cancellationToken) + { + //host/scheme changed from ReRequest + if (args.ReRequest + && (args.HttpClient.Request.IsHttps != connection.IsHttps + || args.HttpClient.Request.Host != connection.HostName)) + { + connection = null; + } + + + //a connection generator task with captured parameters via closure. + Func> generator = () => + tcpConnectionFactory.GetServerConnection(this, args, isConnect: false, + applicationProtocol: protocol, + noCache: false, cancellationToken: cancellationToken); + + //for connection pool, retry fails until cache is exhausted. + return await retryPolicy().ExecuteAsync(async (serverConnection) => + { + args.TimeLine["Connection Ready"] = DateTime.Now; + + // construct the web request that we are going to issue on behalf of the client. + await handleHttpSessionRequest(serverConnection, args); + return true; + + }, generator, connection); + } + /// /// Handle a specific session (request/response sequence) /// @@ -306,7 +341,7 @@ await tcpConnectionFactory.Release(connection, private async Task handleHttpSessionRequest(TcpServerConnection serverConnection, SessionEventArgs args) { var cancellationToken = args.CancellationTokenSource.Token; - var request = args.WebSession.Request; + var request = args.HttpClient.Request; request.Locked = true; var body = request.CompressBodyAndUpdateContentLength(); @@ -315,8 +350,8 @@ private async Task handleHttpSessionRequest(TcpServerConnection serverConnection // and see if server would return 100 conitinue if (request.ExpectContinue) { - args.WebSession.SetConnection(serverConnection); - await args.WebSession.SendRequest(Enable100ContinueBehaviour, args.IsTransparent, + args.HttpClient.SetConnection(serverConnection); + await args.HttpClient.SendRequest(Enable100ContinueBehaviour, args.IsTransparent, cancellationToken); } @@ -327,13 +362,13 @@ await args.WebSession.SendRequest(Enable100ContinueBehaviour, args.IsTransparent if (request.Is100Continue) { - await clientStreamWriter.WriteResponseStatusAsync(args.WebSession.Response.HttpVersion, + await clientStreamWriter.WriteResponseStatusAsync(args.HttpClient.Response.HttpVersion, (int)HttpStatusCode.Continue, "Continue", cancellationToken); await clientStreamWriter.WriteLineAsync(cancellationToken); } else if (request.ExpectationFailed) { - await clientStreamWriter.WriteResponseStatusAsync(args.WebSession.Response.HttpVersion, + await clientStreamWriter.WriteResponseStatusAsync(args.HttpClient.Response.HttpVersion, (int)HttpStatusCode.ExpectationFailed, "Expectation Failed", cancellationToken); await clientStreamWriter.WriteLineAsync(cancellationToken); } @@ -342,8 +377,8 @@ await clientStreamWriter.WriteResponseStatusAsync(args.WebSession.Response.HttpV // If expect continue is not enabled then set the connectio and send request headers if (!request.ExpectContinue) { - args.WebSession.SetConnection(serverConnection); - await args.WebSession.SendRequest(Enable100ContinueBehaviour, args.IsTransparent, + args.HttpClient.SetConnection(serverConnection); + await args.HttpClient.SendRequest(Enable100ContinueBehaviour, args.IsTransparent, cancellationToken); } @@ -352,7 +387,7 @@ await args.WebSession.SendRequest(Enable100ContinueBehaviour, args.IsTransparent { if (request.IsBodyRead) { - var writer = args.WebSession.ServerConnection.StreamWriter; + var writer = args.HttpClient.Connection.StreamWriter; await writer.WriteBodyAsync(body, request.IsChunked, cancellationToken); } else @@ -361,7 +396,7 @@ await args.WebSession.SendRequest(Enable100ContinueBehaviour, args.IsTransparent { if (request.HasBody) { - HttpWriter writer = args.WebSession.ServerConnection.StreamWriter; + HttpWriter writer = args.HttpClient.Connection.StreamWriter; await args.CopyRequestBodyAsync(writer, TransformationMode.None, cancellationToken); } } diff --git a/src/Titanium.Web.Proxy/ResponseHandler.cs b/src/Titanium.Web.Proxy/ResponseHandler.cs index 427ba68bc..f6b13115c 100644 --- a/src/Titanium.Web.Proxy/ResponseHandler.cs +++ b/src/Titanium.Web.Proxy/ResponseHandler.cs @@ -22,11 +22,11 @@ private async Task handleHttpSessionResponse(SessionEventArgs args) var cancellationToken = args.CancellationTokenSource.Token; // read response & headers from server - await args.WebSession.ReceiveResponse(cancellationToken); + await args.HttpClient.ReceiveResponse(cancellationToken); args.TimeLine["Response Received"] = DateTime.Now; - var response = args.WebSession.Response; + var response = args.HttpClient.Response; args.ReRequest = false; // check for windows authentication @@ -38,7 +38,7 @@ private async Task handleHttpSessionResponse(SessionEventArgs args) } else { - WinAuthEndPoint.AuthenticatedResponse(args.WebSession.Data); + WinAuthEndPoint.AuthenticatedResponse(args.HttpClient.Data); } } @@ -53,7 +53,7 @@ private async Task handleHttpSessionResponse(SessionEventArgs args) } // it may changed in the user event - response = args.WebSession.Response; + response = args.HttpClient.Response; var clientStreamWriter = args.ProxyClient.ClientStreamWriter; @@ -63,8 +63,8 @@ private async Task handleHttpSessionResponse(SessionEventArgs args) //write custom user response with body and return. await clientStreamWriter.WriteResponseAsync(response, cancellationToken: cancellationToken); - if(args.WebSession.ServerConnection != null - && !args.WebSession.CloseServerConnection) + if(args.HttpClient.Connection != null + && !args.HttpClient.CloseServerConnection) { // syphon out the original response body from server connection // so that connection will be good to be reused. @@ -80,7 +80,8 @@ private async Task handleHttpSessionResponse(SessionEventArgs args) { // clear current response await args.ClearResponse(cancellationToken); - await handleHttpSessionRequest(args.WebSession.ServerConnection, args); + await handleHttpSessionRequest(args, args.HttpClient.Connection, + args.ClientConnection.NegotiatedApplicationProtocol, cancellationToken); return; } diff --git a/src/Titanium.Web.Proxy/WebSocketHandler.cs b/src/Titanium.Web.Proxy/WebSocketHandler.cs index 1ff4695ed..954b2dffe 100644 --- a/src/Titanium.Web.Proxy/WebSocketHandler.cs +++ b/src/Titanium.Web.Proxy/WebSocketHandler.cs @@ -58,7 +58,7 @@ await clientStreamWriter.WriteResponseAsync(response, } // If user requested call back then do it - if (!args.WebSession.Response.Locked) + if (!args.HttpClient.Response.Locked) { await invokeBeforeResponse(args); } diff --git a/src/Titanium.Web.Proxy/WinAuthHandler.cs b/src/Titanium.Web.Proxy/WinAuthHandler.cs index f57a30f79..05171e137 100644 --- a/src/Titanium.Web.Proxy/WinAuthHandler.cs +++ b/src/Titanium.Web.Proxy/WinAuthHandler.cs @@ -50,7 +50,7 @@ private async Task handle401UnAuthorized(SessionEventArgs args) string headerName = null; HttpHeader authHeader = null; - var response = args.WebSession.Response; + var response = args.HttpClient.Response; // check in non-unique headers first var header = response.Headers.NonUniqueHeaders.FirstOrDefault(x => authHeaderNames.Contains(x.Key)); @@ -96,14 +96,14 @@ private async Task handle401UnAuthorized(SessionEventArgs args) var expectedAuthState = scheme == null ? State.WinAuthState.INITIAL_TOKEN : State.WinAuthState.UNAUTHORIZED; - if (!WinAuthEndPoint.ValidateWinAuthState(args.WebSession.Data, expectedAuthState)) + if (!WinAuthEndPoint.ValidateWinAuthState(args.HttpClient.Data, expectedAuthState)) { // Invalid state, create proper error message to client await rewriteUnauthorizedResponse(args); return; } - var request = args.WebSession.Request; + var request = args.HttpClient.Request; // clear any existing headers to avoid confusing bad servers request.Headers.RemoveHeader(KnownHeaders.Authorization); @@ -111,7 +111,7 @@ private async Task handle401UnAuthorized(SessionEventArgs args) // initial value will match exactly any of the schemes if (scheme != null) { - string clientToken = WinAuthHandler.GetInitialAuthToken(request.Host, scheme, args.WebSession.Data); + string clientToken = WinAuthHandler.GetInitialAuthToken(request.Host, scheme, args.HttpClient.Data); string auth = string.Concat(scheme, clientToken); @@ -133,7 +133,7 @@ private async Task handle401UnAuthorized(SessionEventArgs args) authHeader.Value.Length > x.Length + 1); string serverToken = authHeader.Value.Substring(scheme.Length + 1); - string clientToken = WinAuthHandler.GetFinalAuthToken(request.Host, serverToken, args.WebSession.Data); + string clientToken = WinAuthHandler.GetFinalAuthToken(request.Host, serverToken, args.HttpClient.Data); string auth = string.Concat(scheme, clientToken); @@ -146,7 +146,7 @@ private async Task handle401UnAuthorized(SessionEventArgs args) request.ContentLength = request.Body.Length; } - args.WebSession.ServerConnection.IsWinAuthenticated = true; + args.HttpClient.Connection.IsWinAuthenticated = true; } // Need to revisit this. @@ -165,7 +165,7 @@ private async Task handle401UnAuthorized(SessionEventArgs args) /// private async Task rewriteUnauthorizedResponse(SessionEventArgs args) { - var response = args.WebSession.Response; + var response = args.HttpClient.Response; // Strip authentication headers to avoid credentials prompt in client web browser foreach (string authHeaderName in authHeaderNames) @@ -176,7 +176,7 @@ private async Task rewriteUnauthorizedResponse(SessionEventArgs args) // Add custom div to body to clarify that the proxy (not the client browser) failed authentication string authErrorMessage = "

NTLM authentication through Titanium.Web.Proxy (" + - args.ProxyClient.ClientConnection.LocalEndPoint + + args.ProxyClient.Connection.LocalEndPoint + ") failed. Please check credentials.

"; string originalErrorMessage = "

Response from remote web server below.


"; diff --git a/tests/Titanium.Web.Proxy.IntegrationTests/InterceptionTests.cs b/tests/Titanium.Web.Proxy.IntegrationTests/InterceptionTests.cs index 590227214..7a4ccfcd3 100644 --- a/tests/Titanium.Web.Proxy.IntegrationTests/InterceptionTests.cs +++ b/tests/Titanium.Web.Proxy.IntegrationTests/InterceptionTests.cs @@ -46,9 +46,9 @@ public ProxyTestController() public async Task OnRequest(object sender, SessionEventArgs e) { - if (e.WebSession.Request.Url.Contains("interceptthis.com")) + if (e.HttpClient.Request.Url.Contains("interceptthis.com")) { - if (e.WebSession.Request.HasBody) + if (e.HttpClient.Request.HasBody) { var body = await e.GetRequestBodyAsString(); } From 3471bfefb2bd4cd7873b08a25dc146c2e39d11dd Mon Sep 17 00:00:00 2001 From: buildbot121 Date: Tue, 20 Nov 2018 17:46:29 +0000 Subject: [PATCH 3/5] API documentation update by build server --- ...Proxy.EventArguments.SessionEventArgs.html | 3 + ...y.EventArguments.SessionEventArgsBase.html | 74 +++++++++++++------ ...guments.TunnelConnectSessionEventArgs.html | 3 + .../Titanium.Web.Proxy.Helpers.RunTime.html | 38 +++++++++- docs/index.json | 8 +- docs/xrefmap.yml | 26 +++++++ 6 files changed, 122 insertions(+), 30 deletions(-) diff --git a/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgs.html b/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgs.html index cca617d6d..0affc9e96 100644 --- a/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgs.html +++ b/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgs.html @@ -123,6 +123,9 @@
Inherited Members
+ diff --git a/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html b/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html index f1b423de6..ca6d0491a 100644 --- a/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html +++ b/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html @@ -141,7 +141,7 @@

Constructors Improve this Doc - View Source + View Source

SessionEventArgsBase(ProxyServer, ProxyEndPoint, CancellationTokenSource, Request)

@@ -190,7 +190,7 @@

Fields Improve this Doc - View Source + View Source

bufferPool

@@ -219,7 +219,7 @@
Field Value
Improve this Doc - View Source + View Source

bufferSize

@@ -248,7 +248,7 @@
Field Value
Improve this Doc - View Source + View Source

exceptionFunc

@@ -279,7 +279,7 @@

Properties Improve this Doc - View Source + View Source

ClientEndPoint

@@ -310,7 +310,7 @@
Property Value
Improve this Doc - View Source + View Source

CustomUpStreamProxyUsed

@@ -341,7 +341,7 @@
Property Value
Improve this Doc - View Source + View Source

Exception

@@ -367,12 +367,43 @@
Property Value
+ + | + Improve this Doc + + + View Source + + +

HttpClient

+

The web client used to communicate with server for this session.

+
+
+
Declaration
+
+
public HttpWebClient HttpClient { get; }
+
+
Property Value
+ + + + + + + + + + + + + +
TypeDescription
HttpWebClient
| Improve this Doc - View Source + View Source

IsHttps

@@ -403,7 +434,7 @@
Property Value
Improve this Doc - View Source + View Source

IsTransparent

@@ -434,7 +465,7 @@
Property Value
Improve this Doc - View Source + View Source

LocalEndPoint

@@ -465,7 +496,7 @@
Property Value
Improve this Doc - View Source + View Source

TimeLine

@@ -496,7 +527,7 @@
Property Value
Improve this Doc - View Source + View Source

UserData

@@ -528,17 +559,16 @@
Property Value
Improve this Doc - View Source + View Source

WebSession

-

A web session corresponding to a single request/response sequence -within a proxy connection.

-
+
Declaration
-
public HttpWebClient WebSession { get; }
+
[Obsolete("Use HttpClient instead.")]
+public HttpWebClient WebSession { get; }
Property Value
@@ -562,7 +592,7 @@

Methods Improve this Doc - View Source + View Source

Dispose()

@@ -578,7 +608,7 @@
Declaration
Improve this Doc - View Source + View Source

TerminateSession()

@@ -596,7 +626,7 @@

Events Improve this Doc - View Source + View Source

DataReceived

Fired when data is received within this session from client/server.

@@ -626,7 +656,7 @@
Event Type
Improve this Doc - View Source + View Source

DataSent

Fired when data is sent within this session to server/client.

@@ -666,7 +696,7 @@

Implements

Improve this Doc
  • - View Source + View Source
  • diff --git a/docs/api/Titanium.Web.Proxy.EventArguments.TunnelConnectSessionEventArgs.html b/docs/api/Titanium.Web.Proxy.EventArguments.TunnelConnectSessionEventArgs.html index 2dbe6fa20..6ca5f3be1 100644 --- a/docs/api/Titanium.Web.Proxy.EventArguments.TunnelConnectSessionEventArgs.html +++ b/docs/api/Titanium.Web.Proxy.EventArguments.TunnelConnectSessionEventArgs.html @@ -120,6 +120,9 @@
    Inherited Members
    + diff --git a/docs/api/Titanium.Web.Proxy.Helpers.RunTime.html b/docs/api/Titanium.Web.Proxy.Helpers.RunTime.html index 7881dc758..ff48ef887 100644 --- a/docs/api/Titanium.Web.Proxy.Helpers.RunTime.html +++ b/docs/api/Titanium.Web.Proxy.Helpers.RunTime.html @@ -128,7 +128,7 @@

    Properties Improve this Doc - View Source + View Source

    IsLinux

    @@ -158,7 +158,7 @@
    Property Value
    Improve this Doc - View Source + View Source

    IsMac

    @@ -183,12 +183,42 @@
    Property Value
    + + | + Improve this Doc + + + View Source + + +

    IsUwpOnWindows

    +
    +
    +
    Declaration
    +
    +
    public static bool IsUwpOnWindows { get; }
    +
    +
    Property Value
    + + + + + + + + + + + + + +
    TypeDescription
    Boolean
    | Improve this Doc - View Source + View Source

    IsWindows

    @@ -224,7 +254,7 @@
    Property Value
    Improve this Doc
  • - View Source + View Source
  • diff --git a/docs/index.json b/docs/index.json index 852c6dd56..dc648ef19 100644 --- a/docs/index.json +++ b/docs/index.json @@ -32,17 +32,17 @@ "api/Titanium.Web.Proxy.EventArguments.SessionEventArgs.html": { "href": "api/Titanium.Web.Proxy.EventArguments.SessionEventArgs.html", "title": "Class SessionEventArgs | Titanium Web Proxy", - "keywords": "Class SessionEventArgs Holds info related to a single proxy session (single request/response sequence). A proxy session is bounded to a single connection from client. A proxy session ends when client terminates connection to proxy or when server terminates connection from proxy. Inheritance Object EventArgs SessionEventArgsBase SessionEventArgs Implements IDisposable Inherited Members SessionEventArgsBase.bufferSize SessionEventArgsBase.bufferPool SessionEventArgsBase.exceptionFunc SessionEventArgsBase.TimeLine SessionEventArgsBase.UserData SessionEventArgsBase.IsHttps SessionEventArgsBase.ClientEndPoint SessionEventArgsBase.WebSession SessionEventArgsBase.CustomUpStreamProxyUsed SessionEventArgsBase.LocalEndPoint SessionEventArgsBase.IsTransparent SessionEventArgsBase.Exception SessionEventArgsBase.DataSent SessionEventArgsBase.DataReceived SessionEventArgsBase.TerminateSession() EventArgs.Empty Object.ToString() Object.Equals(Object) Object.Equals(Object, Object) Object.ReferenceEquals(Object, Object) Object.GetHashCode() Object.GetType() Object.MemberwiseClone() Namespace : Titanium.Web.Proxy.EventArguments Assembly : Titanium.Web.Proxy.dll Syntax public class SessionEventArgs : SessionEventArgsBase, IDisposable Constructors | Improve this Doc View Source SessionEventArgs(ProxyServer, ProxyEndPoint, Request, CancellationTokenSource) Declaration protected SessionEventArgs(ProxyServer server, ProxyEndPoint endPoint, Request request, CancellationTokenSource cancellationTokenSource) Parameters Type Name Description ProxyServer server ProxyEndPoint endPoint Request request CancellationTokenSource cancellationTokenSource Properties | Improve this Doc View Source ReRequest Should we send the request again ? Declaration public bool ReRequest { get; set; } Property Value Type Description Boolean Methods | Improve this Doc View Source Dispose() Implement any cleanup here Declaration public override void Dispose() Overrides SessionEventArgsBase.Dispose() | Improve this Doc View Source GenericResponse(Byte[], HttpStatusCode, Dictionary, Boolean) Before request is made to server respond with the specified byte[], the specified status to client. And then ignore the request. Declaration public void GenericResponse(byte[] result, HttpStatusCode status, Dictionary headers, bool closeServerConnection = false) Parameters Type Name Description Byte [] result The bytes to sent. HttpStatusCode status The HTTP status code. Dictionary < String , HttpHeader > headers The HTTP headers. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source GenericResponse(String, HttpStatusCode, Dictionary, Boolean) Before request is made to server respond with the specified HTML string and the specified status to client. And then ignore the request. Declaration public void GenericResponse(string html, HttpStatusCode status, Dictionary headers = null, bool closeServerConnection = false) Parameters Type Name Description String html The html content. HttpStatusCode status The HTTP status code. Dictionary < String , HttpHeader > headers The HTTP headers. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source GetRequestBody(CancellationToken) Gets the request body as bytes. Declaration public Task GetRequestBody(CancellationToken cancellationToken = default(CancellationToken)) Parameters Type Name Description CancellationToken cancellationToken Optional cancellation token for this async task. Returns Type Description Task < Byte []> The body as bytes. | Improve this Doc View Source GetRequestBodyAsString(CancellationToken) Gets the request body as string. Declaration public Task GetRequestBodyAsString(CancellationToken cancellationToken = default(CancellationToken)) Parameters Type Name Description CancellationToken cancellationToken Optional cancellation token for this async task. Returns Type Description Task < String > The body as string. | Improve this Doc View Source GetResponseBody(CancellationToken) Gets the response body as bytes. Declaration public Task GetResponseBody(CancellationToken cancellationToken = default(CancellationToken)) Parameters Type Name Description CancellationToken cancellationToken Optional cancellation token for this async task. Returns Type Description Task < Byte []> The resulting bytes. | Improve this Doc View Source GetResponseBodyAsString(CancellationToken) Gets the response body as string. Declaration public Task GetResponseBodyAsString(CancellationToken cancellationToken = default(CancellationToken)) Parameters Type Name Description CancellationToken cancellationToken Optional cancellation token for this async task. Returns Type Description Task < String > The string body. | Improve this Doc View Source Ok(Byte[], Dictionary, Boolean) Before request is made to server respond with the specified byte[] to client and ignore the request. Declaration public void Ok(byte[] result, Dictionary headers = null, bool closeServerConnection = false) Parameters Type Name Description Byte [] result The html content bytes. Dictionary < String , HttpHeader > headers The HTTP headers. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source Ok(String, Dictionary, Boolean) Before request is made to server respond with the specified HTML string to client and ignore the request. Declaration public void Ok(string html, Dictionary headers = null, bool closeServerConnection = false) Parameters Type Name Description String html HTML content to sent. Dictionary < String , HttpHeader > headers HTTP response headers. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source Redirect(String, Boolean) Redirect to provided URL. Declaration public void Redirect(string url, bool closeServerConnection = false) Parameters Type Name Description String url The URL to redirect. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source Respond(Response, Boolean) Respond with given response object to client. Declaration public void Respond(Response response, bool closeServerConnection = false) Parameters Type Name Description Response response The response object. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source SetRequestBody(Byte[]) Sets the request body. Declaration public void SetRequestBody(byte[] body) Parameters Type Name Description Byte [] body The request body bytes. | Improve this Doc View Source SetRequestBodyString(String) Sets the body with the specified string. Declaration public void SetRequestBodyString(string body) Parameters Type Name Description String body The request body string to set. | Improve this Doc View Source SetResponseBody(Byte[]) Set the response body bytes. Declaration public void SetResponseBody(byte[] body) Parameters Type Name Description Byte [] body The body bytes to set. | Improve this Doc View Source SetResponseBodyString(String) Replace the response body with the specified string. Declaration public void SetResponseBodyString(string body) Parameters Type Name Description String body The body string to set. | Improve this Doc View Source TerminateServerConnection() Terminate the connection to server at the end of this HTTP request/response session. Declaration public void TerminateServerConnection() Events | Improve this Doc View Source MultipartRequestPartSent Occurs when multipart request part sent. Declaration public event EventHandler MultipartRequestPartSent Event Type Type Description EventHandler < MultipartRequestPartSentEventArgs > Implements System.IDisposable" + "keywords": "Class SessionEventArgs Holds info related to a single proxy session (single request/response sequence). A proxy session is bounded to a single connection from client. A proxy session ends when client terminates connection to proxy or when server terminates connection from proxy. Inheritance Object EventArgs SessionEventArgsBase SessionEventArgs Implements IDisposable Inherited Members SessionEventArgsBase.bufferSize SessionEventArgsBase.bufferPool SessionEventArgsBase.exceptionFunc SessionEventArgsBase.TimeLine SessionEventArgsBase.UserData SessionEventArgsBase.IsHttps SessionEventArgsBase.ClientEndPoint SessionEventArgsBase.HttpClient SessionEventArgsBase.WebSession SessionEventArgsBase.CustomUpStreamProxyUsed SessionEventArgsBase.LocalEndPoint SessionEventArgsBase.IsTransparent SessionEventArgsBase.Exception SessionEventArgsBase.DataSent SessionEventArgsBase.DataReceived SessionEventArgsBase.TerminateSession() EventArgs.Empty Object.ToString() Object.Equals(Object) Object.Equals(Object, Object) Object.ReferenceEquals(Object, Object) Object.GetHashCode() Object.GetType() Object.MemberwiseClone() Namespace : Titanium.Web.Proxy.EventArguments Assembly : Titanium.Web.Proxy.dll Syntax public class SessionEventArgs : SessionEventArgsBase, IDisposable Constructors | Improve this Doc View Source SessionEventArgs(ProxyServer, ProxyEndPoint, Request, CancellationTokenSource) Declaration protected SessionEventArgs(ProxyServer server, ProxyEndPoint endPoint, Request request, CancellationTokenSource cancellationTokenSource) Parameters Type Name Description ProxyServer server ProxyEndPoint endPoint Request request CancellationTokenSource cancellationTokenSource Properties | Improve this Doc View Source ReRequest Should we send the request again ? Declaration public bool ReRequest { get; set; } Property Value Type Description Boolean Methods | Improve this Doc View Source Dispose() Implement any cleanup here Declaration public override void Dispose() Overrides SessionEventArgsBase.Dispose() | Improve this Doc View Source GenericResponse(Byte[], HttpStatusCode, Dictionary, Boolean) Before request is made to server respond with the specified byte[], the specified status to client. And then ignore the request. Declaration public void GenericResponse(byte[] result, HttpStatusCode status, Dictionary headers, bool closeServerConnection = false) Parameters Type Name Description Byte [] result The bytes to sent. HttpStatusCode status The HTTP status code. Dictionary < String , HttpHeader > headers The HTTP headers. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source GenericResponse(String, HttpStatusCode, Dictionary, Boolean) Before request is made to server respond with the specified HTML string and the specified status to client. And then ignore the request. Declaration public void GenericResponse(string html, HttpStatusCode status, Dictionary headers = null, bool closeServerConnection = false) Parameters Type Name Description String html The html content. HttpStatusCode status The HTTP status code. Dictionary < String , HttpHeader > headers The HTTP headers. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source GetRequestBody(CancellationToken) Gets the request body as bytes. Declaration public Task GetRequestBody(CancellationToken cancellationToken = default(CancellationToken)) Parameters Type Name Description CancellationToken cancellationToken Optional cancellation token for this async task. Returns Type Description Task < Byte []> The body as bytes. | Improve this Doc View Source GetRequestBodyAsString(CancellationToken) Gets the request body as string. Declaration public Task GetRequestBodyAsString(CancellationToken cancellationToken = default(CancellationToken)) Parameters Type Name Description CancellationToken cancellationToken Optional cancellation token for this async task. Returns Type Description Task < String > The body as string. | Improve this Doc View Source GetResponseBody(CancellationToken) Gets the response body as bytes. Declaration public Task GetResponseBody(CancellationToken cancellationToken = default(CancellationToken)) Parameters Type Name Description CancellationToken cancellationToken Optional cancellation token for this async task. Returns Type Description Task < Byte []> The resulting bytes. | Improve this Doc View Source GetResponseBodyAsString(CancellationToken) Gets the response body as string. Declaration public Task GetResponseBodyAsString(CancellationToken cancellationToken = default(CancellationToken)) Parameters Type Name Description CancellationToken cancellationToken Optional cancellation token for this async task. Returns Type Description Task < String > The string body. | Improve this Doc View Source Ok(Byte[], Dictionary, Boolean) Before request is made to server respond with the specified byte[] to client and ignore the request. Declaration public void Ok(byte[] result, Dictionary headers = null, bool closeServerConnection = false) Parameters Type Name Description Byte [] result The html content bytes. Dictionary < String , HttpHeader > headers The HTTP headers. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source Ok(String, Dictionary, Boolean) Before request is made to server respond with the specified HTML string to client and ignore the request. Declaration public void Ok(string html, Dictionary headers = null, bool closeServerConnection = false) Parameters Type Name Description String html HTML content to sent. Dictionary < String , HttpHeader > headers HTTP response headers. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source Redirect(String, Boolean) Redirect to provided URL. Declaration public void Redirect(string url, bool closeServerConnection = false) Parameters Type Name Description String url The URL to redirect. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source Respond(Response, Boolean) Respond with given response object to client. Declaration public void Respond(Response response, bool closeServerConnection = false) Parameters Type Name Description Response response The response object. Boolean closeServerConnection Close the server connection used by request if any? | Improve this Doc View Source SetRequestBody(Byte[]) Sets the request body. Declaration public void SetRequestBody(byte[] body) Parameters Type Name Description Byte [] body The request body bytes. | Improve this Doc View Source SetRequestBodyString(String) Sets the body with the specified string. Declaration public void SetRequestBodyString(string body) Parameters Type Name Description String body The request body string to set. | Improve this Doc View Source SetResponseBody(Byte[]) Set the response body bytes. Declaration public void SetResponseBody(byte[] body) Parameters Type Name Description Byte [] body The body bytes to set. | Improve this Doc View Source SetResponseBodyString(String) Replace the response body with the specified string. Declaration public void SetResponseBodyString(string body) Parameters Type Name Description String body The body string to set. | Improve this Doc View Source TerminateServerConnection() Terminate the connection to server at the end of this HTTP request/response session. Declaration public void TerminateServerConnection() Events | Improve this Doc View Source MultipartRequestPartSent Occurs when multipart request part sent. Declaration public event EventHandler MultipartRequestPartSent Event Type Type Description EventHandler < MultipartRequestPartSentEventArgs > Implements System.IDisposable" }, "api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html": { "href": "api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html", "title": "Class SessionEventArgsBase | Titanium Web Proxy", - "keywords": "Class SessionEventArgsBase Holds info related to a single proxy session (single request/response sequence). A proxy session is bounded to a single connection from client. A proxy session ends when client terminates connection to proxy or when server terminates connection from proxy. Inheritance Object EventArgs SessionEventArgsBase SessionEventArgs TunnelConnectSessionEventArgs Implements IDisposable Inherited Members EventArgs.Empty Object.ToString() Object.Equals(Object) Object.Equals(Object, Object) Object.ReferenceEquals(Object, Object) Object.GetHashCode() Object.GetType() Object.MemberwiseClone() Namespace : Titanium.Web.Proxy.EventArguments Assembly : Titanium.Web.Proxy.dll Syntax public abstract class SessionEventArgsBase : EventArgs, IDisposable Constructors | Improve this Doc View Source SessionEventArgsBase(ProxyServer, ProxyEndPoint, CancellationTokenSource, Request) Declaration protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint, CancellationTokenSource cancellationTokenSource, Request request) Parameters Type Name Description ProxyServer server ProxyEndPoint endPoint CancellationTokenSource cancellationTokenSource Request request Fields | Improve this Doc View Source bufferPool Declaration protected readonly IBufferPool bufferPool Field Value Type Description StreamExtended.IBufferPool | Improve this Doc View Source bufferSize Declaration protected readonly int bufferSize Field Value Type Description Int32 | Improve this Doc View Source exceptionFunc Declaration protected readonly ExceptionHandler exceptionFunc Field Value Type Description ExceptionHandler Properties | Improve this Doc View Source ClientEndPoint Client End Point. Declaration public IPEndPoint ClientEndPoint { get; } Property Value Type Description IPEndPoint | Improve this Doc View Source CustomUpStreamProxyUsed Are we using a custom upstream HTTP(S) proxy? Declaration public ExternalProxy CustomUpStreamProxyUsed { get; } Property Value Type Description ExternalProxy | Improve this Doc View Source Exception The last exception that happened. Declaration public Exception Exception { get; } Property Value Type Description Exception | Improve this Doc View Source IsHttps Does this session uses SSL? Declaration public bool IsHttps { get; } Property Value Type Description Boolean | Improve this Doc View Source IsTransparent Is this a transparent endpoint? Declaration public bool IsTransparent { get; } Property Value Type Description Boolean | Improve this Doc View Source LocalEndPoint Local endpoint via which we make the request. Declaration public ProxyEndPoint LocalEndPoint { get; } Property Value Type Description ProxyEndPoint | Improve this Doc View Source TimeLine Relative milliseconds for various events. Declaration public Dictionary TimeLine { get; set; } Property Value Type Description Dictionary < String , DateTime > | Improve this Doc View Source UserData Returns a user data for this request/response session which is same as the user data of WebSession. Declaration public object UserData { get; set; } Property Value Type Description Object | Improve this Doc View Source WebSession A web session corresponding to a single request/response sequence within a proxy connection. Declaration public HttpWebClient WebSession { get; } Property Value Type Description HttpWebClient Methods | Improve this Doc View Source Dispose() Implements cleanup here. Declaration public virtual void Dispose() | Improve this Doc View Source TerminateSession() Terminates the session abruptly by terminating client/server connections. Declaration public void TerminateSession() Events | Improve this Doc View Source DataReceived Fired when data is received within this session from client/server. Declaration public event EventHandler DataReceived Event Type Type Description EventHandler < StreamExtended.Network.DataEventArgs > | Improve this Doc View Source DataSent Fired when data is sent within this session to server/client. Declaration public event EventHandler DataSent Event Type Type Description EventHandler < StreamExtended.Network.DataEventArgs > Implements System.IDisposable" + "keywords": "Class SessionEventArgsBase Holds info related to a single proxy session (single request/response sequence). A proxy session is bounded to a single connection from client. A proxy session ends when client terminates connection to proxy or when server terminates connection from proxy. Inheritance Object EventArgs SessionEventArgsBase SessionEventArgs TunnelConnectSessionEventArgs Implements IDisposable Inherited Members EventArgs.Empty Object.ToString() Object.Equals(Object) Object.Equals(Object, Object) Object.ReferenceEquals(Object, Object) Object.GetHashCode() Object.GetType() Object.MemberwiseClone() Namespace : Titanium.Web.Proxy.EventArguments Assembly : Titanium.Web.Proxy.dll Syntax public abstract class SessionEventArgsBase : EventArgs, IDisposable Constructors | Improve this Doc View Source SessionEventArgsBase(ProxyServer, ProxyEndPoint, CancellationTokenSource, Request) Declaration protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint, CancellationTokenSource cancellationTokenSource, Request request) Parameters Type Name Description ProxyServer server ProxyEndPoint endPoint CancellationTokenSource cancellationTokenSource Request request Fields | Improve this Doc View Source bufferPool Declaration protected readonly IBufferPool bufferPool Field Value Type Description StreamExtended.IBufferPool | Improve this Doc View Source bufferSize Declaration protected readonly int bufferSize Field Value Type Description Int32 | Improve this Doc View Source exceptionFunc Declaration protected readonly ExceptionHandler exceptionFunc Field Value Type Description ExceptionHandler Properties | Improve this Doc View Source ClientEndPoint Client End Point. Declaration public IPEndPoint ClientEndPoint { get; } Property Value Type Description IPEndPoint | Improve this Doc View Source CustomUpStreamProxyUsed Are we using a custom upstream HTTP(S) proxy? Declaration public ExternalProxy CustomUpStreamProxyUsed { get; } Property Value Type Description ExternalProxy | Improve this Doc View Source Exception The last exception that happened. Declaration public Exception Exception { get; } Property Value Type Description Exception | Improve this Doc View Source HttpClient The web client used to communicate with server for this session. Declaration public HttpWebClient HttpClient { get; } Property Value Type Description HttpWebClient | Improve this Doc View Source IsHttps Does this session uses SSL? Declaration public bool IsHttps { get; } Property Value Type Description Boolean | Improve this Doc View Source IsTransparent Is this a transparent endpoint? Declaration public bool IsTransparent { get; } Property Value Type Description Boolean | Improve this Doc View Source LocalEndPoint Local endpoint via which we make the request. Declaration public ProxyEndPoint LocalEndPoint { get; } Property Value Type Description ProxyEndPoint | Improve this Doc View Source TimeLine Relative milliseconds for various events. Declaration public Dictionary TimeLine { get; set; } Property Value Type Description Dictionary < String , DateTime > | Improve this Doc View Source UserData Returns a user data for this request/response session which is same as the user data of WebSession. Declaration public object UserData { get; set; } Property Value Type Description Object | Improve this Doc View Source WebSession Declaration [Obsolete(\"Use HttpClient instead.\")] public HttpWebClient WebSession { get; } Property Value Type Description HttpWebClient Methods | Improve this Doc View Source Dispose() Implements cleanup here. Declaration public virtual void Dispose() | Improve this Doc View Source TerminateSession() Terminates the session abruptly by terminating client/server connections. Declaration public void TerminateSession() Events | Improve this Doc View Source DataReceived Fired when data is received within this session from client/server. Declaration public event EventHandler DataReceived Event Type Type Description EventHandler < StreamExtended.Network.DataEventArgs > | Improve this Doc View Source DataSent Fired when data is sent within this session to server/client. Declaration public event EventHandler DataSent Event Type Type Description EventHandler < StreamExtended.Network.DataEventArgs > Implements System.IDisposable" }, "api/Titanium.Web.Proxy.EventArguments.TunnelConnectSessionEventArgs.html": { "href": "api/Titanium.Web.Proxy.EventArguments.TunnelConnectSessionEventArgs.html", "title": "Class TunnelConnectSessionEventArgs | Titanium Web Proxy", - "keywords": "Class TunnelConnectSessionEventArgs A class that wraps the state when a tunnel connect event happen for Explicit endpoints. Inheritance Object EventArgs SessionEventArgsBase TunnelConnectSessionEventArgs Implements IDisposable Inherited Members SessionEventArgsBase.bufferSize SessionEventArgsBase.bufferPool SessionEventArgsBase.exceptionFunc SessionEventArgsBase.TimeLine SessionEventArgsBase.UserData SessionEventArgsBase.IsHttps SessionEventArgsBase.ClientEndPoint SessionEventArgsBase.WebSession SessionEventArgsBase.CustomUpStreamProxyUsed SessionEventArgsBase.LocalEndPoint SessionEventArgsBase.IsTransparent SessionEventArgsBase.Exception SessionEventArgsBase.Dispose() SessionEventArgsBase.DataSent SessionEventArgsBase.DataReceived SessionEventArgsBase.TerminateSession() EventArgs.Empty Object.ToString() Object.Equals(Object) Object.Equals(Object, Object) Object.ReferenceEquals(Object, Object) Object.GetHashCode() Object.GetType() Object.MemberwiseClone() Namespace : Titanium.Web.Proxy.EventArguments Assembly : Titanium.Web.Proxy.dll Syntax public class TunnelConnectSessionEventArgs : SessionEventArgsBase, IDisposable Properties | Improve this Doc View Source DecryptSsl Should we decrypt the Ssl or relay it to server? Default is true. Declaration public bool DecryptSsl { get; set; } Property Value Type Description Boolean | Improve this Doc View Source DenyConnect When set to true it denies the connect request with a Forbidden status. Declaration public bool DenyConnect { get; set; } Property Value Type Description Boolean | Improve this Doc View Source IsHttpsConnect Is this a connect request to secure HTTP server? Or is it to someother protocol. Declaration public bool IsHttpsConnect { get; } Property Value Type Description Boolean Implements System.IDisposable" + "keywords": "Class TunnelConnectSessionEventArgs A class that wraps the state when a tunnel connect event happen for Explicit endpoints. Inheritance Object EventArgs SessionEventArgsBase TunnelConnectSessionEventArgs Implements IDisposable Inherited Members SessionEventArgsBase.bufferSize SessionEventArgsBase.bufferPool SessionEventArgsBase.exceptionFunc SessionEventArgsBase.TimeLine SessionEventArgsBase.UserData SessionEventArgsBase.IsHttps SessionEventArgsBase.ClientEndPoint SessionEventArgsBase.HttpClient SessionEventArgsBase.WebSession SessionEventArgsBase.CustomUpStreamProxyUsed SessionEventArgsBase.LocalEndPoint SessionEventArgsBase.IsTransparent SessionEventArgsBase.Exception SessionEventArgsBase.Dispose() SessionEventArgsBase.DataSent SessionEventArgsBase.DataReceived SessionEventArgsBase.TerminateSession() EventArgs.Empty Object.ToString() Object.Equals(Object) Object.Equals(Object, Object) Object.ReferenceEquals(Object, Object) Object.GetHashCode() Object.GetType() Object.MemberwiseClone() Namespace : Titanium.Web.Proxy.EventArguments Assembly : Titanium.Web.Proxy.dll Syntax public class TunnelConnectSessionEventArgs : SessionEventArgsBase, IDisposable Properties | Improve this Doc View Source DecryptSsl Should we decrypt the Ssl or relay it to server? Default is true. Declaration public bool DecryptSsl { get; set; } Property Value Type Description Boolean | Improve this Doc View Source DenyConnect When set to true it denies the connect request with a Forbidden status. Declaration public bool DenyConnect { get; set; } Property Value Type Description Boolean | Improve this Doc View Source IsHttpsConnect Is this a connect request to secure HTTP server? Or is it to someother protocol. Declaration public bool IsHttpsConnect { get; } Property Value Type Description Boolean Implements System.IDisposable" }, "api/Titanium.Web.Proxy.ExceptionHandler.html": { "href": "api/Titanium.Web.Proxy.ExceptionHandler.html", @@ -92,7 +92,7 @@ "api/Titanium.Web.Proxy.Helpers.RunTime.html": { "href": "api/Titanium.Web.Proxy.Helpers.RunTime.html", "title": "Class RunTime | Titanium Web Proxy", - "keywords": "Class RunTime Run time helpers Inheritance Object RunTime Inherited Members Object.ToString() Object.Equals(Object) Object.Equals(Object, Object) Object.ReferenceEquals(Object, Object) Object.GetHashCode() Object.GetType() Object.MemberwiseClone() Namespace : Titanium.Web.Proxy.Helpers Assembly : Titanium.Web.Proxy.dll Syntax public static class RunTime Properties | Improve this Doc View Source IsLinux Declaration public static bool IsLinux { get; } Property Value Type Description Boolean | Improve this Doc View Source IsMac Declaration public static bool IsMac { get; } Property Value Type Description Boolean | Improve this Doc View Source IsWindows Declaration public static bool IsWindows { get; } Property Value Type Description Boolean" + "keywords": "Class RunTime Run time helpers Inheritance Object RunTime Inherited Members Object.ToString() Object.Equals(Object) Object.Equals(Object, Object) Object.ReferenceEquals(Object, Object) Object.GetHashCode() Object.GetType() Object.MemberwiseClone() Namespace : Titanium.Web.Proxy.Helpers Assembly : Titanium.Web.Proxy.dll Syntax public static class RunTime Properties | Improve this Doc View Source IsLinux Declaration public static bool IsLinux { get; } Property Value Type Description Boolean | Improve this Doc View Source IsMac Declaration public static bool IsMac { get; } Property Value Type Description Boolean | Improve this Doc View Source IsUwpOnWindows Declaration public static bool IsUwpOnWindows { get; } Property Value Type Description Boolean | Improve this Doc View Source IsWindows Declaration public static bool IsWindows { get; } Property Value Type Description Boolean" }, "api/Titanium.Web.Proxy.html": { "href": "api/Titanium.Web.Proxy.html", diff --git a/docs/xrefmap.yml b/docs/xrefmap.yml index 119b7ae55..bfa65757b 100644 --- a/docs/xrefmap.yml +++ b/docs/xrefmap.yml @@ -592,6 +592,19 @@ references: commentId: F:Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.exceptionFunc fullName: Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.exceptionFunc nameWithType: SessionEventArgsBase.exceptionFunc +- uid: Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.HttpClient + name: HttpClient + href: api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html#Titanium_Web_Proxy_EventArguments_SessionEventArgsBase_HttpClient + commentId: P:Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.HttpClient + fullName: Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.HttpClient + nameWithType: SessionEventArgsBase.HttpClient +- uid: Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.HttpClient* + name: HttpClient + href: api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html#Titanium_Web_Proxy_EventArguments_SessionEventArgsBase_HttpClient_ + commentId: Overload:Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.HttpClient + isSpec: "True" + fullName: Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.HttpClient + nameWithType: SessionEventArgsBase.HttpClient - uid: Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.IsHttps name: IsHttps href: api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html#Titanium_Web_Proxy_EventArguments_SessionEventArgsBase_IsHttps @@ -885,6 +898,19 @@ references: isSpec: "True" fullName: Titanium.Web.Proxy.Helpers.RunTime.IsMac nameWithType: RunTime.IsMac +- uid: Titanium.Web.Proxy.Helpers.RunTime.IsUwpOnWindows + name: IsUwpOnWindows + href: api/Titanium.Web.Proxy.Helpers.RunTime.html#Titanium_Web_Proxy_Helpers_RunTime_IsUwpOnWindows + commentId: P:Titanium.Web.Proxy.Helpers.RunTime.IsUwpOnWindows + fullName: Titanium.Web.Proxy.Helpers.RunTime.IsUwpOnWindows + nameWithType: RunTime.IsUwpOnWindows +- uid: Titanium.Web.Proxy.Helpers.RunTime.IsUwpOnWindows* + name: IsUwpOnWindows + href: api/Titanium.Web.Proxy.Helpers.RunTime.html#Titanium_Web_Proxy_Helpers_RunTime_IsUwpOnWindows_ + commentId: Overload:Titanium.Web.Proxy.Helpers.RunTime.IsUwpOnWindows + isSpec: "True" + fullName: Titanium.Web.Proxy.Helpers.RunTime.IsUwpOnWindows + nameWithType: RunTime.IsUwpOnWindows - uid: Titanium.Web.Proxy.Helpers.RunTime.IsWindows name: IsWindows href: api/Titanium.Web.Proxy.Helpers.RunTime.html#Titanium_Web_Proxy_Helpers_RunTime_IsWindows From 9136f87aabf71f4c0f89005e2073d4f32edf065c Mon Sep 17 00:00:00 2001 From: justcoding121 Date: Tue, 20 Nov 2018 12:50:56 -0500 Subject: [PATCH 4/5] comments update --- README.md | 22 ++++++++-------- .../ProxyTestController.cs | 26 +++++++++---------- .../MainWindow.xaml.cs | 6 ++--- .../SessionListItem.cs | 8 +++--- .../EventArguments/SessionEventArgsBase.cs | 2 +- 5 files changed, 32 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 7d096444a..d43237cbb 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ Sample request and response event handlers private async Task OnBeforeTunnelConnectRequest(object sender, TunnelConnectSessionEventArgs e) { - string hostname = e.WebSession.Request.RequestUri.Host; + string hostname = e.HttpClient.Request.RequestUri.Host; if (hostname.Contains("dropbox.com")) { @@ -139,12 +139,12 @@ private async Task OnBeforeTunnelConnectRequest(object sender, TunnelConnectSess public async Task OnRequest(object sender, SessionEventArgs e) { - Console.WriteLine(e.WebSession.Request.Url); + Console.WriteLine(e.HttpClient.Request.Url); ////read request headers - var requestHeaders = e.WebSession.Request.RequestHeaders; + var requestHeaders = e.HttpClient.Request.RequestHeaders; - var method = e.WebSession.Request.Method.ToUpper(); + var method = e.HttpClient.Request.Method.ToUpper(); if ((method == "POST" || method == "PUT" || method == "PATCH")) { //Get/Set request body bytes @@ -157,12 +157,12 @@ public async Task OnRequest(object sender, SessionEventArgs e) //store request //so that you can find it from response handler - e.UserData = e.WebSession.Request; + e.UserData = e.HttpClient.Request; } //To cancel a request with a custom HTML content //Filter URL - if (e.WebSession.Request.RequestUri.AbsoluteUri.Contains("google.com")) + if (e.HttpClient.Request.RequestUri.AbsoluteUri.Contains("google.com")) { e.Ok("" + "

    " + @@ -173,7 +173,7 @@ public async Task OnRequest(object sender, SessionEventArgs e) ""); } //Redirect example - if (e.WebSession.Request.RequestUri.AbsoluteUri.Contains("wikipedia.org")) + if (e.HttpClient.Request.RequestUri.AbsoluteUri.Contains("wikipedia.org")) { e.Redirect("https://www.paypal.com"); } @@ -183,14 +183,14 @@ public async Task OnRequest(object sender, SessionEventArgs e) public async Task OnResponse(object sender, SessionEventArgs e) { //read response headers - var responseHeaders = e.WebSession.Response.ResponseHeaders; + var responseHeaders = e.HttpClient.Response.ResponseHeaders; //if (!e.ProxySession.Request.Host.Equals("medeczane.sgk.gov.tr")) return; - if (e.WebSession.Request.Method == "GET" || e.WebSession.Request.Method == "POST") + if (e.HttpClient.Request.Method == "GET" || e.HttpClient.Request.Method == "POST") { - if (e.WebSession.Response.ResponseStatusCode == "200") + if (e.HttpClient.Response.ResponseStatusCode == "200") { - if (e.WebSession.Response.ContentType!=null && e.WebSession.Response.ContentType.Trim().ToLower().Contains("text/html")) + if (e.HttpClient.Response.ContentType!=null && e.HttpClient.Response.ContentType.Trim().ToLower().Contains("text/html")) { byte[] bodyBytes = await e.GetResponseBody(); await e.SetResponseBody(bodyBytes); diff --git a/examples/Titanium.Web.Proxy.Examples.Basic/ProxyTestController.cs b/examples/Titanium.Web.Proxy.Examples.Basic/ProxyTestController.cs index 309aaaa04..088615c91 100644 --- a/examples/Titanium.Web.Proxy.Examples.Basic/ProxyTestController.cs +++ b/examples/Titanium.Web.Proxy.Examples.Basic/ProxyTestController.cs @@ -145,20 +145,20 @@ private async Task OnRequest(object sender, SessionEventArgs e) // It can be a simple integer, Guid, or any type //e.UserData = new CustomUserData() //{ - // RequestHeaders = e.WebSession.Request.Headers, - // RequestBody = e.WebSession.Request.HasBody ? e.WebSession.Request.Body:null, - // RequestBodyString = e.WebSession.Request.HasBody? e.WebSession.Request.BodyString:null + // RequestHeaders = e.HttpClient.Request.Headers, + // RequestBody = e.HttpClient.Request.HasBody ? e.HttpClient.Request.Body:null, + // RequestBodyString = e.HttpClient.Request.HasBody? e.HttpClient.Request.BodyString:null //}; ////This sample shows how to get the multipart form data headers - //if (e.WebSession.Request.Host == "mail.yahoo.com" && e.WebSession.Request.IsMultipartFormData) + //if (e.HttpClient.Request.Host == "mail.yahoo.com" && e.HttpClient.Request.IsMultipartFormData) //{ // e.MultipartRequestPartSent += MultipartRequestPartSent; //} // To cancel a request with a custom HTML content // Filter URL - //if (e.WebSession.Request.RequestUri.AbsoluteUri.Contains("yahoo.com")) + //if (e.HttpClient.Request.RequestUri.AbsoluteUri.Contains("yahoo.com")) //{ // e.Ok("" + // "

    " + @@ -170,7 +170,7 @@ private async Task OnRequest(object sender, SessionEventArgs e) //} ////Redirect example - //if (e.WebSession.Request.RequestUri.AbsoluteUri.Contains("wikipedia.org")) + //if (e.HttpClient.Request.RequestUri.AbsoluteUri.Contains("wikipedia.org")) //{ // e.Redirect("https://www.paypal.com"); //} @@ -194,7 +194,7 @@ private async Task OnResponse(object sender, SessionEventArgs e) string ext = System.IO.Path.GetExtension(e.HttpClient.Request.RequestUri.AbsolutePath); //access user data set in request to do something with it - //var userData = e.WebSession.UserData as CustomUserData; + //var userData = e.HttpClient.UserData as CustomUserData; //if (ext == ".gif" || ext == ".png" || ext == ".jpg") //{ @@ -207,21 +207,21 @@ private async Task OnResponse(object sender, SessionEventArgs e) // ""); // var response = new OkResponse(btBody); - // response.HttpVersion = e.WebSession.Request.HttpVersion; + // response.HttpVersion = e.HttpClient.Request.HttpVersion; // e.Respond(response); // e.TerminateServerConnection(); //} //// print out process id of current session - ////WriteToConsole($"PID: {e.WebSession.ProcessId.Value}"); + ////WriteToConsole($"PID: {e.HttpClient.ProcessId.Value}"); ////if (!e.ProxySession.Request.Host.Equals("medeczane.sgk.gov.tr")) return; - //if (e.WebSession.Request.Method == "GET" || e.WebSession.Request.Method == "POST") + //if (e.HttpClient.Request.Method == "GET" || e.HttpClient.Request.Method == "POST") //{ - // if (e.WebSession.Response.StatusCode == (int)HttpStatusCode.OK) + // if (e.HttpClient.Response.StatusCode == (int)HttpStatusCode.OK) // { - // if (e.WebSession.Response.ContentType != null && e.WebSession.Response.ContentType.Trim().ToLower().Contains("text/html")) + // if (e.HttpClient.Response.ContentType != null && e.HttpClient.Response.ContentType.Trim().ToLower().Contains("text/html")) // { // var bodyBytes = await e.GetResponseBody(); // await e.SetResponseBody(bodyBytes); @@ -283,7 +283,7 @@ private async Task WriteToConsole(string message, bool useRedColor = false) ///// ///// User data object as defined by user. - ///// User data can be set to each SessionEventArgs.WebSession.UserData property + ///// User data can be set to each SessionEventArgs.HttpClient.UserData property ///// //public class CustomUserData //{ diff --git a/examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml.cs b/examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml.cs index 9cfe1f611..6bc523859 100644 --- a/examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml.cs +++ b/examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml.cs @@ -203,7 +203,7 @@ private SessionListItem CreateSessionListItem(SessionEventArgsBase e) var item = new SessionListItem { Number = lastSessionNumber, - WebSession = e.HttpClient, + HttpClient = e.HttpClient, IsTunnelConnect = isTunnelConnect }; @@ -240,7 +240,7 @@ private void ListViewSessions_OnKeyDown(object sender, KeyEventArgs e) foreach (var item in selectedItems.Cast().ToArray()) { Sessions.Remove(item); - sessionDictionary.Remove(item.WebSession); + sessionDictionary.Remove(item.HttpClient); } } } @@ -254,7 +254,7 @@ private void SelectedSessionChanged() const int truncateLimit = 1024; - var session = SelectedSession.WebSession; + var session = SelectedSession.HttpClient; var request = session.Request; var data = (request.IsBodyRead ? request.Body : null) ?? new byte[0]; bool truncated = data.Length > truncateLimit; diff --git a/examples/Titanium.Web.Proxy.Examples.Wpf/SessionListItem.cs b/examples/Titanium.Web.Proxy.Examples.Wpf/SessionListItem.cs index daadf546e..c3f54b0fe 100644 --- a/examples/Titanium.Web.Proxy.Examples.Wpf/SessionListItem.cs +++ b/examples/Titanium.Web.Proxy.Examples.Wpf/SessionListItem.cs @@ -20,7 +20,7 @@ public class SessionListItem : INotifyPropertyChanged public int Number { get; set; } - public HttpWebClient WebSession { get; set; } + public HttpWebClient HttpClient { get; set; } public bool IsTunnelConnect { get; set; } @@ -97,8 +97,8 @@ protected virtual void OnPropertyChanged([CallerMemberName] string propertyName public void Update() { - var request = WebSession.Request; - var response = WebSession.Response; + var request = HttpClient.Request; + var response = HttpClient.Response; int statusCode = response?.StatusCode ?? 0; StatusCode = statusCode == 0 ? "-" : statusCode.ToString(); Protocol = request.RequestUri.Scheme; @@ -132,7 +132,7 @@ public void Update() BodySize = responseSize; } - Process = GetProcessDescription(WebSession.ProcessId.Value); + Process = GetProcessDescription(HttpClient.ProcessId.Value); } private string GetProcessDescription(int processId) diff --git a/src/Titanium.Web.Proxy/EventArguments/SessionEventArgsBase.cs b/src/Titanium.Web.Proxy/EventArguments/SessionEventArgsBase.cs index cb37f9260..dc627e3f6 100644 --- a/src/Titanium.Web.Proxy/EventArguments/SessionEventArgsBase.cs +++ b/src/Titanium.Web.Proxy/EventArguments/SessionEventArgsBase.cs @@ -83,7 +83,7 @@ protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint, /// /// Returns a user data for this request/response session which is - /// same as the user data of WebSession. + /// same as the user data of HttpClient. /// public object UserData { From 46b3e103cbdfe3143b89501b7d3d10862dc88a29 Mon Sep 17 00:00:00 2001 From: buildbot121 Date: Tue, 20 Nov 2018 17:53:12 +0000 Subject: [PATCH 5/5] API documentation update by build server --- .../Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html | 2 +- docs/index.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html b/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html index ca6d0491a..348c180bf 100644 --- a/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html +++ b/docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html @@ -532,7 +532,7 @@
    Property Value

    UserData

    Returns a user data for this request/response session which is -same as the user data of WebSession.

    +same as the user data of HttpClient.

    Declaration
    diff --git a/docs/index.json b/docs/index.json index dc648ef19..93e21cdc7 100644 --- a/docs/index.json +++ b/docs/index.json @@ -37,7 +37,7 @@ "api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html": { "href": "api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html", "title": "Class SessionEventArgsBase | Titanium Web Proxy", - "keywords": "Class SessionEventArgsBase Holds info related to a single proxy session (single request/response sequence). A proxy session is bounded to a single connection from client. A proxy session ends when client terminates connection to proxy or when server terminates connection from proxy. Inheritance Object EventArgs SessionEventArgsBase SessionEventArgs TunnelConnectSessionEventArgs Implements IDisposable Inherited Members EventArgs.Empty Object.ToString() Object.Equals(Object) Object.Equals(Object, Object) Object.ReferenceEquals(Object, Object) Object.GetHashCode() Object.GetType() Object.MemberwiseClone() Namespace : Titanium.Web.Proxy.EventArguments Assembly : Titanium.Web.Proxy.dll Syntax public abstract class SessionEventArgsBase : EventArgs, IDisposable Constructors | Improve this Doc View Source SessionEventArgsBase(ProxyServer, ProxyEndPoint, CancellationTokenSource, Request) Declaration protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint, CancellationTokenSource cancellationTokenSource, Request request) Parameters Type Name Description ProxyServer server ProxyEndPoint endPoint CancellationTokenSource cancellationTokenSource Request request Fields | Improve this Doc View Source bufferPool Declaration protected readonly IBufferPool bufferPool Field Value Type Description StreamExtended.IBufferPool | Improve this Doc View Source bufferSize Declaration protected readonly int bufferSize Field Value Type Description Int32 | Improve this Doc View Source exceptionFunc Declaration protected readonly ExceptionHandler exceptionFunc Field Value Type Description ExceptionHandler Properties | Improve this Doc View Source ClientEndPoint Client End Point. Declaration public IPEndPoint ClientEndPoint { get; } Property Value Type Description IPEndPoint | Improve this Doc View Source CustomUpStreamProxyUsed Are we using a custom upstream HTTP(S) proxy? Declaration public ExternalProxy CustomUpStreamProxyUsed { get; } Property Value Type Description ExternalProxy | Improve this Doc View Source Exception The last exception that happened. Declaration public Exception Exception { get; } Property Value Type Description Exception | Improve this Doc View Source HttpClient The web client used to communicate with server for this session. Declaration public HttpWebClient HttpClient { get; } Property Value Type Description HttpWebClient | Improve this Doc View Source IsHttps Does this session uses SSL? Declaration public bool IsHttps { get; } Property Value Type Description Boolean | Improve this Doc View Source IsTransparent Is this a transparent endpoint? Declaration public bool IsTransparent { get; } Property Value Type Description Boolean | Improve this Doc View Source LocalEndPoint Local endpoint via which we make the request. Declaration public ProxyEndPoint LocalEndPoint { get; } Property Value Type Description ProxyEndPoint | Improve this Doc View Source TimeLine Relative milliseconds for various events. Declaration public Dictionary TimeLine { get; set; } Property Value Type Description Dictionary < String , DateTime > | Improve this Doc View Source UserData Returns a user data for this request/response session which is same as the user data of WebSession. Declaration public object UserData { get; set; } Property Value Type Description Object | Improve this Doc View Source WebSession Declaration [Obsolete(\"Use HttpClient instead.\")] public HttpWebClient WebSession { get; } Property Value Type Description HttpWebClient Methods | Improve this Doc View Source Dispose() Implements cleanup here. Declaration public virtual void Dispose() | Improve this Doc View Source TerminateSession() Terminates the session abruptly by terminating client/server connections. Declaration public void TerminateSession() Events | Improve this Doc View Source DataReceived Fired when data is received within this session from client/server. Declaration public event EventHandler DataReceived Event Type Type Description EventHandler < StreamExtended.Network.DataEventArgs > | Improve this Doc View Source DataSent Fired when data is sent within this session to server/client. Declaration public event EventHandler DataSent Event Type Type Description EventHandler < StreamExtended.Network.DataEventArgs > Implements System.IDisposable" + "keywords": "Class SessionEventArgsBase Holds info related to a single proxy session (single request/response sequence). A proxy session is bounded to a single connection from client. A proxy session ends when client terminates connection to proxy or when server terminates connection from proxy. Inheritance Object EventArgs SessionEventArgsBase SessionEventArgs TunnelConnectSessionEventArgs Implements IDisposable Inherited Members EventArgs.Empty Object.ToString() Object.Equals(Object) Object.Equals(Object, Object) Object.ReferenceEquals(Object, Object) Object.GetHashCode() Object.GetType() Object.MemberwiseClone() Namespace : Titanium.Web.Proxy.EventArguments Assembly : Titanium.Web.Proxy.dll Syntax public abstract class SessionEventArgsBase : EventArgs, IDisposable Constructors | Improve this Doc View Source SessionEventArgsBase(ProxyServer, ProxyEndPoint, CancellationTokenSource, Request) Declaration protected SessionEventArgsBase(ProxyServer server, ProxyEndPoint endPoint, CancellationTokenSource cancellationTokenSource, Request request) Parameters Type Name Description ProxyServer server ProxyEndPoint endPoint CancellationTokenSource cancellationTokenSource Request request Fields | Improve this Doc View Source bufferPool Declaration protected readonly IBufferPool bufferPool Field Value Type Description StreamExtended.IBufferPool | Improve this Doc View Source bufferSize Declaration protected readonly int bufferSize Field Value Type Description Int32 | Improve this Doc View Source exceptionFunc Declaration protected readonly ExceptionHandler exceptionFunc Field Value Type Description ExceptionHandler Properties | Improve this Doc View Source ClientEndPoint Client End Point. Declaration public IPEndPoint ClientEndPoint { get; } Property Value Type Description IPEndPoint | Improve this Doc View Source CustomUpStreamProxyUsed Are we using a custom upstream HTTP(S) proxy? Declaration public ExternalProxy CustomUpStreamProxyUsed { get; } Property Value Type Description ExternalProxy | Improve this Doc View Source Exception The last exception that happened. Declaration public Exception Exception { get; } Property Value Type Description Exception | Improve this Doc View Source HttpClient The web client used to communicate with server for this session. Declaration public HttpWebClient HttpClient { get; } Property Value Type Description HttpWebClient | Improve this Doc View Source IsHttps Does this session uses SSL? Declaration public bool IsHttps { get; } Property Value Type Description Boolean | Improve this Doc View Source IsTransparent Is this a transparent endpoint? Declaration public bool IsTransparent { get; } Property Value Type Description Boolean | Improve this Doc View Source LocalEndPoint Local endpoint via which we make the request. Declaration public ProxyEndPoint LocalEndPoint { get; } Property Value Type Description ProxyEndPoint | Improve this Doc View Source TimeLine Relative milliseconds for various events. Declaration public Dictionary TimeLine { get; set; } Property Value Type Description Dictionary < String , DateTime > | Improve this Doc View Source UserData Returns a user data for this request/response session which is same as the user data of HttpClient. Declaration public object UserData { get; set; } Property Value Type Description Object | Improve this Doc View Source WebSession Declaration [Obsolete(\"Use HttpClient instead.\")] public HttpWebClient WebSession { get; } Property Value Type Description HttpWebClient Methods | Improve this Doc View Source Dispose() Implements cleanup here. Declaration public virtual void Dispose() | Improve this Doc View Source TerminateSession() Terminates the session abruptly by terminating client/server connections. Declaration public void TerminateSession() Events | Improve this Doc View Source DataReceived Fired when data is received within this session from client/server. Declaration public event EventHandler DataReceived Event Type Type Description EventHandler < StreamExtended.Network.DataEventArgs > | Improve this Doc View Source DataSent Fired when data is sent within this session to server/client. Declaration public event EventHandler DataSent Event Type Type Description EventHandler < StreamExtended.Network.DataEventArgs > Implements System.IDisposable" }, "api/Titanium.Web.Proxy.EventArguments.TunnelConnectSessionEventArgs.html": { "href": "api/Titanium.Web.Proxy.EventArguments.TunnelConnectSessionEventArgs.html",