Search in sources :

Example 1 with UnresolvedEndpoint

use of org.rx.net.support.UnresolvedEndpoint in project rxlib by RockyLOMO.

the class Socks5CommandRequestHandler method relay.

private void relay(Channel inbound, Channel outbound, Socks5AddressType dstAddrType, UnresolvedEndpoint dstEp, StringBuilder extMsg) {
    UnresolvedEndpoint realEp = SocksContext.realDestination(inbound);
    ConcurrentLinkedQueue<Object> pendingPackages = new ConcurrentLinkedQueue<>();
    inbound.pipeline().addLast(FrontendRelayHandler.PIPELINE_NAME, new FrontendRelayHandler(outbound, pendingPackages));
    outbound.pipeline().addLast(BackendRelayHandler.PIPELINE_NAME, new BackendRelayHandler(inbound, pendingPackages));
    inbound.writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS, dstAddrType)).addListener((ChannelFutureListener) f -> {
        if (!f.isSuccess()) {
            Sockets.closeOnFlushed(f.channel());
            return;
        }
        SocksProxyServer server = SocksContext.server(inbound);
        SocksConfig config = server.getConfig();
        if (server.aesRouter(realEp) && config.getTransportFlags().has(TransportFlags.FRONTEND_COMPRESS)) {
            ChannelHandler[] handlers = new AESCodec(config.getAesKey()).channelHandlers();
            for (int i = handlers.length - 1; i > -1; i--) {
                ChannelHandler handler = handlers[i];
                inbound.pipeline().addAfter(TransportUtil.ZIP_DECODER, handler.getClass().getSimpleName(), handler);
            }
            extMsg.append("[FRONTEND_AES]");
        }
        log.info("socks5[{}] {} => {} connected, dstEp={}[{}] {}", config.getListenPort(), inbound.localAddress(), outbound.remoteAddress(), dstEp, realEp, extMsg.toString());
        SocksSupport.ENDPOINT_TRACER.link(inbound, outbound);
    });
}
Also used : TransportUtil(org.rx.net.TransportUtil) Socks5ProxyHandler(org.rx.net.socks.upstream.Socks5ProxyHandler) SneakyThrows(lombok.SneakyThrows) UnresolvedEndpoint(org.rx.net.support.UnresolvedEndpoint) SocksSupport(org.rx.net.support.SocksSupport) AESCodec(org.rx.net.AESCodec) InetSocketAddress(java.net.InetSocketAddress) ExceptionHandler(org.rx.exception.ExceptionHandler) StringBuilder(org.rx.core.StringBuilder) Inet6Address(java.net.Inet6Address) Slf4j(lombok.extern.slf4j.Slf4j) TransportFlags(org.rx.net.TransportFlags) io.netty.handler.codec.socksx.v5(io.netty.handler.codec.socksx.v5) Sockets(org.rx.net.Sockets) io.netty.channel(io.netty.channel) SUID(org.rx.bean.SUID) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) UnresolvedEndpoint(org.rx.net.support.UnresolvedEndpoint) AESCodec(org.rx.net.AESCodec) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue)

Example 2 with UnresolvedEndpoint

use of org.rx.net.support.UnresolvedEndpoint 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 3 with UnresolvedEndpoint

use of org.rx.net.support.UnresolvedEndpoint in project rxlib by RockyLOMO.

the class Socks5Upstream method initChannel.

@SneakyThrows
@Override
public void initChannel(Channel channel) {
    UpstreamSupport next = router.invoke();
    if (next == null) {
        throw new InvalidException("ProxyHandlers is empty");
    }
    AuthenticEndpoint svrEp = next.getEndpoint();
    SocksSupport support = next.getSupport();
    TransportUtil.addBackendHandler(channel, config, svrEp.getEndpoint());
    if (support != null && (SocksSupport.FAKE_IPS.contains(destination.getHost()) || SocksSupport.FAKE_PORTS.contains(destination.getPort()) || !Sockets.isValidIp(destination.getHost()))) {
        String dstEpStr = destination.toString();
        SUID hash = SUID.compute(dstEpStr);
        // 先变更
        destination = new UnresolvedEndpoint(String.format("%s%s", hash, SocksSupport.FAKE_HOST_SUFFIX), Arrays.randomNext(SocksSupport.FAKE_PORT_OBFS));
        Cache.getOrSet(hash, k -> awaitQuietly(() -> {
            App.logMetric(String.format("socks5[%s]", config.getListenPort()), dstEpStr);
            support.fakeEndpoint(hash, dstEpStr);
            return true;
        }, SocksSupport.ASYNC_TIMEOUT));
    }
    Socks5ProxyHandler proxyHandler = new Socks5ProxyHandler(svrEp.getEndpoint(), svrEp.getUsername(), svrEp.getPassword());
    proxyHandler.setConnectTimeoutMillis(config.getConnectTimeoutMillis());
    channel.pipeline().addLast(proxyHandler);
}
Also used : UnresolvedEndpoint(org.rx.net.support.UnresolvedEndpoint) UpstreamSupport(org.rx.net.support.UpstreamSupport) AuthenticEndpoint(org.rx.net.AuthenticEndpoint) SocksSupport(org.rx.net.support.SocksSupport) InvalidException(org.rx.exception.InvalidException) SUID(org.rx.bean.SUID) SneakyThrows(lombok.SneakyThrows)

Example 4 with UnresolvedEndpoint

use of org.rx.net.support.UnresolvedEndpoint 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)

Example 5 with UnresolvedEndpoint

use of org.rx.net.support.UnresolvedEndpoint in project rxlib by RockyLOMO.

the class UdpManager method decode.

@SneakyThrows
public static UnresolvedEndpoint decode(ByteBuf buf) {
    Socks5AddressType addrType = Socks5AddressType.valueOf(buf.readByte());
    String dstAddr = Socks5AddressDecoder.DEFAULT.decodeAddress(addrType, buf);
    return new UnresolvedEndpoint(dstAddr, buf.readUnsignedShort());
}
Also used : UnresolvedEndpoint(org.rx.net.support.UnresolvedEndpoint) Socks5AddressType(io.netty.handler.codec.socksx.v5.Socks5AddressType) SneakyThrows(lombok.SneakyThrows)

Aggregations

UnresolvedEndpoint (org.rx.net.support.UnresolvedEndpoint)10 InetSocketAddress (java.net.InetSocketAddress)8 SneakyThrows (lombok.SneakyThrows)6 io.netty.channel (io.netty.channel)5 Slf4j (lombok.extern.slf4j.Slf4j)5 Sockets (org.rx.net.Sockets)5 SUID (org.rx.bean.SUID)4 AuthenticEndpoint (org.rx.net.AuthenticEndpoint)4 Upstream (org.rx.net.socks.upstream.Upstream)4 SocksSupport (org.rx.net.support.SocksSupport)4 ByteBuf (io.netty.buffer.ByteBuf)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 Inet6Address (java.net.Inet6Address)3 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)3 ExceptionHandler (org.rx.exception.ExceptionHandler)3 io.netty.handler.codec.socksx.v5 (io.netty.handler.codec.socksx.v5)2 StringBuilder (org.rx.core.StringBuilder)2