justcoding121 / titanium-web-proxy

A cross-platform asynchronous HTTP(S) proxy server in C#.
MIT License
1.93k stars 618 forks source link

e.Buffer includes old data. #748

Closed iron2han closed 4 years ago

iron2han commented 4 years ago

I need to get some WebSocket data, but the old data always shows up in “DataReceived”. which has never appeared before in other WebSocket connections. I suspect it is a bug.

` public Form1() { InitializeComponent();

        _proxy = new ProxyServer
        {
            ForwardToUpstreamGateway = true
        };

        var explicitEndPoint = new ExplicitProxyEndPoint(IPAddress.Any, 8000);
        explicitEndPoint.BeforeTunnelConnectRequest += ExplicitEndPoint_BeforeTunnelConnectRequest;
        _proxy.AddEndPoint(explicitEndPoint);
        _proxy.BeforeResponse += Proxy_BeforeResponse;

        _proxy.Start();

        // proxy.SetAsSystemProxy(explicitEndPoint, ProxyProtocolType.AllHttp);
    }

    private readonly ProxyServer _proxy;

    private async Task Proxy_BeforeResponse(object sender, SessionEventArgs e)
    {
        if (e.HttpClient.ConnectRequest?.TunnelType == TunnelType.Websocket)
        {
            e.DataReceived += E_DataReceived;
        }
    }

    private void E_DataReceived(object sender, DataEventArgs e)
    {
        var args = (SessionEventArgs)sender;
        foreach (var frame in args.WebSocketDecoder.Decode(e.Buffer, e.Offset, e.Count))
        {
            if (frame.OpCode == WebsocketOpCode.Text)
            {
                var request = args.HttpClient.Request;
                var text = frame.GetText();
                Console.WriteLine(text);
                /* Data handler */
            }
        }
    }

`

honfika commented 4 years ago

Which old data? how to reproduce the bug? is there a public website?

honfika commented 4 years ago

Anyway, the "e.Buffer includes old data" is true and it is not a bug. You should use the e.Offset and e.Count parameters.

so e.Buffer contains new and valid data only from position e.Offset... and contains e.Count valid bytes.

iron2han commented 4 years ago

Ok, I just saw. Is this a feature? This problem didn’t appear when I test other WebSocket connections, thus I suspect it’s a bug. Thanks for replying.

honfika commented 4 years ago

Yes, the buffer comes from a bufferpool (official System.Buffer.ArrayPool). which can contain memory garbage.

iron2han commented 4 years ago

Includes old frame data in the results of "args.WebSocketDecoder.Decode()". It is also normal?

code (reference example "ProxyTestController.cs"): 2

output window: 1

firefox network debug 3

honfika commented 4 years ago

No, that is not normal... I've fixed it Please try the latest nuget package (3.1.1288)

iron2han commented 4 years ago

It is normally working.

honfika commented 4 years ago

Ok, then I close this issue. feel free to reopen if needed.