Compare commits

..
2 Commits
Author SHA1 Message Date
aoshiguchen 40b7c3444d Merge branch 'gitcode_master' into gitcode_dev 2025-10-20 22:41:59 +08:00
aoshiguchen a55702f4f1 更新README.md 2025-10-20 15:35:02 +08:00
49 changed files with 239 additions and 1168 deletions
+7 -14
View File
@@ -13,43 +13,36 @@
</p>
# 1、简介
- 中微子代理(neutrino-proxy)是一个基于netty的、开源的java内网穿透项目。
- 中微子代理(neutrino-proxy)是一个基于netty的、开源的java代理项目。
- 技术栈:Solon、MybatisPlus、Netty
- 遵循MIT许可,因此您可以对它进行复制、修改、传播并用于任何个人或商业行为。
- 官网地址:https://neutrino-proxy-docs.asgc.fun
- 官网地址1https://neutrino-proxy.dromara.org
- 快速上手请[点击这里](https://neutrino-proxy.dromara.org/neutrino-proxy/pages/793dcb/)
# 2、名称由来
中微子,是轻子的一种,是组成自然界的最基本的粒子之一。它十分微小、不带电,可自由穿过地球,以接近光速运动,与其他物质的相互作用十分微弱,号称宇宙间的“隐身人”。
中微子是宇宙中穿透能力最强的物质,只有粒子之间的间隙小于10的负19次方米时,才能够阻挡住中微子。
因此以中微子命名,寓意着中微子代理拥有中微子"安全"、"快速"、"穿透力强"的特点。
# 3、部署方式
# 2、部署方式
- 1、[使用宝塔面板](https://neutrino-proxy.dromara.org/pages/9e0fde/)
- 2、[使用jar文件](https://neutrino-proxy.dromara.org/pages/eebea1/)
- 3、[使用Docker](https://neutrino-proxy.dromara.org/pages/5b9bef/)
- 4、[原生部署](https://neutrino-proxy.dromara.org/pages/69699a/)
- 5、[使用Docker-Compose](https://neutrino-proxy.dromara.org/pages/2d4123/)
# 4、运行示例
# 3、运行示例
![首页](assets/run-example/home.png)
![用户管理](assets/run-example/user-manager1.png)
![端口池管理](assets/run-example/port-pool1.png)
![License管理](assets/run-example/license1.png)
![端口映射管理](assets/run-example/port-mapping1.png)
# 5、代理示意图
# 4、代理示意图
![代理流程](assets/design/neutrino-proxy-process.jpg)
# 6、联系我们
# 5、联系我们
- 微信: yuyunshize
- GitCodehttps://gitcode.com/dromara/neutrino-proxy
- Gitee: https://gitee.com/asgc/neutrino-proxy
- Github仓库:https://github.com/dromara/neutrino-proxy
# 7、贡献者列表
# 6、贡献者列表
<p>
<a href="https://gitee.com/zcans" target="_blank">
<img src="assets/developer/zcans.png" width="11%">
@@ -51,18 +51,9 @@
</el-table-column>
<el-table-column align="center" :label="$t('table.domainName')" width="190">
<template slot-scope="scope">
<el-dropdown v-if="scope.row.allFullDomainList" @command="handleCopy">
<span class="el-dropdown-link">
{{ scope.row.allFullDomainList[0] }}<i v-if="scope.row.allFullDomainList.length > 1" class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item v-for="(domain, index) in scope.row.allFullDomainList" :command="domain">{{ domain }}</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<div v-if="!scope.row.allFullDomainList">-</div>
<!-- <div v-if="scope.row.allFullDomainList" v-for="(domain, index) in scope.row.allFullDomainList" :key="index">-->
<!-- <span>{{ domain }}</span>-->
<!-- </div>-->
<div v-for="(domain, index) in scope.row.allFullDomainList" :key="index">
<span>{{ domain }}</span>
</div>
</template>
</el-table-column>
<el-table-column align="center" :label="$t('table.serverPort')" width="80">
@@ -437,13 +428,6 @@ export default {
this.getAvailableDomainList()
},
methods: {
handleCopy(text) {
navigator.clipboard.writeText(text).then(() => {
this.$message.success('复制成功')
}).catch(() => {
this.$message.error('复制失败')
})
},
// 添加新的域名映射
addDomainMapping() {
let defaultDomainId = this.domainList[0].id
@@ -1,10 +1,6 @@
package org.dromara.neutrinoproxy.client.config;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.WriteBufferWaterMark;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.client.util.StringUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
@@ -13,7 +9,6 @@ import org.noear.solon.annotation.Inject;
* @author: aoshiguchen
* @date: 2022/6/16
*/
@Slf4j
@Data
@Component
public class ProxyConfig {
@@ -34,8 +29,6 @@ public class ProxyConfig {
private Integer readIdleTime;
private Integer writeIdleTime;
private Integer allIdleTimeSeconds;
// 水位线
private String waterMark;
}
@Data
@@ -78,38 +71,4 @@ public class ProxyConfig {
private String puppetPortRange;
private Boolean transferLogEnable;
}
private WriteBufferWaterMark waterMark;
private boolean isParseWaterMark = false;
public synchronized WriteBufferWaterMark getWaterMark() {
if (isParseWaterMark) {
return waterMark;
}
isParseWaterMark = true;
if (null == protocol || StrUtil.isBlank(protocol.getWaterMark())) {
return null;
}
String[] tmp = protocol.getWaterMark().split("/");
if (tmp.length != 2) {
log.info("[配置解析] 水位线配置参数格式有误! config={}", protocol.getWaterMark());
return null;
}
String lowStr = tmp[0].trim();
String highStr = tmp[1].trim();
if (!StringUtil.isBytesDesc(lowStr) || !StringUtil.isBytesDesc(highStr)) {
log.info("[配置解析] 水位线配置参数格式有误! config={}", protocol.getWaterMark());
return null;
}
Long low = StringUtil.parseBytes(lowStr);
Long high = StringUtil.parseBytes(highStr);
if (null == low || null == high || low >= high) {
log.info("[配置解析] 水位线配置参数格式或大小有误! config={}", protocol.getWaterMark());
return null;
}
waterMark = new WriteBufferWaterMark(low.intValue(), high.intValue());
log.info("[配置解析] 水位线配置 config={},low={},high={}", protocol.getWaterMark(), low.intValue(), high.intValue());
return waterMark;
}
}
@@ -1,6 +1,8 @@
package org.dromara.neutrinoproxy.client.config;
import io.netty.channel.*;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
@@ -14,6 +16,7 @@ import org.dromara.neutrinoproxy.core.aot.NeutrinoCoreRuntimeNativeRegistrar;
import org.dromara.neutrinoproxy.core.dispatcher.DefaultDispatcher;
import org.dromara.neutrinoproxy.core.dispatcher.Dispatcher;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
@@ -105,12 +108,6 @@ public class ProxyConfiguration implements LifecycleBean {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(tunnelWorkGroup);
bootstrap.channel(NioSocketChannel.class);
WriteBufferWaterMark waterMark = proxyConfig.getWaterMark();
if (null != waterMark) {
bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
}
bootstrap.remoteAddress(InetSocketAddress.createUnresolved(proxyConfig.getTunnel().getServerIp(), proxyConfig.getTunnel().getServerPort()));
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@@ -168,12 +165,6 @@ public class ProxyConfiguration implements LifecycleBean {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(tcpRealServerWorkGroup);
bootstrap.channel(NioSocketChannel.class);
WriteBufferWaterMark waterMark = proxyConfig.getWaterMark();
if (null != waterMark) {
bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
}
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
@@ -1,6 +1,5 @@
package org.dromara.neutrinoproxy.client.core;
import io.netty.handler.codec.DecoderException;
import org.dromara.neutrinoproxy.client.config.ProxyConfig;
import org.dromara.neutrinoproxy.client.util.ProxyUtil;
import org.dromara.neutrinoproxy.core.Constants;
@@ -14,9 +13,6 @@ import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.Solon;
import java.io.IOException;
import java.net.SocketException;
/**
* 处理与服务端之间的数据传输
* @author: aoshiguchen
@@ -62,29 +58,8 @@ public class CmdChannelHandler extends SimpleChannelInboundHandler<ProxyMessage>
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// 对于其他异常(可能是可恢复的业务异常),只记录日志
if (cause instanceof IOException) {
// IOException及其子类(包括SocketException)都是致命的网络异常
if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// Connection reset是常见的客户端断开,使用debug级别
log.debug("[Cmd Channel] Client connection reset: {}", cause.getMessage());
} else {
log.error("[Cmd Channel] IO Error", cause);
}
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else if(cause instanceof DecoderException) {
// 协议解析错误,为防止数据污染,立即关闭
log.debug("[Cmd Channel] decoder error: {}", cause.getMessage());
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else {
// 其他异常只记录日志,不关闭channel,让Netty自己处理
log.error("[Cmd Channel] error", cause);
}
log.error("[CMD Channel]Client CmdChannel Error channelId:{}", ctx.channel().id().asLongText(), cause);
ctx.close();
}
@Override
@@ -1,16 +1,14 @@
package org.dromara.neutrinoproxy.client.core;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.client.util.ProxyUtil;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import io.netty.buffer.ByteBuf;
import java.io.IOException;
import java.net.SocketException;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* 处理与被代理客户端的数据传输
@@ -57,10 +55,9 @@ public class RealServerChannelHandler extends SimpleChannelInboundHandler<ByteBu
Channel realServerChannel = ctx.channel();
String visitorId = ProxyUtil.getVisitorIdByRealServerChannel(realServerChannel);
ProxyUtil.removeRealServerChannel(visitorId);
Channel proxyChannel = realServerChannel.attr(Constants.NEXT_CHANNEL).get();
if (proxyChannel != null && proxyChannel.isActive()) {
// channel.writeAndFlush(ProxyMessage.buildDisconnectMessage(visitorId));
proxyChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
Channel channel = realServerChannel.attr(Constants.NEXT_CHANNEL).get();
if (channel != null) {
channel.writeAndFlush(ProxyMessage.buildDisconnectMessage(visitorId));
}
super.channelInactive(ctx);
@@ -79,28 +76,6 @@ public class RealServerChannelHandler extends SimpleChannelInboundHandler<ByteBu
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// 对于其他异常(可能是可恢复的业务异常),只记录日志
if (cause instanceof IOException) {
// IOException及其子类(包括SocketException)都是致命的网络异常
if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// Connection reset是常见的客户端断开,使用debug级别
log.debug("[Real Server Channel] Client connection reset: {}", cause.getMessage());
} else {
log.error("[Real Server Channel] IO Error", cause);
}
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else if(cause instanceof DecoderException) {
// 协议解析错误,为防止数据污染,立即关闭
log.debug("[Real Server Channel] decoder error: {}", cause.getMessage());
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else {
// 其他异常只记录日志,不关闭channel,让Netty自己处理
log.error("[Real Server Channel] error", cause);
}
log.error("Client ProxyChannel Error", cause);
}
}
@@ -1,8 +1,9 @@
package org.dromara.neutrinoproxy.client.core;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.client.util.ProxyUtil;
@@ -11,9 +12,6 @@ import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.core.dispatcher.Dispatcher;
import org.noear.solon.Solon;
import java.io.IOException;
import java.net.SocketException;
/**
* 处理与服务端之间的数据传输
* @author: aoshiguchen
@@ -45,43 +43,18 @@ public class TcpProxyChannelHandler extends SimpleChannelInboundHandler<ProxyMes
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 数据传输连接
Channel realServerChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (null != realServerChannel && realServerChannel.isActive()) {
// realServerChannel.close();
realServerChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
if (realServerChannel != null && realServerChannel.isActive()) {
realServerChannel.close();
}
ProxyUtil.returnTcpProxyChanel(ctx.channel());
ctx.channel().attr(Constants.NEXT_CHANNEL).remove();
ProxyUtil.removeTcpProxyChanel(ctx.channel());
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// 对于其他异常(可能是可恢复的业务异常),只记录日志
if (cause instanceof IOException) {
// IOException及其子类(包括SocketException)都是致命的网络异常
if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// Connection reset是常见的客户端断开,使用debug级别
log.debug("[TCP Proxy Channel] Client connection reset: {}", cause.getMessage());
} else {
log.error("[TCP Proxy Channel] IO Error", cause);
}
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else if(cause instanceof DecoderException) {
// 协议解析错误,为防止数据污染,立即关闭
log.debug("[TCP Proxy Channel] decoder error: {}", cause.getMessage());
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else {
// 其他异常只记录日志,不关闭channel,让Netty自己处理
log.error("[TCP Proxy Channel] error", cause);
}
log.error("[TCP Proxy Channel]Client ProxyChannel Error channelId:{}", ctx.channel().id().asLongText(), cause);
ctx.close();
}
@Override
@@ -1,8 +1,9 @@
package org.dromara.neutrinoproxy.client.core;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.client.util.ProxyUtil;
@@ -11,9 +12,6 @@ import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.core.dispatcher.Dispatcher;
import org.noear.solon.Solon;
import java.io.IOException;
import java.net.SocketException;
/**
* 处理与服务端之间的数据传输
* @author: aoshiguchen
@@ -46,40 +44,17 @@ public class UdpProxyChannelHandler extends SimpleChannelInboundHandler<ProxyMes
// 数据传输连接
Channel realServerChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (realServerChannel != null && realServerChannel.isActive()) {
// realServerChannel.close();
realServerChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
realServerChannel.close();
}
ProxyUtil.returnUdpProxyChanel(ctx.channel());
ProxyUtil.removeUdpProxyChanel(ctx.channel());
ProxyUtil.removeTcpProxyChanel(ctx.channel());
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// 对于其他异常(可能是可恢复的业务异常),只记录日志
if (cause instanceof IOException) {
// IOException及其子类(包括SocketException)都是致命的网络异常
if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// Connection reset是常见的客户端断开,使用debug级别
log.debug("[UDP Proxy Channel] Client connection reset: {}", cause.getMessage());
} else {
log.error("[UDP Proxy Channel] IO Error", cause);
}
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else if(cause instanceof DecoderException) {
// 协议解析错误,为防止数据污染,立即关闭
log.debug("[UDP Proxy Channel] decoder error: {}", cause.getMessage());
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else {
// 其他异常只记录日志,不关闭channel,让Netty自己处理
log.error("[UDP Proxy Channel] error", cause);
}
log.error("[UDP Proxy Channel]Client ProxyChannel Error channelId:{}", ctx.channel().id().asLongText(), cause);
ctx.close();
}
@Override
@@ -88,18 +63,16 @@ public class UdpProxyChannelHandler extends SimpleChannelInboundHandler<ProxyMes
IdleStateEvent event = (IdleStateEvent)evt;
switch (event.state()) {
case READER_IDLE:
if (ctx.channel().isWritable()) {
// 读超时,断开连接
log.info("[UDP Proxy Channel]Read timeout");
ctx.channel().close();
}
break;
case WRITER_IDLE:
ctx.channel().writeAndFlush(ProxyMessage.buildHeartbeatMessage());
break;
case ALL_IDLE:
// log.debug("[UDP Proxy Channel]ReadWrite timeout");
// ctx.close();
log.debug("[UDP Proxy Channel]ReadWrite timeout");
ctx.close();
break;
}
}
@@ -3,16 +3,12 @@ package org.dromara.neutrinoproxy.client.core;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.DecoderException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.client.constant.Constants;
import org.dromara.neutrinoproxy.client.util.UdpChannelBindInfo;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Date;
/**
* @author: aoshiguchen
@@ -40,47 +36,6 @@ public class UdpRealServerHandler extends SimpleChannelInboundHandler<DatagramPa
);
udpChannelBindInfo.getLockChannel().setResponseCount(udpChannelBindInfo.getLockChannel().getResponseCount() + 1);
udpChannelBindInfo.getLockChannel().setLastActiveTime(new Date());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// 对于其他异常(可能是可恢复的业务异常),只记录日志
if (cause instanceof IOException) {
// IOException及其子类(包括SocketException)都是致命的网络异常
if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// Connection reset是常见的客户端断开,使用debug级别
log.debug("[UDP RealServer Channel] Client connection reset: {}", cause.getMessage());
} else {
log.error("[UDP RealServer Channel] IO Error", cause);
}
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else if(cause instanceof DecoderException) {
// 协议解析错误,为防止数据污染,立即关闭
log.debug("[UDP RealServer Channel] decoder error: {}", cause.getMessage());
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else {
// 其他异常只记录日志,不关闭channel,让Netty自己处理
log.error("[UDP RealServer Channel] error", cause);
}
}
// @Override
// public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// // 数据传输连接
// Channel realServerChannel = ctx.channel().attr(org.dromara.neutrinoproxy.core.Constants.NEXT_CHANNEL).get();
// if (realServerChannel != null && realServerChannel.isActive()) {
// // realServerChannel.close();
// realServerChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
// }
//
// ProxyUtil.removeUdpProxyChanel(ctx.channel());
// super.channelInactive(ctx);
// }
}
@@ -1,10 +1,14 @@
package org.dromara.neutrinoproxy.client.handler;
import org.dromara.neutrinoproxy.client.util.ProxyUtil;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyDataTypeEnum;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.core.ProxyMessageHandler;
import org.dromara.neutrinoproxy.core.dispatcher.Match;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import org.noear.solon.annotation.Component;
@@ -19,12 +23,12 @@ public class ProxyMessageDisconnectHandler implements ProxyMessageHandler {
@Override
public void handle(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
// Channel realServerChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
// if (null != realServerChannel) {
// ctx.channel().attr(Constants.NEXT_CHANNEL).remove();
// ProxyUtil.returnTcpProxyChanel(ctx.channel());
// realServerChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
// }
Channel realServerChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (null != realServerChannel) {
ctx.channel().attr(Constants.NEXT_CHANNEL).remove();
ProxyUtil.returnTcpProxyChanel(ctx.channel());
realServerChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
ctx.close();
}
@@ -23,8 +23,6 @@ public class LockChannel {
private long proxyTimeoutMs;
// 被获取的时间
private Date takeTime;
// 最后一次活跃的时间(最后发生读写的时间),每次发送或响应需要重置
private Date lastActiveTime;
// 已经响应的次数(相对于最后一次发送的时,每次发送后需要重置)
// 已经响应的次数
private int responseCount;
}
@@ -180,7 +180,8 @@ public class ProxyUtil {
}
public static ChannelHandler createSslHandler(ProxyConfig proxyConfig) {
try (InputStream jksInputStream = FileUtil.getInputStream(proxyConfig.getTunnel().getJksPath())) {
try {
InputStream jksInputStream = FileUtil.getInputStream(proxyConfig.getTunnel().getJksPath());
SSLContext clientContext = SSLContext.getInstance("TLS");
final KeyStore ks = KeyStore.getInstance("JKS");
@@ -1,75 +0,0 @@
package org.dromara.neutrinoproxy.client.util;
import cn.hutool.core.util.StrUtil;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author: aoshiguchen
* @date: 2023/12/15
*/
public class StringUtil {
private static final Integer BYTES_MUL_KB = 1024;
private static final Integer BYTES_MUL_MB = BYTES_MUL_KB * 1024;
private static final Integer BYTES_MUL_GB = BYTES_MUL_MB * 1024;
private static final String[] BYTES_UNIT_STR = {"B", "K", "KB", "M", "MB", "G", "GB"};
private static final Integer[] BYTES_UNIT_MUL = {1, BYTES_MUL_KB, BYTES_MUL_KB, BYTES_MUL_MB, BYTES_MUL_MB, BYTES_MUL_GB, BYTES_MUL_GB};
private static final String BYTES_DESC_REGEX = "\\s*(\\d+\\.*\\d*)\\s*(B|K|KB|M|MB|G|GB)\\s*";
private static final Pattern BYTES_DESC_PATTERN = Pattern.compile(BYTES_DESC_REGEX);
/**
* 校验是否符合字节描述
* @param desc
* @return
*/
public static boolean isBytesDesc(String desc) {
if (StrUtil.isBlank(desc)) {
return false;
}
return desc.toUpperCase().matches(BYTES_DESC_REGEX);
}
/**
* 解析字节数
* 支持B、K、KB、M、MB、G、GB 忽略大小写、忽略首尾空格、忽略数字与单位之间的空格
* @param desc
* @return
*/
public static Long parseBytes(String desc) {
try {
if (!isBytesDesc(desc)) {
return null;
}
Matcher matcher = BYTES_DESC_PATTERN.matcher(desc.toUpperCase());
boolean found = matcher.find();
if (!found) {
return null;
}
Double n = Double.parseDouble(matcher.group(1));
String unit = matcher.group(2);
Integer unitIndex = getBytesUnitIndex(unit);
if (null == unitIndex) {
return null;
}
return (long)(n * BYTES_UNIT_MUL[unitIndex]);
} catch (Exception e) {
// ignore
}
return null;
}
private static Integer getBytesUnitIndex(String unit) {
if (StrUtil.isBlank(unit)) {
return null;
}
for (int i = 0; i < BYTES_UNIT_STR.length; i++) {
if (unit.equals(BYTES_UNIT_STR[i])) {
return i;
}
}
return null;
}
}
@@ -133,40 +133,28 @@ public class UdpServerUtil {
* @return
*/
public static synchronized Channel takeChannel(ProxyMessage.UdpBaseInfo info, Channel tunnelChannel) {
Channel realServerChannel = tunnelChannel.attr(org.dromara.neutrinoproxy.core.Constants.NEXT_CHANNEL).get();
if (null != realServerChannel) {
UdpChannelBindInfo udpChannelBindInfo = realServerChannel.attr(Constants.UDP_CHANNEL_BIND_KEY).get();
// 每次发送前重置
udpChannelBindInfo.getLockChannel().setResponseCount(0);
udpChannelBindInfo.getLockChannel().setLastActiveTime(new Date());
return realServerChannel;
}
// 响应数量为零、超时时间<=0,则不需要响应(注意:响应数量为-1 则不限制响应数量)
if (info.getProxyResponses() == 0 || info.getProxyTimeoutMs() <= 0) {
if (info.getProxyResponses() <= 0 || info.getProxyTimeoutMs() <= 0) {
return defaultUdpServerChannel;
}
// 没有空闲的 傀儡端口,降级为不需要响应
Integer port = udpServerFreePortPool.poll();
if (null == port) {
return defaultUdpServerChannel;
}
realServerChannel = portToChannelMap.get(port);
if (null == realServerChannel) {
realServerChannel = bindPort(port);
portToChannelMap.put(port, realServerChannel);
Channel channel = portToChannelMap.get(port);
if (null == channel) {
channel = bindPort(port);
portToChannelMap.put(port, channel);
}
// 添加到锁定队列
LockChannel lockChannel = new LockChannel()
.setPort(port)
.setChannel(realServerChannel)
.setChannel(channel)
.setProxyResponses(info.getProxyResponses())
.setProxyTimeoutMs(info.getProxyTimeoutMs())
.setTakeTime(new Date())
.setLastActiveTime(new Date())
.setResponseCount(0);
lockChannelList.add(lockChannel);
realServerChannel.attr(Constants.UDP_CHANNEL_BIND_KEY).set(new UdpChannelBindInfo()
channel.attr(Constants.UDP_CHANNEL_BIND_KEY).set(new UdpChannelBindInfo()
.setTunnelChannel(tunnelChannel)
.setVisitorId(info.getVisitorId())
.setVisitorIp(info.getVisitorIp())
@@ -176,12 +164,7 @@ public class UdpServerUtil {
.setTargetPort(info.getTargetPort())
.setLockChannel(lockChannel)
);
// 连接绑定
realServerChannel.attr(org.dromara.neutrinoproxy.core.Constants.NEXT_CHANNEL).set(tunnelChannel);
tunnelChannel.attr(org.dromara.neutrinoproxy.core.Constants.NEXT_CHANNEL).set(realServerChannel);
return realServerChannel;
return channel;
}
/**
@@ -194,8 +177,8 @@ public class UdpServerUtil {
Iterator<LockChannel> iter = lockChannelList.iterator();
if (iter.hasNext()) {
LockChannel lockChannel = iter.next();
if ((lockChannel.getProxyResponses() > 0 && lockChannel.getResponseCount() >= lockChannel.getProxyResponses()) ||
System.currentTimeMillis() - lockChannel.getLastActiveTime().getTime() > lockChannel.getProxyTimeoutMs()
if (lockChannel.getResponseCount() >= lockChannel.getProxyResponses() ||
System.currentTimeMillis() - lockChannel.getTakeTime().getTime() >= lockChannel.getProxyTimeoutMs()
) {
iter.remove();
UdpChannelBindInfo udpChannelBindInfo = lockChannel.getChannel().attr(Constants.UDP_CHANNEL_BIND_KEY).get();
@@ -203,17 +186,6 @@ public class UdpServerUtil {
closeChannel(udpChannelBindInfo.getTunnelChannel());
lockChannel.getChannel().attr(Constants.UDP_CHANNEL_BIND_KEY).set(null);
udpServerFreePortPool.offer(lockChannel.getPort());
// 连接解绑
Channel realServerChannel = lockChannel.getChannel();
Channel tunnelChannel = realServerChannel.attr(org.dromara.neutrinoproxy.core.Constants.NEXT_CHANNEL).get();
if (null != realServerChannel) {
realServerChannel.attr(org.dromara.neutrinoproxy.core.Constants.NEXT_CHANNEL).set(null);
}
if (null != tunnelChannel) {
tunnelChannel.attr(org.dromara.neutrinoproxy.core.Constants.NEXT_CHANNEL).set(null);
}
log.debug("[udp channel]release udp channel port:{}", lockChannel.getPort());
}
}
@@ -4,9 +4,6 @@ solon.logging.logger:
neutrino:
proxy:
protocol:
# 高低水位线,如:32KB/64KB、32KB/1MB、1MB/5MB
# water-mark: 1MB/8MB
tunnel:
# 线程池相关配置,用于技术调优,可忽略
thread-count: 50
@@ -3,7 +3,7 @@ solon:
add: ./app.yml
app:
name: neutrino-proxy-client
version: 2.0.4
version: 2.0.2
# 日志级别
solon.logging.appender:
console:
@@ -31,8 +31,6 @@ neutrino:
read-idle-time: 120
write-idle-time: 20
all-idle-time-seconds: 0
# 高低水位线,如:32KB/64KB、32KB/1MB、1MB/5MB
# water-mark: 1MB/8MB
tunnel:
# 线程池相关配置,用于技术调优,可忽略
thread-count: 50
@@ -4,7 +4,6 @@ import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import java.net.InetSocketAddress;
import java.util.function.BiConsumer;
/**
*
@@ -34,8 +33,6 @@ public interface Constants {
AttributeKey<Boolean> FLOW_LIMITER_FLAG = AttributeKey.newInstance("flowLimiterFlag");
AttributeKey<ProxyAttachment> PROXY_CONNECT_ATTACHMENT = AttributeKey.newInstance("proxyConnectAttachment");;
int HEADER_SIZE = 4;
int TYPE_SIZE = 1;
@@ -54,20 +51,4 @@ public interface Constants {
String ERROR = "ERROR";
String PORT_MAPPING_SYNC = "PORT_MAPPING_SYNC";
}
class ProxyAttachment {
private byte[] bytes;
private BiConsumer<Channel, byte[]> executor;
public ProxyAttachment(byte[] bytes, BiConsumer<Channel, byte[]> executor) {
this.bytes = bytes;
this.executor = executor;
}
public void execute(Channel channel) {
if (null != executor && null != channel && channel.isActive()) {
this.executor.accept(channel, bytes);
}
}
}
}
@@ -37,17 +37,8 @@ public class HttpUtil {
* @return
*/
public static String getHeaderValue(String httpContent, String header) {
if (!httpContent.contains("\r\n\r\n")) {
return null;
}
String headerContent = httpContent.split("\r\n\r\n")[0];
if (!headerContent.contains("\r\n")) {
return null;
}
String[] lines = headerContent.split("\r\n");
if (lines.length == 0) {
return null;
}
String firstLine = lines[0];
if (!(firstLine.endsWith("HTTP/1.1") || firstLine.endsWith("HTTP/1.0"))) {
return null;
@@ -25,14 +25,13 @@ public class AppLoadEndExecutor implements EventListener<AppLoadEndEvent> {
System.out.printf("""
---------------------------------------------------------------
Neutrino Proxy Server %s
admin: http://localhost:%s
admin: http://localhost:8888
account: admin/123456
Gitee: https://gitee.com/dromara/neutrino-proxy
GitHub: https://github.com/dromara/neutrino-proxy
GitCode: https://gitcode.com/dromara/neutrino-proxy
---------------------------------------------------------------
%n""", Solon.app().cfg().get("solon.app.version"),
Solon.app().cfg().get("server.port"));
%n""", Solon.app().cfg().get("solon.app.version"));
}
}
@@ -1,10 +1,6 @@
package org.dromara.neutrinoproxy.server.base.proxy;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.WriteBufferWaterMark;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.server.util.StringUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
@@ -13,7 +9,6 @@ import org.noear.solon.annotation.Inject;
* @author: aoshiguchen
* @date: 2022/6/16
*/
@Slf4j
@Data
@Component
public class ProxyConfig {
@@ -43,8 +38,6 @@ public class ProxyConfig {
private Integer readIdleTime;
private Integer writeIdleTime;
private Integer allIdleTimeSeconds;
// 水位线
private String waterMark;
}
@Data
@@ -83,37 +76,4 @@ public class ProxyConfig {
private Integer workThreadCount;
private Boolean transferLogEnable;
}
private WriteBufferWaterMark waterMark;
private boolean isParseWaterMark = false;
public synchronized WriteBufferWaterMark getWaterMark() {
if (isParseWaterMark) {
return waterMark;
}
isParseWaterMark = true;
if (null == protocol || StrUtil.isBlank(protocol.getWaterMark())) {
return null;
}
String[] tmp = protocol.getWaterMark().split("/");
if (tmp.length != 2) {
log.info("[配置解析] 水位线配置参数格式有误! config={}", protocol.getWaterMark());
return null;
}
String lowStr = tmp[0].trim();
String highStr = tmp[1].trim();
if (!StringUtil.isBytesDesc(lowStr) || !StringUtil.isBytesDesc(highStr)) {
log.info("[配置解析] 水位线配置参数格式有误! config={}", protocol.getWaterMark());
return null;
}
Long low = StringUtil.parseBytes(lowStr);
Long high = StringUtil.parseBytes(highStr);
if (null == low || null == high || low >= high) {
log.info("[配置解析] 水位线配置参数格式或大小有误! config={}", protocol.getWaterMark());
return null;
}
waterMark = new WriteBufferWaterMark(low.intValue(), high.intValue());
log.info("[配置解析] 水位线配置 config={},low={},high={}", protocol.getWaterMark(), low.intValue(), high.intValue());
return waterMark;
}
}
@@ -1,9 +1,10 @@
package org.dromara.neutrinoproxy.server.base.proxy;
import cn.hutool.core.util.StrUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
@@ -14,13 +15,14 @@ import org.dromara.neutrinoproxy.core.ProxyMessageHandler;
import org.dromara.neutrinoproxy.core.aot.NeutrinoCoreRuntimeNativeRegistrar;
import org.dromara.neutrinoproxy.core.dispatcher.DefaultDispatcher;
import org.dromara.neutrinoproxy.core.dispatcher.Dispatcher;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.nio.NioEventLoopGroup;
import org.dromara.neutrinoproxy.server.proxy.core.BytesMetricsHandler;
import org.dromara.neutrinoproxy.server.proxy.core.TcpVisitorChannelHandler;
import org.dromara.neutrinoproxy.server.proxy.core.UdpVisitorChannelHandler;
import org.dromara.neutrinoproxy.server.proxy.security.TcpVisitorSecurityChannelHandler;
import org.dromara.neutrinoproxy.server.proxy.security.UdpVisitorSecurityChannelHandler;
import org.dromara.neutrinoproxy.server.proxy.security.VisitorFlowLimiterChannelHandler;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
@@ -45,8 +47,6 @@ public class ProxyConfiguration implements LifecycleBean {
null : ProxyDataTypeEnum.of((int)proxyMessage.getType()).getName());
Solon.context().wrapAndPut(Dispatcher.class, dispatcher);
ProxyUtil.init();
}
@Bean("tcpServerBossGroup")
@@ -67,11 +67,6 @@ public class ProxyConfiguration implements LifecycleBean {
@Inject ProxyConfig proxyConfig
) {
ServerBootstrap bootstrap = new ServerBootstrap();
WriteBufferWaterMark waterMark = proxyConfig.getWaterMark();
if (null != waterMark) {
bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
}
bootstrap.group(tcpServerBossGroup, tcpServerWorkerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@@ -80,7 +75,7 @@ public class ProxyConfiguration implements LifecycleBean {
if (null != proxyConfig.getServer().getTcp().getTransferLogEnable() && proxyConfig.getServer().getTcp().getTransferLogEnable()) {
ch.pipeline().addFirst(new LoggingHandler(TcpVisitorChannelHandler.class));
}
// ch.pipeline().addFirst(new BytesMetricsHandler());
ch.pipeline().addFirst(new BytesMetricsHandler());
// ch.pipeline().addLast(new ChannelTrafficShapingHandler(1024 * 1024 * 20, 1024 * 1024 * 20, 100, 20000));
ch.pipeline().addLast(new TcpVisitorSecurityChannelHandler());
ch.pipeline().addLast("flowLimiter", new VisitorFlowLimiterChannelHandler());
@@ -23,7 +23,7 @@ public class GlobalExceptionFilter implements Filter {
try {
chain.doFilter(ctx);
} catch (Throwable e) {
log.debug("global error", e);
log.error("global error", e);
if (e instanceof ServiceException) {
ServiceException serviceException = (ServiceException) e;
@@ -1,26 +0,0 @@
package org.dromara.neutrinoproxy.server.controller;
import org.dromara.neutrinoproxy.server.base.rest.Authorization;
import org.dromara.neutrinoproxy.server.controller.res.stats.StatsInfoRes;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Mapping;
/**
*
* @author: wen.y
* @date: 2026/1/20
*/
@Mapping("/stats")
@Controller
public class StatsController {
@Authorization(login = false)
@Get
@Mapping("/info")
public StatsInfoRes info() {
return new StatsInfoRes().setCacheInfo(ProxyUtil.getCacheInfo());
}
}
@@ -1,31 +0,0 @@
package org.dromara.neutrinoproxy.server.controller.res.stats;
import lombok.Data;
import lombok.experimental.Accessors;
/**
*
* @author: wen.y
* @date: 2026/1/20
*/
@Accessors(chain = true)
@Data
public class StatsInfoRes {
private CacheInfo cacheInfo;
@Data
public static class CacheInfo {
private Integer proxyInfoMapSize;
private Integer serverPortToCmdChannelMapSize;
private Integer licenseToCmdChannelMapSize;
private Integer serverPortToVisitorChannelMapSize;
private Integer proxyConnectAttachmentMapSize;
private Integer fullDomainToServerPortMapSize;
private Integer domainToDomainNameIdMapSize;
private Integer licenseIdToClientIdMapSize;
private Integer visitorIdToSocketAddressMapSize;
private Integer socketAddressToVisitorIdMapSize;
private Integer visitorIdToTunnelChannelMapSize;
}
}
@@ -1,6 +1,5 @@
package org.dromara.neutrinoproxy.server.proxy.core;
import io.netty.handler.codec.DecoderException;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.core.dispatcher.Dispatcher;
@@ -18,9 +17,7 @@ import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.Solon;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Date;
/**
@@ -54,7 +51,6 @@ public class ProxyTunnelChannelHandler extends SimpleChannelInboundHandler<Proxy
Channel visitorChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (visitorChannel != null) {
visitorChannel.config().setOption(ChannelOption.AUTO_READ, ctx.channel().isWritable());
// visitorChannel.config().setAutoRead(ctx.channel().isWritable());
}
super.channelWritabilityChanged(ctx);
@@ -62,13 +58,6 @@ public class ProxyTunnelChannelHandler extends SimpleChannelInboundHandler<Proxy
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
{
// udp情况下不能使用visitorChannel上的visitorId,因为所有的用户都是走的同一个VisitorChannel
String visitorId = ctx.channel().attr(Constants.VISITOR_ID).get();
// 删除Udp的SocketAddress
ProxyUtil.removeSocketAddressByVisitorId(visitorId);
}
Channel visitorChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (null != visitorChannel) {
Integer licenseId = ctx.channel().attr(Constants.LICENSE_ID).get();
@@ -85,7 +74,7 @@ public class ProxyTunnelChannelHandler extends SimpleChannelInboundHandler<Proxy
if (visitorChannel.isActive() && null == isUdp) {
// 数据发送完成后再关闭连接,解决http1.0数据传输问题
visitorChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
// visitorChannel.close();
visitorChannel.close();
}
} else {
CmdChannelAttachInfo cmdChannelAttachInfo = ProxyUtil.getAttachInfo(ctx.channel());
@@ -115,30 +104,12 @@ public class ProxyTunnelChannelHandler extends SimpleChannelInboundHandler<Proxy
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// 对于其他异常(可能是可恢复的业务异常),只记录日志
if (cause instanceof IOException) {
// IOException及其子类(包括SocketException)都是致命的网络异常
if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// Connection reset是常见的客户端断开,使用debug级别
log.debug("[Tunnel Channel] Connection reset: {}", cause.getMessage());
} else {
log.error("[Tunnel Channel] IO error", cause);
}
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else if(cause instanceof DecoderException) {
// 协议解析错误,为防止数据污染,立即关闭
log.debug("[Tunnel Channel] decoder error: {}", cause.getMessage());
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else {
// 其他异常只记录日志,不关闭channel,让Netty自己处理
// super.exceptionCaught(ctx, cause);
// if (ctx.channel().isActive()) {
// ctx.channel().close();
// }
log.error("[Tunnel Channel] error", cause);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
@@ -1,7 +1,5 @@
package org.dromara.neutrinoproxy.server.proxy.core;
import io.netty.channel.ChannelOption;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.handler.logging.LoggingHandler;
import org.dromara.neutrinoproxy.core.ProxyMessageDecoder;
import org.dromara.neutrinoproxy.core.ProxyMessageEncoder;
@@ -56,12 +54,6 @@ public class ProxyTunnelServer implements EventListener<AppLoadEndEvent> {
*/
private void startProxyServer() {
ServerBootstrap bootstrap = new ServerBootstrap();
WriteBufferWaterMark waterMark = proxyConfig.getWaterMark();
if (null != waterMark) {
bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
}
bootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
@@ -99,7 +91,8 @@ public class ProxyTunnelServer implements EventListener<AppLoadEndEvent> {
}
private ChannelHandler createSslHandler() {
try (InputStream jksInputStream = FileUtil.getInputStream(proxyConfig.getTunnel().getJksPath())) {
try {
InputStream jksInputStream = FileUtil.getInputStream(proxyConfig.getTunnel().getJksPath());
SSLContext serverContext = SSLContext.getInstance("TLS");
final KeyStore ks = KeyStore.getInstance("JKS");
@@ -2,9 +2,10 @@ package org.dromara.neutrinoproxy.server.proxy.core;
import cn.hutool.core.util.StrUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyMessage;
@@ -14,9 +15,7 @@ import org.dromara.neutrinoproxy.server.service.FlowReportService;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
import org.noear.solon.Solon;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
/**
*
@@ -28,29 +27,9 @@ public class TcpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteBu
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// 对于其他异常(可能是可恢复的业务异常),只记录日志
if (cause instanceof IOException) {
// IOException及其子类(包括SocketException)都是致命的网络异常
if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// Connection reset是常见的客户端断开,使用debug级别
log.debug("[TCP Visitor Channel] connection reset: {}", cause.getMessage());
} else {
log.error("[TCP Visitor Channel] IO error", cause);
}
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else if(cause instanceof DecoderException) {
// 协议解析错误,为防止数据污染,立即关闭
log.debug("[TCP Visitor Channel] decoder error: {}", cause.getMessage());
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else {
// 其他异常只记录日志,不关闭channel,让Netty自己处理
log.error("[TCP Visitor Channel] error", cause);
}
// 当出现异常就关闭连接
ctx.close();
log.error("VisitorChannel error", cause);
}
@Override
@@ -116,7 +95,11 @@ public class TcpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteBu
InetSocketAddress sa = (InetSocketAddress) visitorChannel.localAddress();
Channel cmdChannel = ProxyUtil.getCmdChannelByServerPort(sa.getPort());
if (null != cmdChannel) {
if (null == cmdChannel) {
// 该端口还没有代理客户端
ctx.channel().close();
} else {
// 用户连接断开,从控制连接中移除
String visitorId = ProxyUtil.getVisitorIdByChannel(visitorChannel);
ProxyUtil.removeVisitorChannelFromCmdChannel(cmdChannel, visitorId);
@@ -133,8 +116,6 @@ public class TcpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteBu
proxyChannel.config().setOption(ChannelOption.AUTO_READ, true);
// 通知客户端,用户连接已经断开
proxyChannel.writeAndFlush(ProxyMessage.buildDisconnectMessage(visitorId));
proxyChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
@@ -157,7 +138,6 @@ public class TcpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteBu
Channel proxyChannel = visitorChannel.attr(Constants.NEXT_CHANNEL).get();
if (null != proxyChannel) {
proxyChannel.config().setOption(ChannelOption.AUTO_READ, visitorChannel.isWritable());
// proxyChannel.config().setAutoRead(visitorChannel.isWritable());
}
}
@@ -10,6 +10,7 @@ import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.server.constant.NetworkProtocolEnum;
import org.dromara.neutrinoproxy.server.proxy.domain.ProxyAttachment;
import org.dromara.neutrinoproxy.server.proxy.domain.VisitorChannelAttachInfo;
import org.dromara.neutrinoproxy.server.service.FlowReportService;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
@@ -32,13 +33,8 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
byte[] bytes = new byte[datagramPacket.content().readableBytes()];
datagramPacket.content().readBytes(bytes);
datagramPacket.content().resetReaderIndex();
Constants.ProxyAttachment proxyAttachment = new Constants.ProxyAttachment(bytes, (channel, buf) -> {
String visitorId = ProxyUtil.getVisitorIdBySocketAddress(datagramPacket.sender());
if (StrUtil.isBlank(visitorId)) {
return;
}
Channel proxyChannel = ProxyUtil.getTunnelChannelByVisitorId(visitorId);
// Channel proxyChannel = channel.attr(Constants.NEXT_CHANNEL).get();
ProxyAttachment proxyAttachment = new ProxyAttachment(ctx.channel(), bytes, (channel, buf) -> {
Channel proxyChannel = channel.attr(Constants.NEXT_CHANNEL).get();
if (null == proxyChannel) {
// // 该端口还没有代理客户端
@@ -53,6 +49,7 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
Long proxyTimeoutMs = proxyChannel.attr(Constants.PROXY_TIMEOUT_MS).get();
// 转发代理数据
String visitorId = ProxyUtil.getVisitorIdByChannel(channel);
proxyChannel.writeAndFlush(ProxyMessage.buildUdpTransferMessage(new ProxyMessage.UdpBaseInfo()
.setVisitorId(visitorId)
.setVisitorIp(datagramPacket.sender().getAddress().getHostAddress())
@@ -68,11 +65,10 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
Solon.context().getBean(FlowReportService.class).addWriteByte(visitorChannelAttachInfo.getLicenseId(), bytes.length);
});
String visitorId = ProxyUtil.getVisitorIdBySocketAddress(datagramPacket.sender());
Channel proxyChannel = ProxyUtil.getTunnelChannelByVisitorId(visitorId);
if (StrUtil.isNotBlank(visitorId) && null != proxyChannel && proxyChannel.isActive()) {
Channel proxyChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (null != proxyChannel && proxyChannel.isActive()) {
// UDP代理隧道已就绪,直接转发
proxyAttachment.execute(ctx.channel());
proxyAttachment.execute();
return;
}
@@ -99,10 +95,8 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
// // 用户连接到代理服务器时,设置用户连接不可读,等待代理后端服务器连接成功后再改变为可读状态
// visitorChannel.config().setOption(ChannelOption.AUTO_READ, false);
// UDP场景下,一个visitorId并不对应一个visitorChannel,所有visitor共用一个visitorChannel
visitorId = ProxyUtil.newVisitorId();
// 设置udp发送方的地址
ProxyUtil.setVisitorIdToSocketAddressMap(visitorId, datagramPacket.sender());
// TODO UDP此处叫visitor似有不妥,与TCP不同,2.x重构思考
String visitorId = ProxyUtil.newVisitorId();
// 此处需要和tcp分开
ProxyUtil.addVisitorChannelToCmdChannel(NetworkProtocolEnum.UDP, cmdChannel, visitorId, visitorChannel, sa.getPort());
ProxyUtil.addProxyConnectAttachment(visitorId, proxyAttachment);
@@ -111,7 +105,6 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
.setServerPort(sa.getPort())
.setTargetIp(targetIp)
.setTargetPort(targetPort)
// connect消息没有传超时时间、响应数量,导致客户端日志输出的超时时间、响应数量都是0
));
}
@@ -120,32 +113,12 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
super.channelActive(ctx);
}
// @Override
// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// // 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// // 对于其他异常(可能是可恢复的业务异常),只记录日志
// if (cause instanceof IOException) {
// // IOException及其子类(包括SocketException)都是致命的网络异常
// if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// // Connection reset是常见的客户端断开,使用debug级别
// log.debug("[UDP Visitor Channel] Connection reset: {}", cause.getMessage());
// } else {
// log.error("[UDP Visitor Channel] IO error", cause);
// }
// if (ctx.channel().isActive()) {
// ctx.channel().close();
// }
// } else if(cause instanceof DecoderException) {
// // 协议解析错误,为防止数据污染,立即关闭
// log.debug("[UDP Visitor Channel] decoder error: {}", cause.getMessage());
// if (ctx.channel().isActive()) {
// ctx.channel().close();
// }
// } else {
// // 其他异常只记录日志,不关闭channel,让Netty自己处理
// log.error("[UDP Visitor Channel] error", cause);
// }
// }
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// 当出现异常就关闭连接
ctx.close();
log.error("[UDP Visitor Channel]VisitorChannel error", cause);
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
@@ -1,28 +1,29 @@
//package org.dromara.neutrinoproxy.server.proxy.domain;
//
//import io.netty.channel.Channel;
//
//import java.util.function.BiConsumer;
//
///**
// * 代理连接附件
// * @author: aoshiguchen
// * @date: 2023/4/2
// */
//public class ProxyAttachment {
// private Channel channel;
// private byte[] bytes;
// private BiConsumer<Channel, byte[]> executor;
//
// public ProxyAttachment(Channel channel, byte[] bytes, BiConsumer<Channel, byte[]> executor) {
// this.channel = channel;
// this.bytes = bytes;
// this.executor = executor;
// }
//
// public void execute() {
// if (null != executor) {
// this.executor.accept(channel, bytes);
// }
// }
//}
package org.dromara.neutrinoproxy.server.proxy.domain;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import java.util.function.BiConsumer;
/**
* 代理连接附件
* @author: aoshiguchen
* @date: 2023/4/2
*/
public class ProxyAttachment {
private Channel channel;
private byte[] bytes;
private BiConsumer<Channel, byte[]> executor;
public ProxyAttachment(Channel channel, byte[] bytes, BiConsumer<Channel, byte[]> executor) {
this.channel = channel;
this.bytes = bytes;
this.executor = executor;
}
public void execute() {
if (null != executor) {
this.executor.accept(channel, bytes);
}
}
}
@@ -8,6 +8,7 @@ import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.server.base.proxy.ProxyConfig;
import org.dromara.neutrinoproxy.server.proxy.core.BytesMetricsHandler;
import org.dromara.neutrinoproxy.server.proxy.security.HttpVisitorSecurityChannelHandler;
import org.dromara.neutrinoproxy.server.proxy.security.VisitorFlowLimiterChannelHandler;
import org.noear.solon.annotation.Component;
@@ -44,7 +45,7 @@ public class HttpProxy implements EventListener<AppLoadEndEvent> {
if (null != proxyConfig.getServer().getTcp().getTransferLogEnable() && proxyConfig.getServer().getTcp().getTransferLogEnable()) {
ch.pipeline().addFirst(new LoggingHandler(HttpProxy.class));
}
// ch.pipeline().addFirst(new BytesMetricsHandler());
ch.pipeline().addFirst(new BytesMetricsHandler());
ch.pipeline().addLast(new HttpVisitorSecurityChannelHandler(false));
ch.pipeline().addLast("flowLimiter",new VisitorFlowLimiterChannelHandler());
ch.pipeline().addLast(new HttpVisitorChannelHandler());
@@ -1,22 +1,22 @@
package org.dromara.neutrinoproxy.server.proxy.enhance;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.server.constant.NetworkProtocolEnum;
import org.dromara.neutrinoproxy.server.proxy.domain.ProxyAttachment;
import org.dromara.neutrinoproxy.server.proxy.domain.VisitorChannelAttachInfo;
import org.dromara.neutrinoproxy.server.service.FlowReportService;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
import org.noear.solon.Solon;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
/**
* @author: aoshiguchen
@@ -30,7 +30,7 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteB
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
byteBuf.resetReaderIndex();
Constants.ProxyAttachment proxyAttachment = new Constants.ProxyAttachment(bytes, (channel, buf) -> {
ProxyAttachment proxyAttachment = new ProxyAttachment(ctx.channel(), bytes, (channel, buf) -> {
Channel proxyChannel = channel.attr(Constants.NEXT_CHANNEL).get();
if (null == proxyChannel) {
// 该端口还没有代理客户端
@@ -47,7 +47,7 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteB
String visitorId = ProxyUtil.getVisitorIdByChannel(ctx.channel());
if (StringUtils.isNotBlank(visitorId)) {
proxyAttachment.execute(ctx.channel());
proxyAttachment.execute();
return;
}
@@ -70,8 +70,7 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteB
visitorId = ProxyUtil.newVisitorId();
ProxyUtil.addVisitorChannelToCmdChannel(NetworkProtocolEnum.HTTP, cmdChannel, visitorId, ctx.channel(), serverPort);
// ProxyUtil.addProxyConnectAttachment(visitorId, proxyAttachment);
ctx.channel().attr(Constants.PROXY_CONNECT_ATTACHMENT).set(proxyAttachment);
ProxyUtil.addProxyConnectAttachment(visitorId, proxyAttachment);
cmdChannel.writeAndFlush(ProxyMessage.buildConnectMessage(visitorId).setData(lanInfo.getBytes()));
}
@@ -83,7 +82,11 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteB
InetSocketAddress sa = (InetSocketAddress) visitorChannel.localAddress();
Channel cmdChannel = ProxyUtil.getCmdChannelByServerPort(sa.getPort());
if (null != cmdChannel) {
if (cmdChannel == null) {
// 该端口还没有代理客户端
ctx.channel().close();
} else {
// 用户连接断开,从控制连接中移除
String visitorId = ProxyUtil.getVisitorIdByChannel(visitorChannel);
ProxyUtil.removeVisitorChannelFromCmdChannel(cmdChannel, visitorId);
@@ -100,8 +103,6 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteB
proxyChannel.config().setOption(ChannelOption.AUTO_READ, true);
// 通知客户端,用户连接已经断开
proxyChannel.writeAndFlush(ProxyMessage.buildDisconnectMessage(visitorId));
proxyChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
@@ -115,29 +116,8 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteB
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// 对于其他异常(可能是可恢复的业务异常),只记录日志
if (cause instanceof IOException) {
// IOException及其子类(包括SocketException)都是致命的网络异常
if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// Connection reset是常见的客户端断开,使用debug级别
log.debug("[HTTP Visitor Channel] Connection reset: {}", cause.getMessage());
} else {
log.error("[HTTP Visitor Channel] IO error", cause);
}
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else if(cause instanceof DecoderException) {
// 协议解析错误,为防止数据污染,立即关闭
log.debug("[HTTP Visitor Channel] decoder error: {}", cause.getMessage());
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else {
// 其他异常只记录日志,不关闭channel,让Netty自己处理
log.error("[HTTP Visitor Channel] error", cause);
}
// 当出现异常就关闭连接
ctx.close();
}
@Override
@@ -10,6 +10,7 @@ import io.netty.handler.ssl.SniHandler;
import io.netty.handler.ssl.SslContext;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.server.base.proxy.ProxyConfig;
import org.dromara.neutrinoproxy.server.proxy.core.BytesMetricsHandler;
import org.dromara.neutrinoproxy.server.proxy.security.HttpVisitorSecurityChannelHandler;
import org.dromara.neutrinoproxy.server.proxy.security.VisitorFlowLimiterChannelHandler;
import org.noear.solon.annotation.Component;
@@ -50,7 +51,7 @@ public class HttpsProxy implements EventListener<AppLoadEndEvent> {
ch.pipeline().addFirst(new LoggingHandler(HttpsProxy.class));
}
ch.pipeline().addLast(createSniHandler());
// ch.pipeline().addFirst(new BytesMetricsHandler());
ch.pipeline().addFirst(new BytesMetricsHandler());
ch.pipeline().addLast(new HttpVisitorSecurityChannelHandler(true));
ch.pipeline().addLast("flowLimiter",new VisitorFlowLimiterChannelHandler());
ch.pipeline().addLast(new HttpVisitorChannelHandler());
@@ -7,6 +7,7 @@ import org.dromara.neutrinoproxy.core.dispatcher.Match;
import org.dromara.neutrinoproxy.server.constant.EnableStatusEnum;
import org.dromara.neutrinoproxy.server.dal.entity.LicenseDO;
import org.dromara.neutrinoproxy.server.dal.entity.UserDO;
import org.dromara.neutrinoproxy.server.proxy.domain.ProxyAttachment;
import org.dromara.neutrinoproxy.server.service.LicenseService;
import org.dromara.neutrinoproxy.server.service.UserService;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
@@ -75,11 +76,8 @@ public class ProxyMessageConnectHandler implements ProxyMessageHandler {
Channel visitorChannel = ProxyUtil.getVisitorChannel(cmdChannel, visitorId);
if (null == visitorChannel) {
ctx.channel().writeAndFlush(ProxyMessage.buildErrMessage(ExceptionEnum.CONNECT_FAILED, "server errorvisitor channel not found!"));
ctx.channel().close();
return;
}
ctx.channel().attr(Constants.VISITOR_ID).set(visitorId);
ctx.channel().attr(Constants.LICENSE_ID).set(licenseDO.getId());
ctx.channel().attr(Constants.NEXT_CHANNEL).set(visitorChannel);
@@ -88,24 +86,13 @@ public class ProxyMessageConnectHandler implements ProxyMessageHandler {
// 代理客户端与后端服务器连接成功,修改用户连接为可读状态
visitorChannel.config().setOption(ChannelOption.AUTO_READ, true);
// 获取代理附加对象
Constants.ProxyAttachment proxyAttachment = visitorChannel.attr(Constants.PROXY_CONNECT_ATTACHMENT).get();
ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(visitorId);
if (null != proxyAttachment) {
// 转发来自visitor的首次代理数据
proxyAttachment.execute(visitorChannel);
// 此处时TCP代理,不一定有代理附加对象,不能因为没有而直接释放visitorChannel
// 及时释放
ProxyUtil.remoteProxyConnectAttachment(visitorId);
proxyAttachment.execute();
}
// // 获取代理附加对象
// ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(visitorId);
// if (null != proxyAttachment) {
// // 及时释放
// ProxyUtil.remoteProxyConnectAttachment(visitorId);
// proxyAttachment.execute();
// }
}
@Override
@@ -38,8 +38,6 @@ public class ProxyMessageTransferHandler implements ProxyMessageHandler {
ctx.channel().config().setAutoRead(true);
}
}
// TODO Netty默认的高水位通常只有64KB,在SCP/SFTP场景下可能很快就填满了。
// 而visitorChannel.writeAndFlush(buf);是异步的。有可能写入数据极快,而visitorChannel的isWritable还没来得及变成false,此处就会写入大量数据把缓冲撑爆。
ByteBuf buf = ctx.alloc().buffer(proxyMessage.getData().length);
buf.writeBytes(proxyMessage.getData());
visitorChannel.writeAndFlush(buf);
@@ -14,6 +14,7 @@ import org.dromara.neutrinoproxy.server.dal.PortMappingMapper;
import org.dromara.neutrinoproxy.server.dal.entity.LicenseDO;
import org.dromara.neutrinoproxy.server.dal.entity.PortMappingDO;
import org.dromara.neutrinoproxy.server.dal.entity.UserDO;
import org.dromara.neutrinoproxy.server.proxy.domain.ProxyAttachment;
import org.dromara.neutrinoproxy.server.service.LicenseService;
import org.dromara.neutrinoproxy.server.service.UserService;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
@@ -86,18 +87,16 @@ public class UdpProxyMessageConnectHandler implements ProxyMessageHandler {
ctx.channel().attr(Constants.TARGET_PORT).set(portMappingDO.getClientPort());
ctx.channel().attr(Constants.PROXY_RESPONSES).set(portMappingDO.getProxyResponses());
ctx.channel().attr(Constants.PROXY_TIMEOUT_MS).set(portMappingDO.getProxyTimeoutMs());
// 所有udb visitor共用一个visitorChannel,设置这个没啥用
// visitorChannel.attr(Constants.NEXT_CHANNEL).set(ctx.channel());
ProxyUtil.setVisitorIdToTunnelChannelMap(udpBaseInfo.getVisitorId(), ctx.channel());
visitorChannel.attr(Constants.NEXT_CHANNEL).set(ctx.channel());
visitorChannel.attr(Constants.IS_UDP_KEY).set(Boolean.TRUE);
// // 代理客户端与后端服务器连接成功,修改用户连接为可读状态
// visitorChannel.config().setOption(ChannelOption.AUTO_READ, true);
// 获取代理附加对象
Constants.ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(udpBaseInfo.getVisitorId());
ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(udpBaseInfo.getVisitorId());
if (null != proxyAttachment) {
// 及时释放
ProxyUtil.remoteProxyConnectAttachment(udpBaseInfo.getVisitorId());
proxyAttachment.execute(visitorChannel);
proxyAttachment.execute();
}
}
@@ -31,9 +31,7 @@ public class UdpProxyMessageTransferHandler implements ProxyMessageHandler {
log.debug("[UDP transfer]info:{} data:{}", proxyMessage.getInfo(), new String(proxyMessage.getData()));
Channel visitorChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (null == visitorChannel) {
return;
}
if (null != visitorChannel) {
if (!visitorChannel.isWritable()) {
//自己不可写,通道可以读,让通道关闭读
@@ -47,6 +45,9 @@ public class UdpProxyMessageTransferHandler implements ProxyMessageHandler {
}
}
// InetSocketAddress address = new InetSocketAddress(udpBaseInfo.getVisitorIp(), udpBaseInfo.getVisitorPort());
// ByteBuf byteBuf = Unpooled.copiedBuffer(proxyMessage.getData());
// visitorChannel.writeAndFlush(new DatagramPacket(byteBuf, address));
InetSocketAddress address = ctx.channel().attr(Constants.SENDER).get();
if (null != address) {
visitorChannel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(proxyMessage.getData()), address));
@@ -58,6 +59,7 @@ public class UdpProxyMessageTransferHandler implements ProxyMessageHandler {
Solon.context().getBean(FlowReportService.class).addReadByte(licenseId, proxyMessage.getData().length);
}
}
}
@Override
public String name() {
@@ -2,14 +2,13 @@ package org.dromara.neutrinoproxy.server.proxy.security;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.i18nformatter.qual.I18nFormat;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.core.util.HttpUtil;
import org.dromara.neutrinoproxy.core.util.IpUtil;
import org.dromara.neutrinoproxy.server.service.DomainService;
@@ -18,10 +17,6 @@ import org.dromara.neutrinoproxy.server.service.SecurityGroupService;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
import org.noear.solon.Solon;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
/**
* @author: aoshiguchen
* @date: 2023/12/14
@@ -114,64 +109,4 @@ public class HttpVisitorSecurityChannelHandler extends ChannelInboundHandlerAdap
// 继续传播
ctx.fireChannelRead(cumulationBuf);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// 对于其他异常(可能是可恢复的业务异常),只记录日志
if (cause instanceof IOException) {
// IOException及其子类(包括SocketException)都是致命的网络异常
if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// Connection reset是常见的客户端断开,使用debug级别
log.debug("[HTTP Visitor Security Channel] Connection reset: {}", cause.getMessage());
} else {
log.error("[HTTP Visitor Security Channel] IO error", cause);
}
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else if(cause instanceof DecoderException) {
// 协议解析错误,为防止数据污染,立即关闭
log.debug("[HTTP Visitor Security Channel] decoder error: {}", cause.getMessage());
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else {
// 其他异常只记录日志,不关闭channel,让Netty自己处理
log.error("[HTTP Visitor Security Channel] error", cause);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 通知代理客户端
Channel visitorChannel = ctx.channel();
InetSocketAddress sa = (InetSocketAddress) visitorChannel.localAddress();
Channel cmdChannel = ProxyUtil.getCmdChannelByServerPort(sa.getPort());
if (null != cmdChannel) {
// 用户连接断开,从控制连接中移除
String visitorId = ProxyUtil.getVisitorIdByChannel(visitorChannel);
ProxyUtil.removeVisitorChannelFromCmdChannel(cmdChannel, visitorId);
// 删除代理附加对象
ProxyUtil.remoteProxyConnectAttachment(visitorId);
Channel proxyChannel = visitorChannel.attr(Constants.NEXT_CHANNEL).get();
if (proxyChannel != null && proxyChannel.isActive()) {
proxyChannel.attr(Constants.NEXT_CHANNEL).remove();
proxyChannel.attr(Constants.LICENSE_ID).remove();
proxyChannel.attr(Constants.VISITOR_ID).remove();
proxyChannel.config().setOption(ChannelOption.AUTO_READ, true);
// 通知客户端,用户连接已经断开
proxyChannel.writeAndFlush(ProxyMessage.buildDisconnectMessage(visitorId));
proxyChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
super.channelInactive(ctx);
}
}
@@ -1,22 +1,18 @@
package org.dromara.neutrinoproxy.server.proxy.security;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.core.util.IpUtil;
import org.dromara.neutrinoproxy.server.service.PortMappingService;
import org.dromara.neutrinoproxy.server.service.SecurityGroupService;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
import org.noear.solon.Solon;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
/**
* @author: aoshiguchen
@@ -69,64 +65,4 @@ public class TcpVisitorSecurityChannelHandler extends ChannelInboundHandlerAdapt
ctx.fireChannelActive();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// 对于其他异常(可能是可恢复的业务异常),只记录日志
if (cause instanceof IOException) {
// IOException及其子类(包括SocketException)都是致命的网络异常
if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// Connection reset是常见的客户端断开,使用debug级别
log.debug("[TCP Visitor Security Channel] Connection reset: {}", cause.getMessage());
} else {
log.error("[TCP Visitor Security Channel] IO error", cause);
}
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else if(cause instanceof DecoderException) {
// 协议解析错误,为防止数据污染,立即关闭
log.debug("[TCP Visitor Security Channel] decoder error: {}", cause.getMessage());
if (ctx.channel().isActive()) {
ctx.channel().close();
}
} else {
// 其他异常只记录日志,不关闭channel,让Netty自己处理
log.error("[TCP Visitor Security Channel] error", cause);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 通知代理客户端
Channel visitorChannel = ctx.channel();
InetSocketAddress sa = (InetSocketAddress) visitorChannel.localAddress();
Channel cmdChannel = ProxyUtil.getCmdChannelByServerPort(sa.getPort());
if (null != cmdChannel) {
// 用户连接断开,从控制连接中移除
String visitorId = ProxyUtil.getVisitorIdByChannel(visitorChannel);
ProxyUtil.removeVisitorChannelFromCmdChannel(cmdChannel, visitorId);
// 删除代理附加对象
ProxyUtil.remoteProxyConnectAttachment(visitorId);
Channel proxyChannel = visitorChannel.attr(Constants.NEXT_CHANNEL).get();
if (proxyChannel != null && proxyChannel.isActive()) {
proxyChannel.attr(Constants.NEXT_CHANNEL).remove();
proxyChannel.attr(Constants.LICENSE_ID).remove();
proxyChannel.attr(Constants.VISITOR_ID).remove();
proxyChannel.config().setOption(ChannelOption.AUTO_READ, true);
// 通知客户端,用户连接已经断开
proxyChannel.writeAndFlush(ProxyMessage.buildDisconnectMessage(visitorId));
proxyChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
super.channelInactive(ctx);
}
}
@@ -1,20 +1,16 @@
package org.dromara.neutrinoproxy.server.proxy.security;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.DecoderException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.server.service.PortMappingService;
import org.dromara.neutrinoproxy.server.service.SecurityGroupService;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
import org.noear.solon.Solon;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
/**
* @author: aoshiguchen
@@ -40,64 +36,4 @@ public class UdpVisitorSecurityChannelHandler extends ChannelInboundHandlerAdapt
ctx.channel().attr(Constants.SERVER_PORT).set(sa.getPort());
ctx.fireChannelRead(msg);
}
// @Override
// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// // 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// // 对于其他异常(可能是可恢复的业务异常),只记录日志
// if (cause instanceof IOException) {
// // IOException及其子类(包括SocketException)都是致命的网络异常
// if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// // Connection reset是常见的客户端断开,使用debug级别
// log.debug("[UDP Visitor Security Channel] Connection reset: {}", cause.getMessage());
// } else {
// log.error("[UDP Visitor Security Channel] IO error", cause);
// }
// if (ctx.channel().isActive()) {
// ctx.channel().close();
// }
// } else if(cause instanceof DecoderException) {
// // 协议解析错误,为防止数据污染,立即关闭
// log.debug("[UDP Visitor Security Channel] decoder error: {}", cause.getMessage());
// if (ctx.channel().isActive()) {
// ctx.channel().close();
// }
// } else {
// // 其他异常只记录日志,不关闭channel,让Netty自己处理
// log.error("[UDP Visitor Security Channel] error", cause);
// }
// }
// @Override
// public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//
// // 通知代理客户端
// Channel visitorChannel = ctx.channel();
// InetSocketAddress sa = (InetSocketAddress) visitorChannel.localAddress();
// Channel cmdChannel = ProxyUtil.getCmdChannelByServerPort(sa.getPort());
//
// if (null != cmdChannel) {
// // 用户连接断开,从控制连接中移除
// String visitorId = ProxyUtil.getVisitorIdByChannel(visitorChannel);
// ProxyUtil.removeVisitorChannelFromCmdChannel(cmdChannel, visitorId);
//
// // 删除代理附加对象
// ProxyUtil.remoteProxyConnectAttachment(visitorId);
//
// Channel proxyChannel = visitorChannel.attr(Constants.NEXT_CHANNEL).get();
// if (proxyChannel != null && proxyChannel.isActive()) {
// proxyChannel.attr(Constants.NEXT_CHANNEL).remove();
// proxyChannel.attr(Constants.LICENSE_ID).remove();
// proxyChannel.attr(Constants.VISITOR_ID).remove();
//
// proxyChannel.config().setOption(ChannelOption.AUTO_READ, true);
// // 通知客户端,用户连接已经断开
// proxyChannel.writeAndFlush(ProxyMessage.buildDisconnectMessage(visitorId));
//
// proxyChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
// }
// }
//
// super.channelInactive(ctx);
// }
}
@@ -1,14 +1,16 @@
package org.dromara.neutrinoproxy.server.proxy.security;
import io.netty.channel.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.server.service.LicenseService;
import org.dromara.neutrinoproxy.server.service.PortMappingService;
import org.dromara.neutrinoproxy.server.service.SecurityGroupService;
import org.dromara.neutrinoproxy.server.service.bo.FlowLimitBO;
import org.noear.solon.Solon;
/**
* 访问者流量限制器
* @author: aoshiguchen
@@ -45,63 +47,4 @@ public class VisitorFlowLimiterChannelHandler extends ChannelInboundHandlerAdapt
ctx.fireChannelRead(msg);
}
// @Override
// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// // 对于网络IO异常(致命异常),关闭channel以防止资源泄漏
// // 对于其他异常(可能是可恢复的业务异常),只记录日志
// if (cause instanceof IOException) {
// // IOException及其子类(包括SocketException)都是致命的网络异常
// if (cause instanceof SocketException && cause.getMessage() != null && cause.getMessage().contains("Connection reset")) {
// // Connection reset是常见的客户端断开,使用debug级别
// log.debug("[Visitor FlowLimit Channel] Connection reset: {}", cause.getMessage());
// } else {
// log.error("[Visitor FlowLimit Channel] IO error", cause);
// }
// if (ctx.channel().isActive()) {
// ctx.channel().close();
// }
// } else if(cause instanceof DecoderException) {
// // 协议解析错误,为防止数据污染,立即关闭
// log.debug("[Visitor FlowLimit Channel] decoder error: {}", cause.getMessage());
// if (ctx.channel().isActive()) {
// ctx.channel().close();
// }
// } else {
// // 其他异常只记录日志,不关闭channel,让Netty自己处理
// log.error("[Visitor FlowLimit Channel] error", cause);
// }
// }
// @Override
// public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//
// // 通知代理客户端
// Channel visitorChannel = ctx.channel();
// InetSocketAddress sa = (InetSocketAddress) visitorChannel.localAddress();
// Channel cmdChannel = ProxyUtil.getCmdChannelByServerPort(sa.getPort());
//
// if (null != cmdChannel) {
// // 用户连接断开,从控制连接中移除
// String visitorId = ProxyUtil.getVisitorIdByChannel(visitorChannel);
// ProxyUtil.removeVisitorChannelFromCmdChannel(cmdChannel, visitorId);
//
// // 删除代理附加对象
// ProxyUtil.remoteProxyConnectAttachment(visitorId);
//
// Channel proxyChannel = visitorChannel.attr(Constants.NEXT_CHANNEL).get();
// if (proxyChannel != null && proxyChannel.isActive()) {
// proxyChannel.attr(Constants.NEXT_CHANNEL).remove();
// proxyChannel.attr(Constants.LICENSE_ID).remove();
// proxyChannel.attr(Constants.VISITOR_ID).remove();
//
// proxyChannel.config().setOption(ChannelOption.AUTO_READ, true);
// // 通知客户端,用户连接已经断开
// proxyChannel.writeAndFlush(ProxyMessage.buildDisconnectMessage(visitorId));
//
// proxyChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
// }
// }
//
// super.channelInactive(ctx);
// }
}
@@ -15,11 +15,17 @@ import org.dromara.neutrinoproxy.server.dal.entity.LicenseDO;
import org.dromara.neutrinoproxy.server.dal.entity.PortMappingDO;
import org.dromara.neutrinoproxy.server.dal.entity.PortPoolDO;
import org.dromara.neutrinoproxy.server.dal.entity.UserDO;
import org.dromara.neutrinoproxy.server.proxy.core.BytesMetricsHandler;
import org.dromara.neutrinoproxy.server.proxy.core.TcpVisitorChannelHandler;
import org.dromara.neutrinoproxy.server.proxy.domain.CmdChannelAttachInfo;
import org.dromara.neutrinoproxy.server.proxy.domain.ProxyMapping;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.solon.annotation.Db;
import org.noear.solon.annotation.Component;
@@ -4,23 +4,17 @@ import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.dromara.neutrinoproxy.core.ChannelAttribute;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.server.constant.NetworkProtocolEnum;
import org.dromara.neutrinoproxy.server.controller.res.stats.StatsInfoRes;
import org.dromara.neutrinoproxy.server.proxy.domain.CmdChannelAttachInfo;
import org.dromara.neutrinoproxy.server.proxy.domain.ProxyAttachment;
import org.dromara.neutrinoproxy.server.proxy.domain.ProxyMapping;
import org.dromara.neutrinoproxy.server.proxy.domain.VisitorChannelAttachInfo;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import org.dromara.solonplugins.job.CustomThreadFactory;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@@ -33,16 +27,16 @@ import java.util.stream.Collectors;
*/
public class ProxyUtil {
public static final AttributeKey<ChannelAttribute> CHANNEL_ATTR_KEY = AttributeKey.valueOf("netty.channel.attr");
// /**
// * license -> 服务端口映射
// */
// private static final Map<Integer, Set<Integer>> licenseToServerPortMap = new HashMap<>();
/**
* license -> 服务端口映射
*/
private static final Map<Integer, Set<Integer>> licenseToServerPortMap = new HashMap<>();
/**
* 代理信息映射 e.g.: 9104 -> 127.0.0.1:8848
*/
private static final Map<Integer, String> proxyInfoMap = new ConcurrentHashMap<>();
/**
* 服务端口 -> 指令通道映射proxyInfoMap
* 服务端口 -> 指令通道映射
*/
private static Map<Integer, Channel> serverPortToCmdChannelMap = new ConcurrentHashMap<>();
/**
@@ -64,10 +58,8 @@ public class ProxyUtil {
private static AtomicLong visitorIdProducer = new AtomicLong(0);
/**
* 代理 - connect附加映射
* (TCP/HTTP场景下,已优化不是用这个。UDP由于无连接,暂时还是要用这个)
* UDP场景时,需要记录最后读写时间,使用定时器定期检查,超时需要释放,待后续优化
*/
private static Map<String, Constants.ProxyAttachment> proxyConnectAttachmentMap = new HashMap<>();
private static Map<String, ProxyAttachment> proxyConnectAttachmentMap = new HashMap<>();
/**
* 完整域名 - 服务端端口映射
*/
@@ -80,58 +72,6 @@ public class ProxyUtil {
* licenseId - 客户端Id映射
*/
private static Map<Integer, String> licenseIdToClientIdMap = new HashMap<>();
/**
* visitorId - SocketAddress映射
*/
private static Map<String, SocketAddress> visitorIdToSocketAddressMap = new HashMap<>();
/**
* SocketAddress - visitorId 映射
*/
private static Map<SocketAddress, String> socketAddressToVisitorIdMap = new HashMap<>();
/**
* visitorId - tunnelChannel 映射
*/
private static Map<String, Channel> visitorIdToTunnelChannelMap = new HashMap<>();
/**
* cache扫描器
*/
private static final ScheduledExecutorService cacheScanner = Executors.newSingleThreadScheduledExecutor(new CustomThreadFactory("cacheScanner"));
/**
* 初始化,启动一个定时器,定时清理缓存
*/
public static void init() {
cacheScanner.scheduleWithFixedDelay(ProxyUtil::cacheScan, 5, 5, TimeUnit.SECONDS);
}
public static synchronized void cacheScan() {
for (Integer key : serverPortToCmdChannelMap.keySet()) {
Channel channel = serverPortToCmdChannelMap.get(key);
if (null == channel || !channel.isRegistered()) {
serverPortToCmdChannelMap.remove(key);
}
}
for (Integer key : licenseToCmdChannelMap.keySet()) {
Channel channel = licenseToCmdChannelMap.get(key);
if (null == channel || !channel.isRegistered()) {
licenseToCmdChannelMap.remove(key);
}
}
for (Integer key : serverPortToVisitorChannel.keySet()) {
Channel channel = serverPortToVisitorChannel.get(key);
if (null == channel || !channel.isRegistered()) {
serverPortToVisitorChannel.remove(key);
}
}
for (String key : visitorIdToTunnelChannelMap.keySet()) {
Channel channel = visitorIdToTunnelChannelMap.get(key);
if (null == channel || !channel.isRegistered()) {
visitorIdToTunnelChannelMap.remove(key);
}
}
}
/**
* 初始化代理信息
@@ -139,14 +79,14 @@ public class ProxyUtil {
* @param proxyMappingList 代理映射集合
*/
public static void initProxyInfo(Integer licenseId, List<ProxyMapping> proxyMappingList) {
// licenseToServerPortMap.put(licenseId, new HashSet<>());
licenseToServerPortMap.put(licenseId, new HashSet<>());
addProxyInfo(licenseId, proxyMappingList);
}
public static void addProxyInfo(Integer licenseId, List<ProxyMapping> proxyMappingList) {
if (!CollectionUtil.isEmpty(proxyMappingList)) {
for (ProxyMapping proxyMapping : proxyMappingList) {
// licenseToServerPortMap.get(licenseId).add(proxyMapping.getServerPort());
licenseToServerPortMap.get(licenseId).add(proxyMapping.getServerPort());
proxyInfoMap.put(proxyMapping.getServerPort(), proxyMapping.getLanInfo());
}
}
@@ -156,7 +96,7 @@ public class ProxyUtil {
if (null == licenseId || null == proxyMapping) {
return;
}
// licenseToServerPortMap.get(licenseId).add(proxyMapping.getServerPort());
licenseToServerPortMap.get(licenseId).add(proxyMapping.getServerPort());
proxyInfoMap.put(proxyMapping.getServerPort(), proxyMapping.getLanInfo());
}
@@ -164,14 +104,14 @@ public class ProxyUtil {
proxyInfoMap.remove(serverPort);
}
// /**
// * 根据licenseId获取服务端端口集合
// * @param licenseId licenseId
// * @return 服务端端口集合
// */
// public static Set<Integer> getServerPortsByLicenseKey(Integer licenseId) {
// return licenseToServerPortMap.get(licenseId);
// }
/**
* 根据licenseId获取服务端端口集合
* @param licenseId licenseId
* @return 服务端端口集合
*/
public static Set<Integer> getServerPortsByLicenseKey(Integer licenseId) {
return licenseToServerPortMap.get(licenseId);
}
/**
* 根据服务端端口获取客户端代理信息
@@ -381,7 +321,7 @@ public class ProxyUtil {
* @param visitorId
* @param proxyAttachment
*/
public static void addProxyConnectAttachment(String visitorId, Constants.ProxyAttachment proxyAttachment) {
public static void addProxyConnectAttachment(String visitorId, ProxyAttachment proxyAttachment) {
proxyConnectAttachmentMap.put(visitorId, proxyAttachment);
}
@@ -390,7 +330,7 @@ public class ProxyUtil {
* @param visitorId
* @return
*/
public static Constants.ProxyAttachment getProxyConnectAttachment(String visitorId) {
public static ProxyAttachment getProxyConnectAttachment(String visitorId) {
return proxyConnectAttachmentMap.get(visitorId);
}
@@ -496,7 +436,7 @@ public class ProxyUtil {
if (StringUtils.isBlank(visitorId)) {
return;
}
Constants.ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(visitorId);
ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(visitorId);
if (null != proxyAttachment) {
tryClose(channel);
}
@@ -539,50 +479,4 @@ public class ProxyUtil {
public static void removeClientIdByLicenseId(Integer licenseId) {
licenseIdToClientIdMap.remove(licenseId);
}
public static void setVisitorIdToSocketAddressMap(String visitorId, SocketAddress socketAddress) {
visitorIdToSocketAddressMap.put(visitorId, socketAddress);
socketAddressToVisitorIdMap.put(socketAddress, visitorId);
}
public static SocketAddress getSocketAddressByVisitorId(String visitorId) {
return visitorIdToSocketAddressMap.get(visitorId);
}
public static void removeSocketAddressByVisitorId(String visitorId) {
SocketAddress socketAddress = visitorIdToSocketAddressMap.get(visitorId);
visitorIdToSocketAddressMap.remove(visitorId);
socketAddressToVisitorIdMap.remove(socketAddress);
visitorIdToTunnelChannelMap.remove(visitorId);
}
public static String getVisitorIdBySocketAddress(SocketAddress socketAddress) {
return socketAddressToVisitorIdMap.get(socketAddress);
}
public static void setVisitorIdToTunnelChannelMap(String visitorId, Channel tunnelChannel) {
visitorIdToTunnelChannelMap.put(visitorId, tunnelChannel);
}
public static Channel getTunnelChannelByVisitorId(String visitorId) {
return visitorIdToTunnelChannelMap.get(visitorId);
}
public static StatsInfoRes.CacheInfo getCacheInfo() {
return new StatsInfoRes.CacheInfo()
.setProxyInfoMapSize(proxyInfoMap.size())
.setServerPortToCmdChannelMapSize(serverPortToCmdChannelMap.size())
.setLicenseToCmdChannelMapSize(licenseToCmdChannelMap.size())
.setServerPortToVisitorChannelMapSize(serverPortToVisitorChannel.size())
.setProxyConnectAttachmentMapSize(proxyConnectAttachmentMap.size())
.setFullDomainToServerPortMapSize(fullDomainToServerPortMap.size())
.setDomainToDomainNameIdMapSize(domainToDomainNameIdMap.size())
.setLicenseIdToClientIdMapSize(licenseIdToClientIdMap.size())
.setVisitorIdToSocketAddressMapSize(visitorIdToSocketAddressMap.size())
.setSocketAddressToVisitorIdMapSize(socketAddressToVisitorIdMap.size())
.setVisitorIdToTunnelChannelMapSize(visitorIdToTunnelChannelMap.size())
;
}
}
@@ -12,9 +12,6 @@ solon.logging:
neutrino:
proxy:
protocol:
# 高低水位线,如:32KB/64KB、32KB/1MB、1MB/5MB
# water-mark: 1MB/8MB
# 隧道相关配置-用于维持服务端与客户端的通信
tunnel:
# 线程池相关配置,用于技术调优,可忽略
@@ -5,7 +5,7 @@ server:
solon:
app:
name: neutrino-proxy-server
version: 2.0.4
version: 2.0.2
config:
add: ./app.yml
# 日志级别
@@ -32,8 +32,6 @@ neutrino:
read-idle-time: 120
write-idle-time: 20
all-idle-time-seconds: 0
# 高低水位线,如:32KB/64KB、32KB/1MB、1MB/5MB
# water-mark: 1MB/8MB
# 隧道相关配置-用于维持服务端与客户端的通信
tunnel:
# 线程池相关配置,用于技术调优,可忽略
@@ -7,7 +7,7 @@ permalink: /pages/eebea1/
## 1、环境准备
- 首先确保已安装Java21运行环境
- 打开[发行版页面](https://gitee.com/dromara/neutrino-proxy/releases),下载最新的release包:`neutrino-proxy-server-jdk21-2.0.2-jar.zip``neutrino-proxy-client-jdk21-2.0.2-jar.zip`
- 百度网盘下载速度慢?[点击这里加速](https://docs.xigexb.com/s/neutrino-proxy/doc/neutrino-proxy-CROFc0fdYh),此站点由[喜鸽小宝](https://www.xigexb.com)提供。
## 2、部署服务端
- 在服务器上新建部署目录:`/work/projects/neutrino-proxy-server`
@@ -19,7 +19,6 @@ permalink: /pages/69699a/
## 1、安装包下载
- 打开[发行版页面](https://gitee.com/dromara/neutrino-proxy/releases),下载所需的最新的release包:
- 比如服务器为linux则可下载`neutrino-proxy-server-linux-2.0.2-native.zip`文件,客户端为windows则可下载`neutrino-proxy-client-windows-2.0.2-native.zip`
- 百度网盘下载速度慢?[点击这里加速](https://docs.xigexb.com/s/neutrino-proxy/doc/neutrino-proxy-CROFc0fdYh),此站点由[喜鸽小宝](https://www.xigexb.com)提供。
## 2、部署服务端
- 将服务端安装包上传至服务器,并解压
@@ -3,10 +3,8 @@ title: 里程碑
date: 2023-10-26 17:41:26
permalink: /pages/e406dd/
---
- 2025-08-14 中微子代理Gitee Star数突破2000
- 2024-12-20 中微子代理服务端支持宝塔面板一件部署
- 2024-12-10 2.0.2版本发布,新增域名管理,端口映射支持绑定多个域名
- 2024-08-12 中微子代理Gitcode 荣获G-Star认证
- 2023-12-21 2.0.1版本发布,jdk版本升级到21,支持安全组(黑/白名单IP限制)、限速
- 2023-10-31 2.0.0版本发布,升级jdk版本至jdk17、支持原生编译、去掉sqlite改为默认H2数据库
- 2023-09-25 中微子代理Gitee Star数突破1000
+1
View File
@@ -29,6 +29,7 @@
<revision>2.0.3</revision>
<native.version>0.9.28</native.version>
<java.version>21</java.version>
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
<maven-flatten.version>1.1.0</maven-flatten.version>
@@ -51,7 +51,7 @@ neutrino:
# 数据库类型,目前支持h2、mysql、mariadb
type: mysql
# 数据库连接URL
url: jdbc:mysql://mysql:3306/neutrino-proxy?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useAffectedRows=true&useSSL=false&allowPublicKeyRetrieval=true
url: jdbc:mysql://mysql:3306/neutrino-proxy?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useAffectedRows=true&useSSL=false
# 数据库用户名
username: root
# 数据库密码