use of org.rx.net.dns.DnsServer in project rxlib by RockyLOMO.
the class Main method main.
@SneakyThrows
public static void main(String[] args) {
Map<String, String> options = App.argsOptions(args);
Integer port = Reflects.tryConvert(options.get("port"), Integer.class);
if (port == null) {
log.info("Invalid port arg");
return;
}
Main app;
Integer connectTimeout = Reflects.tryConvert(options.get("connectTimeout"), Integer.class, 60000);
String mode = options.get("shadowMode");
boolean udp2raw = false;
if (eq(mode, "1")) {
AuthenticEndpoint shadowUser = Reflects.tryConvert(options.get("shadowUser"), AuthenticEndpoint.class);
if (shadowUser == null) {
log.info("Invalid shadowUser arg");
return;
}
SocksUser ssUser = new SocksUser(shadowUser.getUsername());
ssUser.setPassword(shadowUser.getPassword());
ssUser.setMaxIpCount(-1);
SocksConfig backConf = new SocksConfig(port);
backConf.setTransportFlags(TransportFlags.FRONTEND_COMPRESS.flags());
backConf.setMemoryMode(MemoryMode.MEDIUM);
backConf.setConnectTimeoutMillis(connectTimeout);
backConf.setEnableUdp2raw(udp2raw);
SocksProxyServer backSvr = new SocksProxyServer(backConf, (u, p) -> eq(u, ssUser.getUsername()) && eq(p, ssUser.getPassword()) ? ssUser : SocksUser.ANONYMOUS);
backSvr.setAesRouter(SocksProxyServer.DNS_AES_ROUTER);
// server port + 1 = rpc
RpcServerConfig rpcConf = new RpcServerConfig(port + 1);
rpcConf.setTransportFlags(TransportFlags.FRONTEND_AES_COMBO.flags());
Remoting.listen(app = new Main(backSvr), rpcConf);
} else {
String[] arg1 = Strings.split(options.get("shadowUsers"), ",");
if (arg1.length == 0) {
log.info("Invalid shadowUsers arg");
return;
}
RandomList<UpstreamSupport> shadowServers = new RandomList<>();
SocksConfig frontConf = new SocksConfig(port);
YamlConfiguration watcher = new YamlConfiguration("conf.yml").enableWatch();
watcher.onChanged.combine((s, e) -> {
SSConf changed = s.readAs(SSConf.class);
if (changed == null) {
return;
}
conf = changed;
NQuery<AuthenticEndpoint> svrs = NQuery.of(conf.shadowServer).select(p -> Reflects.tryConvert(p, AuthenticEndpoint.class));
if (!svrs.any() || svrs.any(Objects::isNull)) {
throw new InvalidException("Invalid shadowServer arg");
}
for (UpstreamSupport support : shadowServers) {
tryClose(support.getSupport());
}
shadowServers.clear();
for (AuthenticEndpoint shadowServer : svrs) {
RpcClientConfig rpcConf = RpcClientConfig.poolMode(Sockets.newEndpoint(shadowServer.getEndpoint(), shadowServer.getEndpoint().getPort() + 1), 2, 6);
rpcConf.setTransportFlags(TransportFlags.BACKEND_AES_COMBO.flags());
String weight = shadowServer.getParameters().get("w");
if (Strings.isEmpty(weight)) {
continue;
}
shadowServers.add(new UpstreamSupport(shadowServer, Remoting.create(SocksSupport.class, rpcConf)), Integer.parseInt(weight));
}
log.info("reload svrs {}", toJsonString(svrs));
if (conf.bypassHosts != null) {
frontConf.getBypassList().addAll(conf.bypassHosts);
}
});
watcher.raiseChange();
NQuery<Tuple<ShadowsocksConfig, SocksUser>> shadowUsers = NQuery.of(arg1).select(shadowUser -> {
String[] sArgs = Strings.split(shadowUser, ":", 4);
ShadowsocksConfig config = new ShadowsocksConfig(Sockets.anyEndpoint(Integer.parseInt(sArgs[0])), CipherKind.AES_256_GCM.getCipherName(), sArgs[1]);
SocksUser user = new SocksUser(sArgs[2]);
user.setPassword(conf.socksPwd);
user.setMaxIpCount(Integer.parseInt(sArgs[3]));
return Tuple.of(config, user);
});
Integer shadowDnsPort = Reflects.tryConvert(options.get("shadowDnsPort"), Integer.class, 53);
DnsServer dnsSvr = new DnsServer(shadowDnsPort);
// 12 hour
dnsSvr.setTtl(60 * 60 * 10);
dnsSvr.setShadowServers(shadowServers);
dnsSvr.addHostsFile("hosts.txt");
InetSocketAddress shadowDnsEp = Sockets.localEndpoint(shadowDnsPort);
Sockets.injectNameService(Collections.singletonList(shadowDnsEp));
frontConf.setTransportFlags(TransportFlags.BACKEND_COMPRESS.flags());
frontConf.setMemoryMode(MemoryMode.MEDIUM);
frontConf.setConnectTimeoutMillis(connectTimeout);
frontConf.setEnableUdp2raw(conf.udp2raw);
frontConf.setUdp2rawServers(NQuery.of(shadowServers).select(p -> p.getEndpoint().getEndpoint()).toList());
if (frontConf.isEnableUdp2raw() && conf.udp2rawEndpoint != null) {
log.info("udp2rawEndpoint: {}", conf.udp2rawEndpoint);
AuthenticEndpoint udp2rawSvrEp = AuthenticEndpoint.valueOf(conf.udp2rawEndpoint);
frontConf.getUdp2rawServers().add(udp2rawSvrEp.getEndpoint());
}
SocksProxyServer frontSvr = new SocksProxyServer(frontConf, Authenticator.dbAuth(shadowUsers.select(p -> p.right).toList(), port + 1));
Upstream shadowDnsUpstream = new Upstream(new UnresolvedEndpoint(shadowDnsEp));
TripleAction<SocksProxyServer, RouteEventArgs> firstRoute = (s, e) -> {
UnresolvedEndpoint dstEp = e.getDestinationEndpoint();
// must first
if (dstEp.getPort() == SocksSupport.DNS_PORT) {
e.setValue(shadowDnsUpstream);
return;
}
// bypass
if (frontConf.isBypass(dstEp.getHost())) {
e.setValue(new Upstream(dstEp));
}
};
frontSvr.onRoute.replace(firstRoute, (s, e) -> {
if (e.getValue() != null) {
return;
}
e.setValue(new Socks5Upstream(e.getDestinationEndpoint(), frontConf, () -> shadowServers.next(e.getSourceEndpoint(), conf.steeringTTL, true)));
});
frontSvr.onUdpRoute.replace(firstRoute, (s, e) -> {
if (e.getValue() != null) {
return;
}
UnresolvedEndpoint dstEp = e.getDestinationEndpoint();
if (conf.pcap2socks && e.getSourceEndpoint().getAddress().isLoopbackAddress()) {
Cache<String, Boolean> cache = Cache.getInstance(Cache.MEMORY_CACHE);
if (cache.get(hashKey("pcap", e.getSourceEndpoint().getPort()), k -> Sockets.socketInfos(SocketProtocol.UDP).any(p -> p.getSource().getPort() == e.getSourceEndpoint().getPort() && Strings.startsWith(p.getProcessName(), "pcap2socks")))) {
log.info("pcap2socks forward");
e.setValue(new Upstream(dstEp));
return;
}
}
// if (frontConf.isEnableUdp2raw()) {
// if (udp2rawSvrEp != null) {
// e.setValue(new Upstream(dstEp, udp2rawSvrEp));
// } else {
// e.setValue(new Upstream(dstEp, shadowServers.next().getEndpoint()));
// }
// return;
// }
e.setValue(new Socks5UdpUpstream(dstEp, frontConf, () -> shadowServers.next(e.getSourceEndpoint(), conf.steeringTTL, true)));
});
frontSvr.setAesRouter(SocksProxyServer.DNS_AES_ROUTER);
app = new Main(frontSvr);
Action fn = () -> {
InetAddress addr = InetAddress.getByName(IPSearcher.DEFAULT.current().getIp());
eachQuietly(shadowServers, p -> p.getSupport().addWhiteList(addr));
};
fn.invoke();
Tasks.schedule(fn, conf.autoWhiteListSeconds * 1000L);
InetSocketAddress frontSvrEp = Sockets.localEndpoint(port);
for (Tuple<ShadowsocksConfig, SocksUser> tuple : shadowUsers) {
ShadowsocksConfig ssConfig = tuple.left;
SocksUser user = tuple.right;
AuthenticEndpoint srvEp = new AuthenticEndpoint(frontSvrEp, user.getUsername(), user.getPassword());
ssConfig.setMemoryMode(MemoryMode.MEDIUM);
ssConfig.setConnectTimeoutMillis(connectTimeout);
SocksConfig directConf = new SocksConfig(port);
frontConf.setMemoryMode(MemoryMode.MEDIUM);
frontConf.setConnectTimeoutMillis(connectTimeout);
ShadowsocksServer server = new ShadowsocksServer(ssConfig);
TripleAction<ShadowsocksServer, RouteEventArgs> ssFirstRoute = (s, e) -> {
UnresolvedEndpoint dstEp = e.getDestinationEndpoint();
// must first
if (dstEp.getPort() == SocksSupport.DNS_PORT) {
e.setValue(shadowDnsUpstream);
return;
}
// bypass
if (ssConfig.isBypass(dstEp.getHost())) {
log.info("ss bypass: {}", dstEp);
e.setValue(new Upstream(dstEp));
}
};
server.onRoute.replace(ssFirstRoute, (s, e) -> {
if (e.getValue() != null) {
return;
}
// gateway
IPAddress ipAddress = awaitQuietly(() -> IPSearcher.DEFAULT.search(e.getDestinationEndpoint().getHost()), SocksSupport.ASYNC_TIMEOUT / 2);
if (ipAddress != null && ipAddress.isChina()) {
e.setValue(new Upstream(e.getDestinationEndpoint()));
return;
}
e.setValue(new Socks5Upstream(e.getDestinationEndpoint(), directConf, () -> new UpstreamSupport(srvEp, null)));
});
server.onUdpRoute.replace(ssFirstRoute, (s, e) -> {
if (e.getValue() != null) {
return;
}
e.setValue(new Upstream(e.getDestinationEndpoint(), srvEp));
});
}
app.ddns();
}
log.info("Server started..");
app.await();
}
use of org.rx.net.dns.DnsServer in project rxlib by RockyLOMO.
the class SocksTester method dns.
@SneakyThrows
@Test
public synchronized void dns() {
// System.out.println(HttpClient.godaddyDns("", "f-li.cn", "dd", "3.3.3.3"));
InetSocketAddress nsEp = Sockets.parseEndpoint("114.114.114.114:53");
InetSocketAddress localNsEp = Sockets.parseEndpoint("127.0.0.1:54");
final InetAddress ip2 = InetAddress.getByName("2.2.2.2");
final InetAddress ip4 = InetAddress.getByName("4.4.4.4");
DnsServer server = new DnsServer(54, nsEp);
server.setShadowServers(new RandomList<>(Collections.singletonList(new UpstreamSupport(null, new SocksSupport() {
@Override
public void fakeEndpoint(SUID hash, String realEndpoint) {
}
@Override
public List<InetAddress> resolveHost(String host) {
return DnsClient.inlandClient().resolveAll(host);
}
@Override
public void addWhiteList(InetAddress endpoint) {
}
}))));
server.setHostsTtl(5);
server.addHosts(host_devops, 2, Arrays.toList(ip2, ip4));
// hostTtl
DnsClient client = new DnsClient(Collections.singletonList(localNsEp));
List<InetAddress> result = client.resolveAll(host_devops);
System.out.println("eq: " + result);
assert result.contains(ip2) && result.contains(ip4);
Tasks.setTimeout(() -> {
server.removeHosts(host_devops, Collections.singletonList(ip2));
List<InetAddress> x = client.resolveAll(host_devops);
System.out.println(toJsonString(x));
assert x.contains(ip4);
_exit();
}, 6000);
InetAddress wanIp = InetAddress.getByName(HttpClient.getWanIp());
// IPAddress current = IPSearcher.DEFAULT.current();
// System.out.println(current);
List<InetAddress> currentIps = DnsClient.inlandClient().resolveAll(host_devops);
System.out.println("ddns: " + wanIp + " = " + currentIps);
// 注入变更 InetAddress.getAllByName 内部查询dnsServer的地址,支持非53端口
Sockets.injectNameService(Collections.singletonList(localNsEp));
List<InetAddress> wanResult = DnsClient.inlandClient().resolveAll(host_devops);
InetAddress[] localResult = InetAddress.getAllByName(host_devops);
System.out.println("wanResolve: " + wanResult + " != " + toJsonString(localResult));
assert !wanResult.get(0).equals(localResult[0]);
server.addHostsFile(path("hosts.txt"));
assert client.resolve(host_cloud).equals(InetAddress.getByName("192.168.31.7"));
wait();
}
use of org.rx.net.dns.DnsServer in project rxlib by RockyLOMO.
the class SocksTester method ssProxy.
@SneakyThrows
@Test
public void ssProxy() {
int shadowDnsPort = 853;
DnsServer dnsSvr = new DnsServer(shadowDnsPort);
InetSocketAddress shadowDnsEp = Sockets.localEndpoint(shadowDnsPort);
Upstream shadowDnsUpstream = new Upstream(new UnresolvedEndpoint(shadowDnsEp));
String defPwd = "123456";
SocksConfig backConf = new SocksConfig(2080);
backConf.setEnableUdp2raw(true);
backConf.setUdp2rawServers(Collections.emptyList());
SocksUser usr = new SocksUser("rocky");
usr.setPassword(defPwd);
usr.setMaxIpCount(-1);
SocksProxyServer backSvr = new SocksProxyServer(backConf, Authenticator.dbAuth(Collections.singletonList(usr), null));
AuthenticEndpoint srvEp = new AuthenticEndpoint(Sockets.localEndpoint(backConf.getListenPort()), usr.getUsername(), usr.getPassword());
ShadowsocksConfig config = new ShadowsocksConfig(Sockets.anyEndpoint(2090), CipherKind.AES_128_GCM.getCipherName(), defPwd);
ShadowsocksServer server = new ShadowsocksServer(config);
server.onRoute.combine((s, e) -> {
UnresolvedEndpoint dstEp = e.getDestinationEndpoint();
// must first
if (dstEp.getPort() == SocksSupport.DNS_PORT) {
e.setValue(shadowDnsUpstream);
return;
}
// bypass
if (config.isBypass(dstEp.getHost())) {
e.setValue(new Upstream(dstEp));
return;
}
e.setValue(new Socks5Upstream(dstEp, backConf, () -> new UpstreamSupport(srvEp, null)));
});
server.onUdpRoute.combine((s, e) -> {
UnresolvedEndpoint dstEp = e.getDestinationEndpoint();
// must first
if (dstEp.getPort() == SocksSupport.DNS_PORT) {
e.setValue(shadowDnsUpstream);
}
// bypass
if (config.isBypass(dstEp.getHost())) {
e.setValue(new Upstream(dstEp));
}
e.setValue(new Upstream(dstEp));
// return new Upstream(dstEp, srvEp);
});
// ShadowsocksClient client = new ShadowsocksClient(1080, config);
System.in.read();
}
use of org.rx.net.dns.DnsServer in project rxlib by RockyLOMO.
the class SocksTester method socks5Proxy.
@SneakyThrows
@Test
public void socks5Proxy() {
boolean udp2raw = false;
boolean udp2rawDirect = false;
Udp2rawHandler.DEFAULT.setGzipMinLength(40);
InetSocketAddress backSrvEp = Sockets.localEndpoint(2080);
int shadowDnsPort = 853;
// backend
SocksConfig backConf = new SocksConfig(backSrvEp.getPort());
backConf.setTransportFlags(TransportFlags.FRONTEND_COMPRESS.flags());
backConf.setConnectTimeoutMillis(connectTimeoutMillis);
backConf.setEnableUdp2raw(udp2raw);
SocksProxyServer backSvr = new SocksProxyServer(backConf, null);
// backSvr.setAesRouter(SocksProxyServer.DNS_AES_ROUTER);
RpcServerConfig rpcServerConf = new RpcServerConfig(backSrvEp.getPort() + 1);
rpcServerConf.setTransportFlags(TransportFlags.FRONTEND_COMPRESS.flags());
Remoting.listen(new Main(backSvr), rpcServerConf);
// dns
DnsServer dnsSvr = new DnsServer(shadowDnsPort);
InetSocketAddress shadowDnsEp = Sockets.localEndpoint(shadowDnsPort);
// Sockets.injectNameService(shadowDnsEp);
// frontend
RandomList<UpstreamSupport> shadowServers = new RandomList<>();
RpcClientConfig rpcClientConf = RpcClientConfig.poolMode(Sockets.newEndpoint(backSrvEp, backSrvEp.getPort() + 1), 2, 2);
rpcClientConf.setTransportFlags(TransportFlags.BACKEND_COMPRESS.flags());
shadowServers.add(new UpstreamSupport(new AuthenticEndpoint(backSrvEp), Remoting.create(SocksSupport.class, rpcClientConf)));
SocksConfig frontConf = new SocksConfig(2090);
frontConf.setTransportFlags(TransportFlags.BACKEND_COMPRESS.flags());
frontConf.setConnectTimeoutMillis(connectTimeoutMillis);
frontConf.setEnableUdp2raw(udp2raw);
if (!udp2rawDirect) {
frontConf.setUdp2rawServers(Arrays.toList(backSrvEp));
} else {
frontConf.setUdp2rawServers(Collections.emptyList());
}
SocksProxyServer frontSvr = new SocksProxyServer(frontConf);
Upstream shadowDnsUpstream = new Upstream(new UnresolvedEndpoint(shadowDnsEp));
TripleAction<SocksProxyServer, RouteEventArgs> firstRoute = (s, e) -> {
UnresolvedEndpoint dstEp = e.getDestinationEndpoint();
// must first
if (dstEp.getPort() == SocksSupport.DNS_PORT) {
e.setValue(shadowDnsUpstream);
return;
}
// bypass
if (frontConf.isBypass(dstEp.getHost())) {
e.setValue(new Upstream(dstEp));
}
};
frontSvr.onRoute.combine(firstRoute, (s, e) -> {
if (e.getValue() != null) {
return;
}
e.setValue(new Socks5Upstream(e.getDestinationEndpoint(), frontConf, () -> shadowServers.next()));
});
frontSvr.onUdpRoute.combine(firstRoute, (s, e) -> {
if (e.getValue() != null) {
return;
}
UnresolvedEndpoint dstEp = e.getDestinationEndpoint();
if (frontConf.isEnableUdp2raw()) {
if (!udp2rawDirect) {
e.setValue(new Upstream(dstEp, shadowServers.next().getEndpoint()));
} else {
e.setValue(new Upstream(dstEp));
}
return;
}
e.setValue(new Socks5UdpUpstream(dstEp, frontConf, shadowServers::next));
});
// frontSvr.setAesRouter(SocksProxyServer.DNS_AES_ROUTER);
// sleep(2000);
// for (UpstreamSupport support : shadowServers) {
// support.getSupport().addWhiteList(InetAddress.getByName(HttpClient.getWanIp()));
// }
System.in.read();
}
Aggregations