【fix】新增本地socks代理服务端

This commit is contained in:
wujiawei
2025-05-03 22:36:21 +08:00
parent f0fd22ccd4
commit b7f099d3a4
28 changed files with 1185 additions and 5 deletions

View File

@ -6,6 +6,7 @@ import org.framework.lazy.cloud.network.heartbeat.client.netty.permeate.event.Cl
import org.framework.lazy.cloud.network.heartbeat.client.netty.permeate.tcp.advanced.*;
import org.framework.lazy.cloud.network.heartbeat.client.netty.permeate.udp.advanced.*;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.http.advanced.*;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.advanced.*;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
@ -383,4 +384,32 @@ public class ClientAutoConfiguration {
return new ClientHandleDistributeHttpServerProxyClientTransferRequestAdvanced();
}
}
@Configuration
static class SocksProxyConfiguration {
@Bean
public NettySocketProtocolHandleSocketClientProxyServerTypeAdvanced nettySocketProtocolHandleSocketClientProxyServerTypeAdvanced() {
return new NettySocketProtocolHandleSocketClientProxyServerTypeAdvanced();
}
@Bean
public ClientHandleDistributeSocksClientProxyServerConnectionTransferSuccessfulAdvanced clientHandleDistributeSocksClientProxyServerConnectionTransferSuccessfulAdvanced() {
return new ClientHandleDistributeSocksClientProxyServerConnectionTransferSuccessfulAdvanced();
}
@Bean
public ClientHandleDistributeSocksClientProxyServerConnectionTransferFailAdvanced clientHandleDistributeSocksClientProxyServerConnectionTransferFailAdvanced() {
return new ClientHandleDistributeSocksClientProxyServerConnectionTransferFailAdvanced();
}
@Bean
public ClientHandleDistributeSocksClientProxyServerTransferTransferResponseAdvanced clientHandleDistributeSocksClientProxyServerTransferTransferResponseAdvanced() {
return new ClientHandleDistributeSocksClientProxyServerTransferTransferResponseAdvanced();
}
@Bean
public ClientHandleDistributeSocksClientProxyServerTransferCloseAdvanced clientHandleDistributeSocksClientProxyServerTransferCloseAdvanced() {
return new ClientHandleDistributeSocksClientProxyServerTransferCloseAdvanced();
}
}
}

View File

@ -12,6 +12,7 @@ import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.http.filter
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelTypeAdapter;
import org.framework.lazy.cloud.network.heartbeat.common.factory.EventLoopGroupFactory;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import java.util.concurrent.TimeUnit;
@ -21,13 +22,13 @@ import java.util.concurrent.TimeUnit;
*/
@Slf4j
public class NettyHttpClientProxyClientProxySocket {
static EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
/**
* 连接服务端通信通道
*/
public static void buildTransferServer(NettyHttpClientProxyClient nettyHttpClientProxyClient, Channel visitorChannel) {
EventLoopGroup eventLoopGroup = EventLoopGroupFactory.createClientWorkGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)

View File

@ -0,0 +1,48 @@
package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks;
import io.netty.handler.codec.socksx.v5.Socks5AddressType;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.framework.lazy.cloud.network.heartbeat.client.config.NettyClientProperties;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.HandleChannelTypeAdvanced;
import java.util.List;
/**
* 客户端代理服务端配置信息
*/
@NoArgsConstructor
@Data
public class NettySocksClientProxyServer {
/**
* 目标地址
*/
private String targetIp;
/**
* 目标端口
*/
private Integer targetPort;
/**
* 服务端地址信息
*/
private NettyClientProperties nettyClientProperties;
/**
* 通道处理器
*/
private List<HandleChannelTypeAdvanced> handleChannelTypeAdvancedList;
/**
* 是否是ssl
*/
private boolean isSsl;
/**
* 地址类型
*/
private Socks5AddressType socks5AddressType;
}

View File

@ -0,0 +1,26 @@
package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.advanced;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.proxy.socket.client.AbstractHandleSocksDistributeClientProxyServerConnectionTransferFailTypeAdvanced;
@Slf4j
public class ClientHandleDistributeSocksClientProxyServerConnectionTransferFailAdvanced extends
AbstractHandleSocksDistributeClientProxyServerConnectionTransferFailTypeAdvanced<NettyProxyMsg> {
/**
* 处理当前数据
*
* @param nettyChannelContext 当前通道
* @param nettyProxyMsg 通道数据
*/
@Override
protected void doHandler(NettyChannelContext nettyChannelContext, NettyProxyMsg nettyProxyMsg) {
// 传输通道关闭
}
}

View File

@ -0,0 +1,51 @@
package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.advanced;
import io.netty.channel.Channel;
import io.netty.handler.codec.socksx.v5.DefaultSocks5CommandResponse;
import io.netty.handler.codec.socksx.v5.Socks5AddressType;
import io.netty.handler.codec.socksx.v5.Socks5CommandRequestDecoder;
import io.netty.handler.codec.socksx.v5.Socks5CommandStatus;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.handler.NettyClientProxyServerVisitorInboundHandler;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.proxy.socket.client.AbstractHandleSocksDistributeClientProxyServerConnectionTransferSuccessTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.decoder.TransferDecoder;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import org.framework.lazy.cloud.network.heartbeat.protocol.handler.NettySocks5CommandRequestHandler;
@Slf4j
public class ClientHandleDistributeSocksClientProxyServerConnectionTransferSuccessfulAdvanced extends
AbstractHandleSocksDistributeClientProxyServerConnectionTransferSuccessTypeAdvanced<NettyProxyMsg> {
/**
* 处理当前数据
*
* @param nettyChannelContext 当前通道
* @param nettyProxyMsg 通道数据
*/
@Override
protected void doHandler(NettyChannelContext nettyChannelContext, NettyProxyMsg nettyProxyMsg) {
// 传输通道
Channel transferChannel = nettyChannelContext.channel();
// 根据传输通道获取代理通道
Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(transferChannel);
Byte socks5AddressTypeByte = ChannelAttributeKeyUtils.getSocks5AddressType(nextChannel);
Socks5AddressType socks5AddressType = Socks5AddressType.valueOf(socks5AddressTypeByte);
//添加客户端转发请求到服务端的Handler
// TODO bug fix
nextChannel.pipeline().addLast(new TransferDecoder(Integer.MAX_VALUE, 1024 * 1024*10));
// 请求数据开始上报
nextChannel.pipeline().addLast(new NettyClientProxyServerVisitorInboundHandler(transferChannel));
DefaultSocks5CommandResponse commandResponse =
new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS, socks5AddressType);
nextChannel.writeAndFlush(commandResponse);
nextChannel.pipeline().remove(NettySocks5CommandRequestHandler.class);
nextChannel.pipeline().remove(Socks5CommandRequestDecoder.class);
}
}

View File

@ -0,0 +1,25 @@
package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.advanced;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.proxy.socket.client.AbstractHandleSocksDistributeClientProxyServerTransferCloseTypeAdvanced;
@Slf4j
public class ClientHandleDistributeSocksClientProxyServerTransferCloseAdvanced extends
AbstractHandleSocksDistributeClientProxyServerTransferCloseTypeAdvanced<NettyProxyMsg> {
/**
* 处理当前数据
*
* @param nettyChannelContext 当前通道
* @param nettyProxyMsg 通道数据
*/
@Override
protected void doHandler(NettyChannelContext nettyChannelContext, NettyProxyMsg nettyProxyMsg) {
}
}

View File

@ -0,0 +1,38 @@
package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.advanced;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.proxy.socket.client.AbstractHandleSocksDistributeClientProxyServerTransferResponseTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import org.wu.framework.core.utils.ObjectUtils;
@Slf4j
public class ClientHandleDistributeSocksClientProxyServerTransferTransferResponseAdvanced extends
AbstractHandleSocksDistributeClientProxyServerTransferResponseTypeAdvanced<NettyProxyMsg> {
/**
* 处理当前数据
*
* @param nettyChannelContext 当前通道
* @param nettyProxyMsg 通道数据
*/
@Override
protected void doHandler(NettyChannelContext nettyChannelContext, NettyProxyMsg nettyProxyMsg) {
// 数据直接下发
Channel channel = nettyChannelContext.channel();
Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(channel);
if(ObjectUtils.isNotEmpty(nextChannel)&&nextChannel.isActive()){
ByteBuf buf = nextChannel.config().getAllocator().buffer(nettyProxyMsg.getData().length);
buf.writeBytes(nettyProxyMsg.getData());
nextChannel.writeAndFlush(buf);
}else {
log.error("客户端代理服务端socks本地通道已关闭");
}
}
}

View File

@ -0,0 +1,75 @@
package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.advanced;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.socksx.v5.DefaultSocks5CommandResponse;
import io.netty.handler.codec.socksx.v5.Socks5AddressType;
import io.netty.handler.codec.socksx.v5.Socks5CommandRequestDecoder;
import io.netty.handler.codec.socksx.v5.Socks5CommandStatus;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.client.config.NettyClientProperties;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.NettySocksClientProxyServer;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.socket.NettySocksClientProxyServerSocket;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.HandleChannelTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettySocketChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.proxy.socket.client.AbstractHandleSocketClientProxyServerTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.factory.EventLoopGroupFactory;
import org.framework.lazy.cloud.network.heartbeat.protocol.handler.NettyProxy2RealInboundHandler;
import org.framework.lazy.cloud.network.heartbeat.protocol.handler.NettySocketBackendHandler;
import org.framework.lazy.cloud.network.heartbeat.protocol.handler.NettySocks5CommandRequestHandler;
import org.springframework.stereotype.Component;
import org.wu.framework.spring.utils.SpringContextHolder;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Component
public class NettySocketProtocolHandleSocketClientProxyServerTypeAdvanced
extends AbstractHandleSocketClientProxyServerTypeAdvanced<NettyProxyMsg> {
/**
* 处理当前数据
*
* @param nettyChannelContext 当前通道
* @param nettyProxyMsg 通道数据
*/
@Override
protected void doHandler(NettyChannelContext nettyChannelContext, NettyProxyMsg nettyProxyMsg) {
NettySocketChannelContext nettySocketChannelContext = (NettySocketChannelContext) nettyChannelContext;
Channel channel = nettySocketChannelContext.channel();
ChannelHandlerContext channelHandlerContext = nettySocketChannelContext.channelHandlerContext();
EventLoopGroup group = EventLoopGroupFactory.createClientWorkGroup();
String host = nettyProxyMsg.getTargetIpString();
Integer port = Integer.parseInt(nettyProxyMsg.getTargetPortString());
Bootstrap b = new Bootstrap();
Socks5AddressType socks5AddressType = nettySocketChannelContext.getSocks5AddressType();
List<HandleChannelTypeAdvanced> handleChannelTypeAdvancedList = new ArrayList<>(SpringContextHolder.getApplicationContext().getBeansOfType(HandleChannelTypeAdvanced.class).values());
NettyClientProperties nettyClientProperties = SpringContextHolder.getBean(NettyClientProperties.class);
NettySocksClientProxyServer nettySocksClientProxyServer = new NettySocksClientProxyServer();
nettySocksClientProxyServer.setSsl(false);
nettySocksClientProxyServer.setTargetIp(host);
nettySocksClientProxyServer.setTargetPort(Integer.parseInt(String.valueOf(port)));
nettySocksClientProxyServer.setSocks5AddressType(socks5AddressType);
nettySocksClientProxyServer.setHandleChannelTypeAdvancedList(handleChannelTypeAdvancedList);
nettySocksClientProxyServer.setNettyClientProperties(nettyClientProperties);
// 创建连接
NettySocksClientProxyServerSocket.buildTransferServer(nettySocksClientProxyServer, channel);
}
}

View File

@ -0,0 +1,43 @@
package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.filter;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.handler.NettySocksClientProxyServerTransferHandler;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelTypeAdapter;
import org.framework.lazy.cloud.network.heartbeat.common.decoder.NettyProxyMsgDecoder;
import org.framework.lazy.cloud.network.heartbeat.common.encoder.NettyProxyMsgEncoder;
import org.framework.lazy.cloud.network.heartbeat.common.filter.DebugChannelInitializer;
/**
* netty 客户端代理服务端数据传输通道
*/
public class NettySocksClientProxyServerTransferFilter extends DebugChannelInitializer<SocketChannel> {
private final ChannelTypeAdapter channelTypeAdapter;
public NettySocksClientProxyServerTransferFilter(ChannelTypeAdapter channelTypeAdapter) {
this.channelTypeAdapter = channelTypeAdapter;
}
/**
* This method will be called once the {@link Channel} was registered. After the method returns this instance
* will be removed from the {@link ChannelPipeline} of the {@link Channel}.
*
* @param ch the {@link Channel} which was registered.
* @throws Exception is thrown if an error occurs. In that case it will be handled by
* {@link #exceptionCaught(ChannelHandlerContext, Throwable)} which will by default connectionClose
* the {@link Channel}.
*/
@Override
protected void initChannel0(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// 解码、编码
pipeline.addLast(new IdleStateHandler(0, 4, 0));
pipeline.addLast(new NettyProxyMsgDecoder(Integer.MAX_VALUE, 0, 4, -4, 0));
pipeline.addLast(new NettyProxyMsgEncoder());
pipeline.addLast(new NettySocksClientProxyServerTransferHandler(channelTypeAdapter));
}
}

View File

@ -0,0 +1,73 @@
package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.handler;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.NettyByteBuf;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
@Slf4j
public class NettyClientProxyServerVisitorInboundHandler extends SimpleChannelInboundHandler<NettyByteBuf> {
private final Channel transferChannel;
public NettyClientProxyServerVisitorInboundHandler(Channel transferChannel) {
this.transferChannel = transferChannel;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
}
@Override
public void channelRead0(ChannelHandlerContext ctx, NettyByteBuf nettyByteBuf) throws Exception {
log.info("转发客户端的请求到代理服务器");
// 结果下发
Channel channel = ctx.channel();
byte[] bytes = nettyByteBuf.getData();
log.debug("bytes.length:{}",bytes.length);
log.debug("客户端代理服务端,本地接收请求数据:{}", new String(bytes));
Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(channel);
if (nextChannel.isActive()) {
// 上传数据到服务端
NettyProxyMsg nettyProxyMsg = new NettyProxyMsg();
nettyProxyMsg.setType(ProxyMessageType.SOCKS_REPORT_CLIENT_PROXY_SERVER_TRANSFER_REQUEST_);
nettyProxyMsg.setData(nettyByteBuf.getData());
nextChannel.writeAndFlush(nettyProxyMsg);
} else {
log.info("释放内存");
ReferenceCountUtil.release(nettyByteBuf);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
log.info("客户端与代理服务器的连接已经断开,即将断开代理服务器和目标服务器的连接");
Channel channel = ctx.channel();
Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(channel);
if (nextChannel.isActive()) {
// 上报断开链接
NettyProxyMsg nettyProxyMsgTransferClose = new NettyProxyMsg();
nettyProxyMsgTransferClose.setType(ProxyMessageType.SOCKS_REPORT_CLIENT_PROXY_SERVER_TRANSFER_CLOSE_);
nextChannel.writeAndFlush(nettyProxyMsgTransferClose);
if (ctx.channel().isActive()) {
ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("NettyClientProxyServerVisitorInboundHandler exception", cause);
ctx.close();
}
}

View File

@ -0,0 +1,70 @@
package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.handler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelTypeAdapter;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
/**
* 客户端访客通信通道 处理器
*/
@Slf4j
public class NettySocksClientProxyServerTransferHandler extends SimpleChannelInboundHandler<NettyProxyMsg> {
private final ChannelTypeAdapter channelTypeAdapter;
public NettySocksClientProxyServerTransferHandler(ChannelTypeAdapter channelTypeAdapter) {
this.channelTypeAdapter = channelTypeAdapter;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
}
@Override
public void channelRead0(ChannelHandlerContext ctx, NettyProxyMsg nettyProxyMsg) throws Exception {
Channel channel = ctx.channel();
channelTypeAdapter.handler(ctx, nettyProxyMsg);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
String clientId = ChannelAttributeKeyUtils.getClientId(ctx.channel());
String visitorId = ChannelAttributeKeyUtils.getVisitorId(ctx.channel());
// 关闭访客
Channel nextChannel = ChannelAttributeKeyUtils.getNextChannel(ctx.channel());
if (nextChannel != null) {
// 上报关闭这个客户端的访客通道
NettyProxyMsg closeVisitorMsg = new NettyProxyMsg();
closeVisitorMsg.setType(ProxyMessageType.SOCKS_REPORT_CLIENT_PROXY_SERVER_TRANSFER_CLOSE_);
closeVisitorMsg.setVisitorId(visitorId);
nextChannel.writeAndFlush(closeVisitorMsg);
}
super.channelInactive(ctx);
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
if (ctx.channel().isWritable()) {
log.debug("Channel is writable again");
// 恢复之前暂停的操作,如写入数据
} else {
log.debug("Channel is not writable");
// 暂停写入操作,等待可写状态
}
log.info("channelWritabilityChanged!");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}

View File

@ -0,0 +1,98 @@
package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.socket;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.socksx.v5.Socks5AddressType;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.client.config.NettyClientProperties;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.NettySocksClientProxyServer;
import org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.filter.NettySocksClientProxyServerTransferFilter;
import org.framework.lazy.cloud.network.heartbeat.common.adapter.ChannelTypeAdapter;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.factory.EventLoopGroupFactory;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import java.util.concurrent.TimeUnit;
/**
* 客户端代理服务端
*/
@Slf4j
public class NettySocksClientProxyServerSocket {
/**
* 连接服务端通信通道
*/
public static void buildTransferServer(NettySocksClientProxyServer nettySocksClientProxyServer, Channel visitorChannel) {
EventLoopGroup eventLoopGroup = EventLoopGroupFactory.createClientWorkGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
// 设置读缓冲区为2M
.option(ChannelOption.SO_RCVBUF, 2048 * 1024)
// 设置写缓冲区为1M
.option(ChannelOption.SO_SNDBUF, 1024 * 1024)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000 * 60)//连接超时时间设置为 60 秒
.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 1024 * 1024 * 2))
.handler(new NettySocksClientProxyServerTransferFilter(new ChannelTypeAdapter(nettySocksClientProxyServer.getHandleChannelTypeAdvancedList())))
;
NettyClientProperties nettyClientProperties = nettySocksClientProxyServer.getNettyClientProperties();
String inetHost = nettyClientProperties.getInetHost();
int inetPort = nettyClientProperties.getInetPort();
// local client id
String clientId = nettyClientProperties.getClientId();
String targetIp = nettySocksClientProxyServer.getTargetIp();
Integer targetPort = nettySocksClientProxyServer.getTargetPort();
Socks5AddressType socks5AddressType = nettySocksClientProxyServer.getSocks5AddressType();
byte socks5AddressTypeByteValue = socks5AddressType.byteValue();
String visitorId = ChannelAttributeKeyUtils.getVisitorId(visitorChannel);
// 客户端链接服务端
log.info("Client creates a new proxy channel to connect to server IP: {}, connecting to server port: {} with clientId:【{}】 & visitorId:【{}】",
inetHost, inetPort, clientId, visitorId);
ChannelFuture future = bootstrap.connect(inetHost, inetPort);
// 使用的客户端ID:{}
future.addListener((ChannelFutureListener) futureListener -> {
Channel transferChannel = futureListener.channel();
if (futureListener.isSuccess()) {
NettyProxyMsg nettyProxyMsg = new NettyProxyMsg();
nettyProxyMsg.setType(ProxyMessageType.SOCKS_REPORT_CLIENT_PROXY_SERVER_TRANSFER_CONNECTION_);
// other clientId
nettyProxyMsg.setClientTargetIp(targetIp);
nettyProxyMsg.setClientTargetPort(targetPort);
nettyProxyMsg.setVisitorId(visitorId);
nettyProxyMsg.setData(new byte[]{socks5AddressTypeByteValue});
transferChannel.writeAndFlush(nettyProxyMsg);
// 绑定客户端真实通信通道
ChannelAttributeKeyUtils.buildVisitorId(transferChannel, visitorId);
ChannelAttributeKeyUtils.buildClientId(transferChannel, clientId);
// 传输通道
ChannelAttributeKeyUtils.buildNextChannel(visitorChannel, transferChannel);
ChannelAttributeKeyUtils.buildNextChannel(transferChannel, visitorChannel);
} else {
log.info("无法连接到服务端....");
eventLoopGroup.schedule(() -> {
try {
buildTransferServer(nettySocksClientProxyServer, visitorChannel);
} catch (Exception e) {
e.printStackTrace();
}
}, 2, TimeUnit.SECONDS);
}
});
}
}