Skip to content
This repository was archived by the owner on Jul 9, 2023. It is now read-only.

Commit d90adbb

Browse files
committed
various fixes
1 parent 17a4efe commit d90adbb

File tree

16 files changed

+272
-66
lines changed

16 files changed

+272
-66
lines changed

examples/Titanium.Web.Proxy.Examples.Basic/ProxyTestController.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ public void Stop()
119119
private async Task onBeforeTunnelConnectRequest(object sender, TunnelConnectSessionEventArgs e)
120120
{
121121
string hostname = e.HttpClient.Request.RequestUri.Host;
122-
await writeToConsole("Tunnel to: " + hostname);
122+
//await writeToConsole("Tunnel to: " + hostname);
123123

124124
if (hostname.Contains("dropbox.com"))
125125
{
@@ -138,8 +138,8 @@ private Task onBeforeTunnelConnectResponse(object sender, TunnelConnectSessionEv
138138
// intecept & cancel redirect or update requests
139139
private async Task onRequest(object sender, SessionEventArgs e)
140140
{
141-
await writeToConsole("Active Client Connections:" + ((ProxyServer)sender).ClientConnectionCount);
142-
await writeToConsole(e.HttpClient.Request.Url);
141+
//await writeToConsole("Active Client Connections:" + ((ProxyServer)sender).ClientConnectionCount);
142+
//await writeToConsole(e.HttpClient.Request.Url);
143143

144144
// store it in the UserData property
145145
// It can be a simple integer, Guid, or any type
@@ -189,7 +189,7 @@ private async Task multipartRequestPartSent(object sender, MultipartRequestPartS
189189

190190
private async Task onResponse(object sender, SessionEventArgs e)
191191
{
192-
await writeToConsole("Active Server Connections:" + ((ProxyServer)sender).ServerConnectionCount);
192+
//await writeToConsole("Active Server Connections:" + ((ProxyServer)sender).ServerConnectionCount);
193193

194194
string ext = System.IO.Path.GetExtension(e.HttpClient.Request.RequestUri.AbsolutePath);
195195

examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
</TabItem>
5555
</TabControl>
5656
<StackPanel Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="3" Orientation="Horizontal">
57+
<ToggleButton IsChecked="True" Content="On/Off" Click="ButtonProxyOnOff_OnClick" />
5758
<TextBlock Text="ClientConnectionCount:" />
5859
<TextBlock Text="{Binding ClientConnectionCount}" Margin="10,0,20,0" />
5960
<TextBlock Text="ServerConnectionCount:" />

examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml.cs

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using System.Threading.Tasks;
99
using System.Windows;
1010
using System.Windows.Controls;
11+
using System.Windows.Controls.Primitives;
1112
using System.Windows.Input;
1213
using System.Windows.Media.Imaging;
1314
using Titanium.Web.Proxy.EventArguments;
@@ -95,7 +96,7 @@ public MainWindow()
9596
Dispatcher.Invoke(() => { ServerConnectionCount = proxyServer.ServerConnectionCount; });
9697
};
9798
proxyServer.Start();
98-
99+
99100
proxyServer.SetAsSystemProxy(explicitEndPoint, ProxyProtocolType.AllHttp);
100101

101102
InitializeComponent();
@@ -284,30 +285,44 @@ private void ListViewSessions_OnKeyDown(object sender, KeyEventArgs e)
284285
{
285286
if (e.Key == Key.Delete)
286287
{
288+
bool isSelected = false;
287289
var selectedItems = ((ListView)sender).SelectedItems;
288290
Sessions.SuppressNotification = true;
289291
foreach (var item in selectedItems.Cast<SessionListItem>().ToArray())
290292
{
293+
if (item == SelectedSession)
294+
{
295+
isSelected = true;
296+
}
297+
291298
Sessions.Remove(item);
292299
sessionDictionary.Remove(item.HttpClient);
293300
}
294301

295302
Sessions.SuppressNotification = false;
303+
304+
if (isSelected)
305+
{
306+
SelectedSession = null;
307+
}
296308
}
297309
}
298310

299311
private void selectedSessionChanged()
300312
{
301313
if (SelectedSession == null)
302314
{
315+
TextBoxRequest.Text = null;
316+
TextBoxResponse.Text = string.Empty;
317+
ImageResponse.Source = null;
303318
return;
304319
}
305320

306321
const int truncateLimit = 1024;
307322

308323
var session = SelectedSession.HttpClient;
309324
var request = session.Request;
310-
var fullData = (request.IsBodyRead ? request.Body : null) ?? new byte[0];
325+
var fullData = (request.IsBodyRead ? request.Body : null) ?? Array.Empty<byte>();
311326
var data = fullData;
312327
bool truncated = data.Length > truncateLimit;
313328
if (truncated)
@@ -324,7 +339,7 @@ private void selectedSessionChanged()
324339
TextBoxRequest.Text = sb.ToString();
325340

326341
var response = session.Response;
327-
fullData = (response.IsBodyRead ? response.Body : null) ?? new byte[0];
342+
fullData = (response.IsBodyRead ? response.Body : null) ?? Array.Empty<byte>();
328343
data = fullData;
329344
truncated = data.Length > truncateLimit;
330345
if (truncated)
@@ -348,16 +363,33 @@ private void selectedSessionChanged()
348363

349364
try
350365
{
351-
using (MemoryStream stream = new MemoryStream(fullData))
366+
if (fullData.Length > 0)
352367
{
353-
ImageResponse.Source =
354-
BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
368+
using (var stream = new MemoryStream(fullData))
369+
{
370+
ImageResponse.Source =
371+
BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
372+
}
355373
}
356374
}
357375
catch
358376
{
359377
ImageResponse.Source = null;
360378
}
361379
}
380+
381+
private void ButtonProxyOnOff_OnClick(object sender, RoutedEventArgs e)
382+
{
383+
var button = (ToggleButton)sender;
384+
if (button.IsChecked == true)
385+
{
386+
proxyServer.SetAsSystemProxy((ExplicitProxyEndPoint)proxyServer.ProxyEndPoints[0],
387+
ProxyProtocolType.AllHttp);
388+
}
389+
else
390+
{
391+
proxyServer.RestoreOriginalProxySettings();
392+
}
393+
}
362394
}
363395
}

src/Titanium.Web.Proxy/ExplicitClientHandler.cs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,8 @@ await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response,
265265

266266
try
267267
{
268-
await clientStream.ReadAsync(data, 0, available, cancellationToken);
269268
// clientStream.Available should be at most BufferSize because it is using the same buffer size
269+
await clientStream.ReadAsync(data, 0, available, cancellationToken);
270270
await connection.StreamWriter.WriteAsync(data, 0, available, true, cancellationToken);
271271
}
272272
finally
@@ -279,10 +279,13 @@ await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response,
279279
((ConnectResponse)connectArgs.HttpClient.Response).ServerHelloInfo = serverHelloInfo;
280280
}
281281

282-
await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool, BufferSize,
283-
(buffer, offset, count) => { connectArgs.OnDataSent(buffer, offset, count); },
284-
(buffer, offset, count) => { connectArgs.OnDataReceived(buffer, offset, count); },
285-
connectArgs.CancellationTokenSource, ExceptionFunc);
282+
if (!clientStream.IsClosed && !connection.Stream.IsClosed)
283+
{
284+
await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool, BufferSize,
285+
(buffer, offset, count) => { connectArgs.OnDataSent(buffer, offset, count); },
286+
(buffer, offset, count) => { connectArgs.OnDataReceived(buffer, offset, count); },
287+
connectArgs.CancellationTokenSource, ExceptionFunc);
288+
}
286289
}
287290
finally
288291
{

src/Titanium.Web.Proxy/Network/Tcp/TcpConnectionFactory.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,7 @@ private async Task clearOutdatedConnections()
481481
{
482482
try
483483
{
484+
var cutOff = DateTime.Now.AddSeconds(-1 * Server.ConnectionTimeOutSeconds);
484485
foreach (var item in cache)
485486
{
486487
var queue = item.Value;
@@ -489,7 +490,6 @@ private async Task clearOutdatedConnections()
489490
{
490491
if (queue.TryDequeue(out var connection))
491492
{
492-
var cutOff = DateTime.Now.AddSeconds(-1 * Server.ConnectionTimeOutSeconds);
493493
if (!Server.EnableConnectionPool
494494
|| connection.LastAccess < cutOff)
495495
{
@@ -512,7 +512,7 @@ private async Task clearOutdatedConnections()
512512
var emptyKeys = cache.Where(x => x.Value.Count == 0).Select(x => x.Key).ToList();
513513
foreach (string key in emptyKeys)
514514
{
515-
cache.TryRemove(key, out var _);
515+
cache.TryRemove(key, out _);
516516
}
517517
}
518518
finally

src/Titanium.Web.Proxy/ProxyServer.cs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,20 @@ public void DisableSystemHttpsProxy()
516516
DisableSystemProxy(ProxyProtocolType.Https);
517517
}
518518

519+
/// <summary>
520+
/// Restores the original proxy settings.
521+
/// </summary>
522+
public void RestoreOriginalProxySettings()
523+
{
524+
if (!RunTime.IsWindows)
525+
{
526+
throw new NotSupportedException(@"Setting system proxy settings are only supported in Windows.
527+
Please manually configure your operating system to use this proxy's port and address.");
528+
}
529+
530+
systemProxySettingsManager.RestoreOriginalSettings();
531+
}
532+
519533
/// <summary>
520534
/// Clear the specified proxy setting for current machine.
521535
/// </summary>
@@ -524,7 +538,7 @@ public void DisableSystemProxy(ProxyProtocolType protocolType)
524538
if (!RunTime.IsWindows)
525539
{
526540
throw new NotSupportedException(@"Setting system proxy settings are only supported in Windows.
527-
Please manually confugure you operating system to use this proxy's port and address.");
541+
Please manually configure your operating system to use this proxy's port and address.");
528542
}
529543

530544
systemProxySettingsManager.RemoveProxy(protocolType);

src/Titanium.Web.Proxy/RequestHandler.cs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ private async Task handleHttpSessionRequest(ProxyEndPoint endPoint, TcpClientCon
6565
// (assuming HTTP connection is kept alive by client)
6666
while (true)
6767
{
68+
if (clientStream.IsClosed)
69+
{
70+
return;
71+
}
72+
6873
// read the request line
6974
string httpCmd = await clientStream.ReadLineAsync(cancellationToken);
7075

@@ -255,11 +260,11 @@ await clientStreamWriter.WriteResponseAsync(args.HttpClient.Response,
255260
throw new Exception("Session was terminated by user.");
256261
}
257262

258-
//Release server connection for each HTTP session instead of per client connection.
259-
//This will be more efficient especially when client is idly holding server connection
260-
//between sessions without using it.
261-
//Do not release authenticated connections for performance reasons.
262-
//Otherwise it will keep authenticating per session.
263+
// Release server connection for each HTTP session instead of per client connection.
264+
// This will be more efficient especially when client is idly holding server connection
265+
// between sessions without using it.
266+
// Do not release authenticated connections for performance reasons.
267+
// Otherwise it will keep authenticating per session.
263268
if (EnableConnectionPool && connection != null
264269
&& !connection.IsWinAuthenticated)
265270
{
Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using System.Collections.Concurrent;
1+
using System.Buffers;
2+
using System.Collections.Concurrent;
23

34
namespace Titanium.Web.Proxy.StreamExtended.BufferPool
45
{
@@ -10,21 +11,14 @@ namespace Titanium.Web.Proxy.StreamExtended.BufferPool
1011
/// </summary>
1112
public class DefaultBufferPool : IBufferPool
1213
{
13-
private readonly ConcurrentStack<byte[]> buffers = new ConcurrentStack<byte[]>();
14-
1514
/// <summary>
1615
/// Gets a buffer.
1716
/// </summary>
1817
/// <param name="bufferSize">Size of the buffer.</param>
1918
/// <returns></returns>
2019
public byte[] GetBuffer(int bufferSize)
2120
{
22-
if (!buffers.TryPop(out var buffer) || buffer.Length != bufferSize)
23-
{
24-
buffer = new byte[bufferSize];
25-
}
26-
27-
return buffer;
21+
return ArrayPool<byte>.Shared.Rent(bufferSize);
2822
}
2923

3024
/// <summary>
@@ -33,15 +27,11 @@ public byte[] GetBuffer(int bufferSize)
3327
/// <param name="buffer">The buffer.</param>
3428
public void ReturnBuffer(byte[] buffer)
3529
{
36-
if (buffer != null)
37-
{
38-
buffers.Push(buffer);
39-
}
30+
ArrayPool<byte>.Shared.Return(buffer);
4031
}
4132

4233
public void Dispose()
4334
{
44-
buffers.Clear();
4535
}
4636
}
4737
}

src/Titanium.Web.Proxy/StreamExtended/BufferPool/IBufferPool.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ namespace Titanium.Web.Proxy.StreamExtended.BufferPool
99
public interface IBufferPool : IDisposable
1010
{
1111
byte[] GetBuffer(int bufferSize);
12+
1213
void ReturnBuffer(byte[] buffer);
1314
}
1415
}

0 commit comments

Comments
 (0)