.net core 拦截socket

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace WebApplication1
{
    class SocketFilterAdapter : IConnectionAdapter
    {
        public bool IsHttps => false;

        public Task<IAdaptedConnection> OnConnectionAsync(ConnectionAdapterContext context)
        {
            var connectionTransportFeature = context.Features.Get<IConnectionTransportFeature>();
            var f = connectionTransportFeature.GetType().GetField("_receiver", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var receiver = f.GetValue(connectionTransportFeature) as SocketReceiver;
            f = receiver.GetType().GetField("_socket", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var socket = (Socket)f.GetValue(receiver);

            return Task.Run<IAdaptedConnection>(()=> {
                //这里可以判断是否合格
                //byte[] bs = new byte[1024];
                //int readed = socket.Receive(bs,bs.Length, SocketFlags.Peek);
                //var text = Encoding.UTF8.GetString(bs);
                //socket.Shutdown(SocketShutdown.Both);
                //socket.Close();
                //socket.Dispose();
                //return null;
                return new AdaptedConnection(context.ConnectionStream);
            });
            
        }

        private class RewritingStream : Stream
        {
            private readonly Stream _innerStream;

            public RewritingStream(Stream innerStream)
            {
                _innerStream = innerStream;
            }

            public override bool CanRead => _innerStream.CanRead;

            public override bool CanSeek => _innerStream.CanSeek;

            public override bool CanWrite => _innerStream.CanWrite;

            public override long Length => _innerStream.Length;

            public override long Position
            {
                get
                {
                    return _innerStream.Position;
                }
                set
                {
                    _innerStream.Position = value;
                }
            }

            public override void Flush()
            {
                _innerStream.Flush();
            }

            public override Task FlushAsync(CancellationToken cancellationToken)
            {
                return _innerStream.FlushAsync(cancellationToken);
            }

            public override int Read(byte[] buffer, int offset, int count)
            {
                return _innerStream.Read(buffer, offset, count);
            }

            public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
               return _innerStream.ReadAsync(buffer, offset, count);
            }

            public override long Seek(long offset, SeekOrigin origin)
            {
                return _innerStream.Seek(offset, origin);
            }

            public override void SetLength(long value)
            {
                _innerStream.SetLength(value);
            }

            public override void Write(byte[] buffer, int offset, int count)
            {
                _innerStream.Write(buffer, offset, count);
            }

            public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                return _innerStream.WriteAsync(buffer, offset, count, cancellationToken);
            }
        }

        private class AdaptedConnection : IAdaptedConnection
        {
            public AdaptedConnection(Stream adaptedStream)
            {
                ConnectionStream = new RewritingStream(adaptedStream);
            }

            public Stream ConnectionStream { get; }

            public void Dispose()
            {
            }
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
           .UseKestrel(options =>
           {
               options.Listen(IPAddress.Any, 5000, listenOptions =>
                                {
                                    listenOptions.ConnectionAdapters.Add(new SocketFilterAdapter());


                                });
           })
                .UseStartup<Startup>();
    }
}

 

posted @ 2020-05-15 09:53  IWing  阅读(595)  评论(0编辑  收藏  举报