Search in sources :

Example 1 with Upstream

use of org.rx.net.socks.upstream.Upstream 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();
}
Also used : DnsServer(org.rx.net.dns.DnsServer) Extends(org.rx.core.Extends) SneakyThrows(lombok.SneakyThrows) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Upstream(org.rx.net.socks.upstream.Upstream) InvalidException(org.rx.exception.InvalidException) DnsClient(org.rx.net.dns.DnsClient) CipherKind(org.rx.net.shadowsocks.encryption.CipherKind) HttpClient(org.rx.net.http.HttpClient) InetAddress(java.net.InetAddress) TripleAction(org.rx.util.function.TripleAction) org.rx.net.socks(org.rx.net.socks) Map(java.util.Map) Socks5UdpUpstream(org.rx.net.socks.upstream.Socks5UdpUpstream) App(org.rx.core.App) org.rx.core(org.rx.core) ShadowsocksConfig(org.rx.net.shadowsocks.ShadowsocksConfig) RandomList(org.rx.bean.RandomList) ShadowsocksServer(org.rx.net.shadowsocks.ShadowsocksServer) org.rx.net.support(org.rx.net.support) Tasks.awaitQuietly(org.rx.core.Tasks.awaitQuietly) InetSocketAddress(java.net.InetSocketAddress) Tuple(org.rx.bean.Tuple) Action(org.rx.util.function.Action) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) RpcClientConfig(org.rx.net.rpc.RpcClientConfig) Data(lombok.Data) Remoting(org.rx.net.rpc.Remoting) SUID(org.rx.bean.SUID) org.rx.net(org.rx.net) RpcServerConfig(org.rx.net.rpc.RpcServerConfig) Socks5Upstream(org.rx.net.socks.upstream.Socks5Upstream) Collections(java.util.Collections) TripleAction(org.rx.util.function.TripleAction) Action(org.rx.util.function.Action) RpcServerConfig(org.rx.net.rpc.RpcServerConfig) InetSocketAddress(java.net.InetSocketAddress) InvalidException(org.rx.exception.InvalidException) RandomList(org.rx.bean.RandomList) RpcClientConfig(org.rx.net.rpc.RpcClientConfig) Upstream(org.rx.net.socks.upstream.Upstream) Socks5UdpUpstream(org.rx.net.socks.upstream.Socks5UdpUpstream) Socks5Upstream(org.rx.net.socks.upstream.Socks5Upstream) ShadowsocksConfig(org.rx.net.shadowsocks.ShadowsocksConfig) ShadowsocksServer(org.rx.net.shadowsocks.ShadowsocksServer) DnsServer(org.rx.net.dns.DnsServer) Socks5UdpUpstream(org.rx.net.socks.upstream.Socks5UdpUpstream) Socks5Upstream(org.rx.net.socks.upstream.Socks5Upstream) InetAddress(java.net.InetAddress) Tuple(org.rx.bean.Tuple) SneakyThrows(lombok.SneakyThrows)

Example 2 with Upstream

use of org.rx.net.socks.upstream.Upstream 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();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Upstream(org.rx.net.socks.upstream.Upstream) Socks5UdpUpstream(org.rx.net.socks.upstream.Socks5UdpUpstream) Socks5Upstream(org.rx.net.socks.upstream.Socks5Upstream) ShadowsocksConfig(org.rx.net.shadowsocks.ShadowsocksConfig) ShadowsocksServer(org.rx.net.shadowsocks.ShadowsocksServer) DnsServer(org.rx.net.dns.DnsServer) Socks5Upstream(org.rx.net.socks.upstream.Socks5Upstream) Test(org.junit.jupiter.api.Test) SneakyThrows(lombok.SneakyThrows)

Example 3 with Upstream

use of org.rx.net.socks.upstream.Upstream 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();
}
Also used : DnsServer(org.rx.net.dns.DnsServer) Bytes(org.rx.io.Bytes) java.util(java.util) SneakyThrows(lombok.SneakyThrows) org.rx.test.bean(org.rx.test.bean) Extends.eq(org.rx.core.Extends.eq) Upstream(org.rx.net.socks.upstream.Upstream) InvalidException(org.rx.exception.InvalidException) DnsClient(org.rx.net.dns.DnsClient) CipherKind(org.rx.net.shadowsocks.encryption.CipherKind) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) org.rx.net.http(org.rx.net.http) CollectionUtils(org.apache.commons.collections4.CollectionUtils) InetAddress(java.net.InetAddress) TripleAction(org.rx.util.function.TripleAction) ByteBuf(io.netty.buffer.ByteBuf) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) org.rx.net.socks(org.rx.net.socks) Arrays(org.rx.core.Arrays) NameserverConfig(org.rx.net.nameserver.NameserverConfig) Extends.sleep(org.rx.core.Extends.sleep) LogStrategy(org.rx.bean.LogStrategy) Socks5UdpUpstream(org.rx.net.socks.upstream.Socks5UdpUpstream) AESUtil(org.rx.security.AESUtil) App(org.rx.core.App) Main(org.rx.Main) org.rx.core(org.rx.core) ShadowsocksConfig(org.rx.net.shadowsocks.ShadowsocksConfig) RandomList(org.rx.bean.RandomList) NameserverImpl(org.rx.net.nameserver.NameserverImpl) org.rx.net.rpc(org.rx.net.rpc) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) NameserverClient(org.rx.net.nameserver.NameserverClient) java.util.concurrent(java.util.concurrent) ShadowsocksServer(org.rx.net.shadowsocks.ShadowsocksServer) org.rx.net.support(org.rx.net.support) IOException(java.io.IOException) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) MultiValueMap(org.rx.bean.MultiValueMap) Slf4j(lombok.extern.slf4j.Slf4j) JSONObject(com.alibaba.fastjson.JSONObject) SUID(org.rx.bean.SUID) IOStream(org.rx.io.IOStream) org.rx.net(org.rx.net) Socks5Upstream(org.rx.net.socks.upstream.Socks5Upstream) InetSocketAddress(java.net.InetSocketAddress) Upstream(org.rx.net.socks.upstream.Upstream) Socks5UdpUpstream(org.rx.net.socks.upstream.Socks5UdpUpstream) Socks5Upstream(org.rx.net.socks.upstream.Socks5Upstream) DnsServer(org.rx.net.dns.DnsServer) RandomList(org.rx.bean.RandomList) Socks5UdpUpstream(org.rx.net.socks.upstream.Socks5UdpUpstream) Socks5Upstream(org.rx.net.socks.upstream.Socks5Upstream) Main(org.rx.Main) Test(org.junit.jupiter.api.Test) SneakyThrows(lombok.SneakyThrows)

Example 4 with Upstream

use of org.rx.net.socks.upstream.Upstream in project rxlib by RockyLOMO.

the class Udp2rawHandler method channelRead0.

@SneakyThrows
@Override
protected void channelRead0(ChannelHandlerContext inbound, DatagramPacket in) throws Exception {
    ByteBuf inBuf = in.content();
    if (inBuf.readableBytes() < 4) {
        return;
    }
    SocksProxyServer server = SocksContext.server(inbound.channel());
    final InetSocketAddress srcEp0 = in.sender();
    List<InetSocketAddress> udp2rawServers = server.config.getUdp2rawServers();
    // client
    if (udp2rawServers != null) {
        if (!udp2rawServers.contains(srcEp0) && !clientRoutes.containsKey(srcEp0)) {
            final UnresolvedEndpoint dstEp = UdpManager.socks5Decode(inBuf);
            RouteEventArgs e = new RouteEventArgs(srcEp0, dstEp);
            server.raiseEvent(server.onUdpRoute, e);
            Upstream upstream = e.getValue();
            AuthenticEndpoint svrEp = upstream.getSocksServer();
            if (svrEp != null) {
                ByteBuf outBuf = Bytes.directBuffer(64 + inBuf.readableBytes());
                outBuf.writeShort(STREAM_MAGIC);
                outBuf.writeByte(STREAM_VERSION);
                UdpManager.encode(outBuf, new UnresolvedEndpoint(srcEp0));
                UdpManager.encode(outBuf, dstEp);
                zip(outBuf, inBuf);
                inbound.writeAndFlush(new DatagramPacket(outBuf, svrEp.getEndpoint()));
                // log.info("UDP2RAW CLIENT {} => {}[{}]", srcEp0, svrEp.getEndpoint(), dstEp);
                return;
            }
            UnresolvedEndpoint upDstEp = upstream.getDestination();
            log.debug("UDP2RAW[{}] CLIENT DIRECT {} => {}[{}]", server.config.getListenPort(), srcEp0, upDstEp, dstEp);
            inbound.writeAndFlush(new DatagramPacket(inBuf.retain(), upDstEp.socketAddress()));
            clientRoutes.put(upDstEp.socketAddress(), Tuple.of(srcEp0, dstEp));
            return;
        }
        Tuple<InetSocketAddress, UnresolvedEndpoint> upSrcs = clientRoutes.get(srcEp0);
        if (upSrcs != null) {
            ByteBuf outBuf = UdpManager.socks5Encode(inBuf, upSrcs.right);
            log.debug("UDP2RAW[{}] CLIENT DIRECT {}[{}] => {}", server.config.getListenPort(), srcEp0, upSrcs.right, upSrcs.left);
            inbound.writeAndFlush(new DatagramPacket(outBuf, upSrcs.left));
            return;
        }
        if (inBuf.readShort() != STREAM_MAGIC & inBuf.readByte() != STREAM_VERSION) {
            log.warn("discard {} bytes", inBuf.readableBytes());
            return;
        }
        UnresolvedEndpoint srcEp = UdpManager.decode(inBuf);
        UnresolvedEndpoint dstEp = UdpManager.decode(inBuf);
        ByteBuf outBuf = UdpManager.socks5Encode(inBuf, dstEp);
        inbound.writeAndFlush(new DatagramPacket(outBuf, srcEp.socketAddress()));
        // log.info("UDP2RAW CLIENT {}[{}] => {}", srcEp0, dstEp, srcEp);
        return;
    }
    // server
    if (inBuf.readShort() != STREAM_MAGIC & inBuf.readByte() != STREAM_VERSION) {
        log.warn("discard {} bytes", inBuf.readableBytes());
        return;
    }
    final UnresolvedEndpoint srcEp = UdpManager.decode(inBuf);
    final UnresolvedEndpoint dstEp = UdpManager.decode(inBuf);
    Channel outbound = UdpManager.openChannel(srcEp.socketAddress(), k -> {
        RouteEventArgs e = new RouteEventArgs(srcEp.socketAddress(), dstEp);
        server.raiseEvent(server.onUdpRoute, e);
        Upstream upstream = e.getValue();
        return SocksContext.initOutbound(Sockets.udpBootstrap(server.config.getMemoryMode(), ob -> {
            SocksContext.server(ob, server);
            upstream.initChannel(ob);
            ob.pipeline().addLast(new IdleStateHandler(0, 0, server.config.getUdpTimeoutSeconds()) {

                @Override
                protected IdleStateEvent newIdleStateEvent(IdleState state, boolean first) {
                    UdpManager.closeChannel(SocksContext.realSource(ob));
                    return super.newIdleStateEvent(state, first);
                }
            }, new SimpleChannelInboundHandler<DatagramPacket>() {

                @Override
                protected void channelRead0(ChannelHandlerContext outbound, DatagramPacket out) {
                    ByteBuf outBuf = Bytes.directBuffer(64 + out.content().readableBytes());
                    outBuf.writeShort(STREAM_MAGIC);
                    outBuf.writeByte(STREAM_VERSION);
                    UdpManager.encode(outBuf, srcEp);
                    UdpManager.encode(outBuf, dstEp);
                    outBuf.writeBytes(out.content());
                    inbound.writeAndFlush(new DatagramPacket(outBuf, srcEp0));
                // log.info("UDP2RAW SERVER {}[{}] => {}[{}]", out.sender(), dstEp, srcEp0, srcEp);
                }
            });
        }).bind(0).addListener(Sockets.logBind(0)).addListener(UdpManager.FLUSH_PENDING_QUEUE).channel(), srcEp.socketAddress(), dstEp, upstream);
    });
    ByteBuf outBuf = unzip(inBuf);
    UdpManager.pendOrWritePacket(outbound, new DatagramPacket(outBuf, dstEp.socketAddress()));
// log.info("UDP2RAW SERVER {}[{}] => {}", srcEp0, srcEp, dstEp);
}
Also used : AuthenticEndpoint(org.rx.net.AuthenticEndpoint) Setter(lombok.Setter) Bytes(org.rx.io.Bytes) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) SneakyThrows(lombok.SneakyThrows) UnresolvedEndpoint(org.rx.net.support.UnresolvedEndpoint) Upstream(org.rx.net.socks.upstream.Upstream) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MemoryStream(org.rx.io.MemoryStream) InetSocketAddress(java.net.InetSocketAddress) Tuple(org.rx.bean.Tuple) Compressible(org.rx.io.Compressible) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) ByteBuf(io.netty.buffer.ByteBuf) IdleState(io.netty.handler.timeout.IdleState) Map(java.util.Map) DatagramPacket(io.netty.channel.socket.DatagramPacket) Sockets(org.rx.net.Sockets) io.netty.channel(io.netty.channel) GZIPStream(org.rx.io.GZIPStream) AuthenticEndpoint(org.rx.net.AuthenticEndpoint) InetSocketAddress(java.net.InetSocketAddress) IdleState(io.netty.handler.timeout.IdleState) Upstream(org.rx.net.socks.upstream.Upstream) ByteBuf(io.netty.buffer.ByteBuf) UnresolvedEndpoint(org.rx.net.support.UnresolvedEndpoint) DatagramPacket(io.netty.channel.socket.DatagramPacket) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) SneakyThrows(lombok.SneakyThrows)

Example 5 with Upstream

use of org.rx.net.socks.upstream.Upstream in project rxlib by RockyLOMO.

the class Socks5UdpRelayHandler method channelRead0.

/**
 * https://datatracker.ietf.org/doc/html/rfc1928
 * +----+------+------+----------+----------+----------+
 * |RSV | FRAG | ATYP | DST.ADDR | DST.PORT |   DATA   |
 * +----+------+------+----------+----------+----------+
 * | 2  |  1   |  1   | Variable |    2     | Variable |
 * +----+------+------+----------+----------+----------+
 *
 * @param inbound
 * @param in
 * @throws Exception
 */
@Override
protected void channelRead0(ChannelHandlerContext inbound, DatagramPacket in) throws Exception {
    ByteBuf inBuf = in.content();
    if (inBuf.readableBytes() < 4) {
        return;
    }
    SocksProxyServer server = SocksContext.server(inbound.channel());
    final InetSocketAddress srcEp = in.sender();
    if (!Sockets.isNatIp(srcEp.getAddress()) && !server.config.getWhiteList().contains(srcEp.getAddress())) {
        log.warn("security error, package from {}", srcEp);
        return;
    }
    final UnresolvedEndpoint dstEp = UdpManager.socks5Decode(inBuf);
    Channel outbound = UdpManager.openChannel(srcEp, k -> {
        RouteEventArgs e = new RouteEventArgs(srcEp, dstEp);
        server.raiseEvent(server.onUdpRoute, e);
        Upstream upstream = e.getValue();
        return SocksContext.initOutbound(Sockets.udpBootstrap(server.config.getMemoryMode(), ob -> {
            SocksContext.server(ob, server);
            upstream.initChannel(ob);
            ob.pipeline().addLast(new IdleStateHandler(0, 0, server.config.getUdpTimeoutSeconds()) {

                @Override
                protected IdleStateEvent newIdleStateEvent(IdleState state, boolean first) {
                    // UdpManager.closeChannel(SocksContext.realSource(ob));
                    UdpManager.closeChannel(srcEp);
                    return super.newIdleStateEvent(state, first);
                }
            }, new SimpleChannelInboundHandler<DatagramPacket>() {

                @Override
                protected void channelRead0(ChannelHandlerContext outbound, DatagramPacket out) throws Exception {
                    InetSocketAddress srcEp = SocksContext.realSource(outbound.channel());
                    UnresolvedEndpoint dstEp = SocksContext.realDestination(outbound.channel());
                    ByteBuf outBuf = out.content();
                    if (upstream.getSocksServer() == null) {
                        outBuf = UdpManager.socks5Encode(outBuf, dstEp);
                    } else {
                        outBuf.retain();
                    }
                    inbound.writeAndFlush(new DatagramPacket(outBuf, srcEp));
                    log.debug("socks5[{}] UDP IN {}[{}] => {}", server.config.getListenPort(), out.sender(), dstEp, srcEp);
                }
            });
        }).bind(0).addListener(Sockets.logBind(0)).sync().channel(), srcEp, dstEp, upstream, false);
    });
    // todo sync改eventcallback
    Upstream upstream = SocksContext.upstream(outbound);
    // UnresolvedEndpoint upDstEp = upstream.getDestination();  //udp dstEp可能多个,但upstream只有一个,所以直接用dstEp。
    UnresolvedEndpoint upDstEp = dstEp;
    AuthenticEndpoint socksServer = upstream.getSocksServer();
    if (socksServer != null) {
        upDstEp = new UnresolvedEndpoint(socksServer.getEndpoint());
        inBuf.readerIndex(0);
    }
    UdpManager.pendOrWritePacket(outbound, new DatagramPacket(inBuf.retain(), upDstEp.socketAddress()));
    log.debug("socks5[{}] UDP OUT {} => {}[{}]", server.config.getListenPort(), srcEp, upDstEp, dstEp);
}
Also used : IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) AuthenticEndpoint(org.rx.net.AuthenticEndpoint) Slf4j(lombok.extern.slf4j.Slf4j) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) ByteBuf(io.netty.buffer.ByteBuf) UnresolvedEndpoint(org.rx.net.support.UnresolvedEndpoint) IdleState(io.netty.handler.timeout.IdleState) DatagramPacket(io.netty.channel.socket.DatagramPacket) Sockets(org.rx.net.Sockets) Upstream(org.rx.net.socks.upstream.Upstream) io.netty.channel(io.netty.channel) InetSocketAddress(java.net.InetSocketAddress) AuthenticEndpoint(org.rx.net.AuthenticEndpoint) InetSocketAddress(java.net.InetSocketAddress) IdleState(io.netty.handler.timeout.IdleState) Upstream(org.rx.net.socks.upstream.Upstream) ByteBuf(io.netty.buffer.ByteBuf) UnresolvedEndpoint(org.rx.net.support.UnresolvedEndpoint) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) DatagramPacket(io.netty.channel.socket.DatagramPacket)

Aggregations

InetSocketAddress (java.net.InetSocketAddress)7 Upstream (org.rx.net.socks.upstream.Upstream)7 Slf4j (lombok.extern.slf4j.Slf4j)5 ByteBuf (io.netty.buffer.ByteBuf)4 SneakyThrows (lombok.SneakyThrows)4 UnresolvedEndpoint (org.rx.net.support.UnresolvedEndpoint)4 io.netty.channel (io.netty.channel)3 DatagramPacket (io.netty.channel.socket.DatagramPacket)3 IdleState (io.netty.handler.timeout.IdleState)3 IdleStateEvent (io.netty.handler.timeout.IdleStateEvent)3 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)3 SUID (org.rx.bean.SUID)3 AuthenticEndpoint (org.rx.net.AuthenticEndpoint)3 Sockets (org.rx.net.Sockets)3 DnsServer (org.rx.net.dns.DnsServer)3 ShadowsocksConfig (org.rx.net.shadowsocks.ShadowsocksConfig)3 ShadowsocksServer (org.rx.net.shadowsocks.ShadowsocksServer)3 Socks5UdpUpstream (org.rx.net.socks.upstream.Socks5UdpUpstream)3 Socks5Upstream (org.rx.net.socks.upstream.Socks5Upstream)3 InetAddress (java.net.InetAddress)2