Compare commits

..
29 Commits
Author SHA1 Message Date
aoshiguchen 6389c8bf43 更新版本号 2026-01-28 09:30:44 +08:00
aoshiguchen c478d8ba80 新增水位线配置. 2026-01-26 18:17:55 +08:00
aoshiguchen a93646619e 新增水位线配置 2026-01-26 18:04:09 +08:00
aoshiguchen f83f9e45a4 增加日志 2026-01-26 15:44:27 +08:00
aoshiguchen 2104f829ef 增加cache大小检查接口 2026-01-20 11:46:07 +08:00
aoshiguchen 456ac900e9 针对HTTP代理附加对象的优化 2026-01-20 10:54:12 +08:00
aoshiguchen 72d79b5ccf 删除无用的缓存:license -> 服务端口映射 2026-01-20 10:17:03 +08:00
aoshiguchen 2ae5259670 代码优化. 2026-01-20 10:10:58 +08:00
aoshiguchen 0c5c7908ae 代码优化 2026-01-19 14:39:13 +08:00
aoshiguchen 7282e32ac5 代码优化 2026-01-16 13:19:53 +08:00
aoshiguchen 810661d5f4 连接关闭、异常处理优化 2026-01-15 15:17:27 +08:00
aoshiguchen 7dc605ab7c solon版本从3.4.1退回2.7.6 2025-11-23 13:46:48 +08:00
aoshiguchen 150c69d37c 解决通过mc基岩 udp代理,同一个代理端口只能有一个人连接的问题 2025-11-23 13:06:30 +08:00
aoshiguchen 9cbcf4de2e 异常日志调整 2025-11-19 17:05:34 +08:00
aoshiguchen f124557686 官网更新 2025-11-19 14:22:17 +08:00
aoshiguchen 4a7df310f1 更新docker-compose脚本 2025-11-11 10:06:38 +08:00
aoshiguchen e0aaccc949 新增注释 2025-11-01 22:57:04 +08:00
aoshiguchen da4b030234 udp代理优化 2025-10-27 11:50:33 +08:00
aoshiguchen 7e7a1546b3 日志调整 2025-10-27 10:45:52 +08:00
aoshiguchen b001247088 更新里程碑记录 2025-10-17 14:39:25 +08:00
aoshiguchen b83e40051e 更新里程碑记录 2025-10-14 09:47:30 +08:00
傲世孤尘 a58902f984 !67 solon 升为 3.4.1
Merge pull request !67 from 西东/dev
2025-07-28 02:45:26 +00:00
noear 9188a41ad6 solon 升为 3.4.1 2025-07-26 08:19:24 +08:00
aoshiguchen e88671c880 更新README 2025-07-18 16:33:39 +08:00
aoshiguchen 82773034c6 端口映射列表展示优化,多域名时鼠标悬浮自动下拉,点击自动复制 2025-05-30 22:26:59 +08:00
aoshiguchen 2e33f9ff1a tmp 2025-05-25 10:30:27 +08:00
aoshiguchen 23f3ec1ba2 tmp... 2025-05-25 10:20:34 +08:00
aoshiguchen 666f071e37 tmp... 2025-05-25 10:19:09 +08:00
aoshiguchen bd56ce094a 优化https多级主域名存在包含关系时的匹配机制 2025-05-24 23:40:02 +08:00
49 changed files with 1157 additions and 235 deletions
+1 -1
View File
@@ -16,7 +16,7 @@
- 中微子代理(neutrino-proxy)是一个基于netty的、开源的java内网穿透项目。
- 技术栈:Solon、MybatisPlus、Netty
- 遵循MIT许可,因此您可以对它进行复制、修改、传播并用于任何个人或商业行为。
- 官网地址1https://neutrino-proxy.dromara.org
- 官网地址:https://neutrino-proxy-docs.asgc.fun
- 快速上手请[点击这里](https://neutrino-proxy.dromara.org/neutrino-proxy/pages/793dcb/)
# 2、名称由来
@@ -51,9 +51,18 @@
</el-table-column>
<el-table-column align="center" :label="$t('table.domainName')" width="190">
<template slot-scope="scope">
<div v-for="(domain, index) in scope.row.allFullDomainList" :key="index">
<span>{{ domain }}</span>
</div>
<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>-->
</template>
</el-table-column>
<el-table-column align="center" :label="$t('table.serverPort')" width="80">
@@ -428,6 +437,13 @@ 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,6 +1,10 @@
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;
@@ -9,6 +13,7 @@ import org.noear.solon.annotation.Inject;
* @author: aoshiguchen
* @date: 2022/6/16
*/
@Slf4j
@Data
@Component
public class ProxyConfig {
@@ -29,6 +34,8 @@ public class ProxyConfig {
private Integer readIdleTime;
private Integer writeIdleTime;
private Integer allIdleTimeSeconds;
// 水位线
private String waterMark;
}
@Data
@@ -71,4 +78,38 @@ 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,8 +1,6 @@
package org.dromara.neutrinoproxy.client.config;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
@@ -16,7 +14,6 @@ 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;
@@ -108,6 +105,12 @@ 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>() {
@@ -165,6 +168,12 @@ 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,5 +1,6 @@
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;
@@ -13,6 +14,9 @@ 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
@@ -58,8 +62,29 @@ public class CmdChannelHandler extends SimpleChannelInboundHandler<ProxyMessage>
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("[CMD Channel]Client CmdChannel Error channelId:{}", ctx.channel().id().asLongText(), cause);
ctx.close();
// 对于网络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);
}
}
@Override
@@ -1,14 +1,16 @@
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 io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import java.io.IOException;
import java.net.SocketException;
/**
* 处理与被代理客户端的数据传输
@@ -55,9 +57,10 @@ public class RealServerChannelHandler extends SimpleChannelInboundHandler<ByteBu
Channel realServerChannel = ctx.channel();
String visitorId = ProxyUtil.getVisitorIdByRealServerChannel(realServerChannel);
ProxyUtil.removeRealServerChannel(visitorId);
Channel channel = realServerChannel.attr(Constants.NEXT_CHANNEL).get();
if (channel != null) {
channel.writeAndFlush(ProxyMessage.buildDisconnectMessage(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);
}
super.channelInactive(ctx);
@@ -76,6 +79,28 @@ public class RealServerChannelHandler extends SimpleChannelInboundHandler<ByteBu
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("Client ProxyChannel Error", 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("[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);
}
}
}
@@ -1,9 +1,8 @@
package org.dromara.neutrinoproxy.client.core;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.client.util.ProxyUtil;
@@ -12,6 +11,9 @@ 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
@@ -43,18 +45,43 @@ public class TcpProxyChannelHandler extends SimpleChannelInboundHandler<ProxyMes
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 数据传输连接
Channel realServerChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (realServerChannel != null && realServerChannel.isActive()) {
realServerChannel.close();
if (null != realServerChannel && realServerChannel.isActive()) {
// realServerChannel.close();
realServerChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.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 {
log.error("[TCP Proxy Channel]Client ProxyChannel Error channelId:{}", ctx.channel().id().asLongText(), cause);
ctx.close();
// 对于网络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);
}
}
@Override
@@ -1,9 +1,8 @@
package org.dromara.neutrinoproxy.client.core;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.client.util.ProxyUtil;
@@ -12,6 +11,9 @@ 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
@@ -44,17 +46,40 @@ public class UdpProxyChannelHandler extends SimpleChannelInboundHandler<ProxyMes
// 数据传输连接
Channel realServerChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (realServerChannel != null && realServerChannel.isActive()) {
realServerChannel.close();
// realServerChannel.close();
realServerChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
ProxyUtil.removeTcpProxyChanel(ctx.channel());
ProxyUtil.returnUdpProxyChanel(ctx.channel());
ProxyUtil.removeUdpProxyChanel(ctx.channel());
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("[UDP Proxy Channel]Client ProxyChannel Error channelId:{}", ctx.channel().id().asLongText(), cause);
ctx.close();
// 对于网络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);
}
}
@Override
@@ -63,16 +88,18 @@ public class UdpProxyChannelHandler extends SimpleChannelInboundHandler<ProxyMes
IdleStateEvent event = (IdleStateEvent)evt;
switch (event.state()) {
case READER_IDLE:
// 读超时,断开连接
log.info("[UDP Proxy Channel]Read timeout");
ctx.channel().close();
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,12 +3,16 @@ 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
@@ -36,6 +40,47 @@ 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,14 +1,10 @@
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;
@@ -23,12 +19,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,6 +23,8 @@ public class LockChannel {
private long proxyTimeoutMs;
// 被获取的时间
private Date takeTime;
// 已经响应的次数
// 最后一次活跃的时间(最后发生读写的时间),每次发送或响应需要重置
private Date lastActiveTime;
// 已经响应的次数(相对于最后一次发送的时,每次发送后需要重置)
private int responseCount;
}
@@ -180,8 +180,7 @@ 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");
@@ -0,0 +1,75 @@
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,28 +133,40 @@ public class UdpServerUtil {
* @return
*/
public static synchronized Channel takeChannel(ProxyMessage.UdpBaseInfo info, Channel tunnelChannel) {
if (info.getProxyResponses() <= 0 || info.getProxyTimeoutMs() <= 0) {
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) {
return defaultUdpServerChannel;
}
// 没有空闲的 傀儡端口,降级为不需要响应
Integer port = udpServerFreePortPool.poll();
if (null == port) {
return defaultUdpServerChannel;
}
Channel channel = portToChannelMap.get(port);
if (null == channel) {
channel = bindPort(port);
portToChannelMap.put(port, channel);
realServerChannel = portToChannelMap.get(port);
if (null == realServerChannel) {
realServerChannel = bindPort(port);
portToChannelMap.put(port, realServerChannel);
}
// 添加到锁定队列
LockChannel lockChannel = new LockChannel()
.setPort(port)
.setChannel(channel)
.setChannel(realServerChannel)
.setProxyResponses(info.getProxyResponses())
.setProxyTimeoutMs(info.getProxyTimeoutMs())
.setTakeTime(new Date())
.setLastActiveTime(new Date())
.setResponseCount(0);
lockChannelList.add(lockChannel);
channel.attr(Constants.UDP_CHANNEL_BIND_KEY).set(new UdpChannelBindInfo()
realServerChannel.attr(Constants.UDP_CHANNEL_BIND_KEY).set(new UdpChannelBindInfo()
.setTunnelChannel(tunnelChannel)
.setVisitorId(info.getVisitorId())
.setVisitorIp(info.getVisitorIp())
@@ -164,7 +176,12 @@ public class UdpServerUtil {
.setTargetPort(info.getTargetPort())
.setLockChannel(lockChannel)
);
return channel;
// 连接绑定
realServerChannel.attr(org.dromara.neutrinoproxy.core.Constants.NEXT_CHANNEL).set(tunnelChannel);
tunnelChannel.attr(org.dromara.neutrinoproxy.core.Constants.NEXT_CHANNEL).set(realServerChannel);
return realServerChannel;
}
/**
@@ -177,8 +194,8 @@ public class UdpServerUtil {
Iterator<LockChannel> iter = lockChannelList.iterator();
if (iter.hasNext()) {
LockChannel lockChannel = iter.next();
if (lockChannel.getResponseCount() >= lockChannel.getProxyResponses() ||
System.currentTimeMillis() - lockChannel.getTakeTime().getTime() >= lockChannel.getProxyTimeoutMs()
if ((lockChannel.getProxyResponses() > 0 && lockChannel.getResponseCount() >= lockChannel.getProxyResponses()) ||
System.currentTimeMillis() - lockChannel.getLastActiveTime().getTime() > lockChannel.getProxyTimeoutMs()
) {
iter.remove();
UdpChannelBindInfo udpChannelBindInfo = lockChannel.getChannel().attr(Constants.UDP_CHANNEL_BIND_KEY).get();
@@ -186,6 +203,17 @@ 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,6 +4,9 @@ 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.2
version: 2.0.4
# 日志级别
solon.logging.appender:
console:
@@ -31,6 +31,8 @@ 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,6 +4,7 @@ import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import java.net.InetSocketAddress;
import java.util.function.BiConsumer;
/**
*
@@ -33,6 +34,8 @@ 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;
@@ -51,4 +54,20 @@ 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,8 +37,17 @@ 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,13 +25,14 @@ public class AppLoadEndExecutor implements EventListener<AppLoadEndEvent> {
System.out.printf("""
---------------------------------------------------------------
Neutrino Proxy Server %s
admin: http://localhost:8888
admin: http://localhost:%s
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"));
%n""", Solon.app().cfg().get("solon.app.version"),
Solon.app().cfg().get("server.port"));
}
}
@@ -1,6 +1,10 @@
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;
@@ -9,6 +13,7 @@ import org.noear.solon.annotation.Inject;
* @author: aoshiguchen
* @date: 2022/6/16
*/
@Slf4j
@Data
@Component
public class ProxyConfig {
@@ -38,6 +43,8 @@ public class ProxyConfig {
private Integer readIdleTime;
private Integer writeIdleTime;
private Integer allIdleTimeSeconds;
// 水位线
private String waterMark;
}
@Data
@@ -76,4 +83,37 @@ 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,10 +1,9 @@
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.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
@@ -15,14 +14,13 @@ 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;
@@ -47,6 +45,8 @@ public class ProxyConfiguration implements LifecycleBean {
null : ProxyDataTypeEnum.of((int)proxyMessage.getType()).getName());
Solon.context().wrapAndPut(Dispatcher.class, dispatcher);
ProxyUtil.init();
}
@Bean("tcpServerBossGroup")
@@ -67,6 +67,11 @@ 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>() {
@@ -75,7 +80,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.error("global error", e);
log.debug("global error", e);
if (e instanceof ServiceException) {
ServiceException serviceException = (ServiceException) e;
@@ -0,0 +1,26 @@
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());
}
}
@@ -0,0 +1,31 @@
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,5 +1,6 @@
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;
@@ -17,7 +18,9 @@ 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;
/**
@@ -51,6 +54,7 @@ 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);
@@ -58,6 +62,13 @@ 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();
@@ -74,7 +85,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());
@@ -104,11 +115,29 @@ public class ProxyTunnelChannelHandler extends SimpleChannelInboundHandler<Proxy
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// super.exceptionCaught(ctx, cause);
// if (ctx.channel().isActive()) {
// ctx.channel().close();
// }
log.error("[Tunnel Channel] error", 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("[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自己处理
log.error("[Tunnel Channel] error", cause);
}
}
@Override
@@ -1,5 +1,7 @@
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;
@@ -54,6 +56,12 @@ 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
@@ -91,8 +99,7 @@ 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,10 +2,9 @@ package org.dromara.neutrinoproxy.server.proxy.core;
import cn.hutool.core.util.StrUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyMessage;
@@ -15,7 +14,9 @@ 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;
/**
*
@@ -27,9 +28,29 @@ public class TcpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteBu
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// 当出现异常就关闭连接
ctx.close();
log.error("VisitorChannel error", 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);
}
}
@Override
@@ -95,11 +116,7 @@ public class TcpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteBu
InetSocketAddress sa = (InetSocketAddress) visitorChannel.localAddress();
Channel cmdChannel = ProxyUtil.getCmdChannelByServerPort(sa.getPort());
if (null == cmdChannel) {
// 该端口还没有代理客户端
ctx.channel().close();
} else {
if (null != cmdChannel) {
// 用户连接断开,从控制连接中移除
String visitorId = ProxyUtil.getVisitorIdByChannel(visitorChannel);
ProxyUtil.removeVisitorChannelFromCmdChannel(cmdChannel, visitorId);
@@ -116,6 +133,8 @@ 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);
}
}
@@ -138,6 +157,7 @@ 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,7 +10,6 @@ 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;
@@ -33,8 +32,13 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
byte[] bytes = new byte[datagramPacket.content().readableBytes()];
datagramPacket.content().readBytes(bytes);
datagramPacket.content().resetReaderIndex();
ProxyAttachment proxyAttachment = new ProxyAttachment(ctx.channel(), bytes, (channel, buf) -> {
Channel proxyChannel = channel.attr(Constants.NEXT_CHANNEL).get();
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();
if (null == proxyChannel) {
// // 该端口还没有代理客户端
@@ -49,7 +53,6 @@ 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())
@@ -65,10 +68,11 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
Solon.context().getBean(FlowReportService.class).addWriteByte(visitorChannelAttachInfo.getLicenseId(), bytes.length);
});
Channel proxyChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (null != proxyChannel && proxyChannel.isActive()) {
String visitorId = ProxyUtil.getVisitorIdBySocketAddress(datagramPacket.sender());
Channel proxyChannel = ProxyUtil.getTunnelChannelByVisitorId(visitorId);
if (StrUtil.isNotBlank(visitorId) && null != proxyChannel && proxyChannel.isActive()) {
// UDP代理隧道已就绪直接转发
proxyAttachment.execute();
proxyAttachment.execute(ctx.channel());
return;
}
@@ -95,8 +99,10 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
// // 用户连接到代理服务器时设置用户连接不可读等待代理后端服务器连接成功后再改变为可读状态
// visitorChannel.config().setOption(ChannelOption.AUTO_READ, false);
// TODO UDP此处叫visitor似有不妥与TCP不同,2.x重构思考
String visitorId = ProxyUtil.newVisitorId();
// UDP场景下一个visitorId并不对应一个visitorChannel所有visitor共用一个visitorChannel
visitorId = ProxyUtil.newVisitorId();
// 设置udp发送方的地址
ProxyUtil.setVisitorIdToSocketAddressMap(visitorId, datagramPacket.sender());
// 此处需要和tcp分开
ProxyUtil.addVisitorChannelToCmdChannel(NetworkProtocolEnum.UDP, cmdChannel, visitorId, visitorChannel, sa.getPort());
ProxyUtil.addProxyConnectAttachment(visitorId, proxyAttachment);
@@ -105,6 +111,7 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
.setServerPort(sa.getPort())
.setTargetIp(targetIp)
.setTargetPort(targetPort)
// connect消息没有传超时时间响应数量导致客户端日志输出的超时时间响应数量都是0
));
}
@@ -113,12 +120,32 @@ public class UdpVisitorChannelHandler extends SimpleChannelInboundHandler<Datagr
super.channelActive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// 当出现异常就关闭连接
ctx.close();
log.error("[UDP Visitor Channel]VisitorChannel error", cause);
}
// @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 channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
@@ -1,29 +1,28 @@
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);
}
}
}
//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);
// }
// }
//}
@@ -8,7 +8,6 @@ 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;
@@ -45,7 +44,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.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
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();
ProxyAttachment proxyAttachment = new ProxyAttachment(ctx.channel(), bytes, (channel, buf) -> {
Constants.ProxyAttachment proxyAttachment = new Constants.ProxyAttachment(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();
proxyAttachment.execute(ctx.channel());
return;
}
@@ -70,7 +70,8 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteB
visitorId = ProxyUtil.newVisitorId();
ProxyUtil.addVisitorChannelToCmdChannel(NetworkProtocolEnum.HTTP, cmdChannel, visitorId, ctx.channel(), serverPort);
ProxyUtil.addProxyConnectAttachment(visitorId, proxyAttachment);
// ProxyUtil.addProxyConnectAttachment(visitorId, proxyAttachment);
ctx.channel().attr(Constants.PROXY_CONNECT_ATTACHMENT).set(proxyAttachment);
cmdChannel.writeAndFlush(ProxyMessage.buildConnectMessage(visitorId).setData(lanInfo.getBytes()));
}
@@ -82,11 +83,7 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteB
InetSocketAddress sa = (InetSocketAddress) visitorChannel.localAddress();
Channel cmdChannel = ProxyUtil.getCmdChannelByServerPort(sa.getPort());
if (cmdChannel == null) {
// 该端口还没有代理客户端
ctx.channel().close();
} else {
if (null != cmdChannel) {
// 用户连接断开从控制连接中移除
String visitorId = ProxyUtil.getVisitorIdByChannel(visitorChannel);
ProxyUtil.removeVisitorChannelFromCmdChannel(cmdChannel, visitorId);
@@ -103,6 +100,8 @@ 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);
}
}
@@ -116,8 +115,29 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler<ByteB
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// 当出现异常就关闭连接
ctx.close();
// 对于网络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);
}
}
@Override
@@ -10,7 +10,6 @@ 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;
@@ -51,7 +50,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,7 +7,6 @@ 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;
@@ -76,8 +75,11 @@ 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);
@@ -86,13 +88,24 @@ public class ProxyMessageConnectHandler implements ProxyMessageHandler {
// 代理客户端与后端服务器连接成功修改用户连接为可读状态
visitorChannel.config().setOption(ChannelOption.AUTO_READ, true);
// 获取代理附加对象
ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(visitorId);
if (null != proxyAttachment) {
// 及时释放
ProxyUtil.remoteProxyConnectAttachment(visitorId);
proxyAttachment.execute();
}
// 获取代理附加对象
Constants.ProxyAttachment proxyAttachment = visitorChannel.attr(Constants.PROXY_CONNECT_ATTACHMENT).get();
if (null != proxyAttachment) {
// 转发来自visitor的首次代理数据
proxyAttachment.execute(visitorChannel);
// 此处时TCP代理不一定有代理附加对象不能因为没有而直接释放visitorChannel
}
// // 获取代理附加对象
// ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(visitorId);
// if (null != proxyAttachment) {
// // 及时释放
// ProxyUtil.remoteProxyConnectAttachment(visitorId);
// proxyAttachment.execute();
// }
}
@Override
@@ -38,6 +38,8 @@ 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,7 +14,6 @@ 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;
@@ -87,16 +86,18 @@ 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());
visitorChannel.attr(Constants.NEXT_CHANNEL).set(ctx.channel());
// 所有udb visitor共用一个visitorChannel设置这个没啥用
// visitorChannel.attr(Constants.NEXT_CHANNEL).set(ctx.channel());
ProxyUtil.setVisitorIdToTunnelChannelMap(udpBaseInfo.getVisitorId(), ctx.channel());
visitorChannel.attr(Constants.IS_UDP_KEY).set(Boolean.TRUE);
// // 代理客户端与后端服务器连接成功修改用户连接为可读状态
// visitorChannel.config().setOption(ChannelOption.AUTO_READ, true);
// 获取代理附加对象
ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(udpBaseInfo.getVisitorId());
Constants.ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(udpBaseInfo.getVisitorId());
if (null != proxyAttachment) {
// 及时释放
ProxyUtil.remoteProxyConnectAttachment(udpBaseInfo.getVisitorId());
proxyAttachment.execute();
proxyAttachment.execute(visitorChannel);
}
}
@@ -31,33 +31,31 @@ 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) {
if (null == visitorChannel) {
return;
}
if (!visitorChannel.isWritable()) {
//自己不可写通道可以读让通道关闭读
//自己可写通道不可以读让通道打开读
if (ctx.channel().config().isAutoRead()) {
ctx.channel().config().setAutoRead(false);
}
} else {
if (ctx.channel().config().isAutoRead()) {
ctx.channel().config().setAutoRead(true);
}
if (!visitorChannel.isWritable()) {
//自己不可写通道可以读让通道关闭读
//自己可写通道不可以读让通道打开读
if (ctx.channel().config().isAutoRead()) {
ctx.channel().config().setAutoRead(false);
}
} else {
if (ctx.channel().config().isAutoRead()) {
ctx.channel().config().setAutoRead(true);
}
}
// 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));
}
InetSocketAddress address = ctx.channel().attr(Constants.SENDER).get();
if (null != address) {
visitorChannel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(proxyMessage.getData()), address));
}
// 增加流量计数(TODO 如果UDP映射服务端端口修改这个似乎不准)
Integer licenseId = visitorChannel.attr(Constants.LICENSE_ID).get();
if (null != licenseId) {
Solon.context().getBean(FlowReportService.class).addReadByte(licenseId, proxyMessage.getData().length);
}
// 增加流量计数(TODO 如果UDP映射服务端端口修改这个似乎不准)
Integer licenseId = visitorChannel.attr(Constants.LICENSE_ID).get();
if (null != licenseId) {
Solon.context().getBean(FlowReportService.class).addReadByte(licenseId, proxyMessage.getData().length);
}
}
@@ -2,13 +2,14 @@ package org.dromara.neutrinoproxy.server.proxy.security;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
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;
@@ -17,6 +18,10 @@ 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
@@ -109,4 +114,64 @@ 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,18 +1,22 @@
package org.dromara.neutrinoproxy.server.proxy.security;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DecoderException;
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
@@ -65,4 +69,64 @@ 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,16 +1,20 @@
package org.dromara.neutrinoproxy.server.proxy.security;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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
@@ -36,4 +40,64 @@ 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,16 +1,14 @@
package org.dromara.neutrinoproxy.server.proxy.security;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.*;
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
@@ -47,4 +45,63 @@ 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,17 +15,11 @@ 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,17 +4,23 @@ 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;
@@ -27,16 +33,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<>();
/**
@@ -58,8 +64,10 @@ public class ProxyUtil {
private static AtomicLong visitorIdProducer = new AtomicLong(0);
/**
* 代理 - connect附加映射
* TCP/HTTP场景下已优化不是用这个UDP由于无连接暂时还是要用这个
* UDP场景时需要记录最后读写时间使用定时器定期检查超时需要释放待后续优化
*/
private static Map<String, ProxyAttachment> proxyConnectAttachmentMap = new HashMap<>();
private static Map<String, Constants.ProxyAttachment> proxyConnectAttachmentMap = new HashMap<>();
/**
* 完整域名 - 服务端端口映射
*/
@@ -72,6 +80,58 @@ 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);
}
}
}
/**
* 初始化代理信息
@@ -79,14 +139,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());
}
}
@@ -96,7 +156,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());
}
@@ -104,14 +164,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);
// }
/**
* 根据服务端端口获取客户端代理信息
@@ -321,7 +381,7 @@ public class ProxyUtil {
* @param visitorId
* @param proxyAttachment
*/
public static void addProxyConnectAttachment(String visitorId, ProxyAttachment proxyAttachment) {
public static void addProxyConnectAttachment(String visitorId, Constants.ProxyAttachment proxyAttachment) {
proxyConnectAttachmentMap.put(visitorId, proxyAttachment);
}
@@ -330,7 +390,7 @@ public class ProxyUtil {
* @param visitorId
* @return
*/
public static ProxyAttachment getProxyConnectAttachment(String visitorId) {
public static Constants.ProxyAttachment getProxyConnectAttachment(String visitorId) {
return proxyConnectAttachmentMap.get(visitorId);
}
@@ -414,9 +474,9 @@ public class ProxyUtil {
* 通过完整域名获取域名
*/
public static String getDomainNameByFullDomain(String fullDomain) {
List<String> domains = domainToDomainNameIdMap.keySet().stream().filter(item -> fullDomain.endsWith(item)).collect(Collectors.toList());
List<String> domains = domainToDomainNameIdMap.keySet().stream().sorted((a,b) -> b.length() - a.length()).filter(item -> fullDomain.endsWith(item)).collect(Collectors.toList());
// 不存在 或者 有多条记录返回null
if (CollectionUtil.isEmpty(domains) || domains.size() > 1) {
if (CollectionUtil.isEmpty(domains)) {
return null;
}
return domains.getFirst();
@@ -436,7 +496,7 @@ public class ProxyUtil {
if (StringUtils.isBlank(visitorId)) {
return;
}
ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(visitorId);
Constants.ProxyAttachment proxyAttachment = ProxyUtil.getProxyConnectAttachment(visitorId);
if (null != proxyAttachment) {
tryClose(channel);
}
@@ -479,4 +539,50 @@ 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,6 +12,9 @@ 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.2
version: 2.0.4
config:
add: ./app.yml
# 日志级别
@@ -32,6 +32,8 @@ 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,6 +19,7 @@ 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,8 +3,10 @@ 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,7 +29,6 @@
<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
url: jdbc:mysql://mysql:3306/neutrino-proxy?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useAffectedRows=true&useSSL=false&allowPublicKeyRetrieval=true
# 数据库用户名
username: root
# 数据库密码