Search in sources :

Example 11 with NetClient

use of io.vertx.core.net.NetClient in project vert.x by eclipse.

the class SocksProxy method start.

/**
 * Start the server.
 *
 * @param vertx
 *          Vertx instance to use for creating the server and client
 */
@Override
public SocksProxy start(Vertx vertx) throws Exception {
    NetServerOptions options = new NetServerOptions();
    options.setHost("localhost").setPort(PORT);
    server = vertx.createNetServer(options);
    server.connectHandler(socket -> {
        socket.handler(buffer -> {
            Buffer expectedInit = username == null ? clientInit : clientInitAuth;
            if (!buffer.equals(expectedInit)) {
                throw new IllegalStateException("expected " + toHex(expectedInit) + ", got " + toHex(buffer));
            }
            boolean useAuth = buffer.equals(clientInitAuth);
            log.debug("got request: " + toHex(buffer));
            final Handler<Buffer> handler = buffer2 -> {
                if (!buffer2.getBuffer(0, clientRequest.length()).equals(clientRequest)) {
                    throw new IllegalStateException("expected " + toHex(clientRequest) + ", got " + toHex(buffer2));
                }
                int addressType = buffer2.getUnsignedByte(3);
                String host;
                int port;
                if (addressType == 1) {
                    if (buffer2.length() != 10) {
                        throw new IllegalStateException("format error in client request (attribute type ipv4), got " + toHex(buffer2));
                    }
                    host = buffer2.getUnsignedByte(4) + "." + buffer2.getUnsignedByte(5) + "." + buffer2.getUnsignedByte(6) + "." + buffer2.getUnsignedByte(7);
                    port = buffer2.getUnsignedShort(8);
                } else if (addressType == 3) {
                    int stringLen = buffer2.getUnsignedByte(4);
                    log.debug("string len " + stringLen);
                    if (buffer2.length() != 7 + stringLen) {
                        throw new IllegalStateException("format error in client request (attribute type domain name), got " + toHex(buffer2));
                    }
                    host = buffer2.getString(5, 5 + stringLen);
                    port = buffer2.getUnsignedShort(5 + stringLen);
                } else {
                    throw new IllegalStateException("expected address type ip (v4) or name, got " + addressType);
                }
                log.debug("got request: " + toHex(buffer2));
                log.debug("connect: " + host + ":" + port);
                socket.handler(null);
                lastUri = host + ":" + port;
                if (forceUri != null) {
                    host = forceUri.substring(0, forceUri.indexOf(':'));
                    port = Integer.valueOf(forceUri.substring(forceUri.indexOf(':') + 1));
                }
                log.debug("connecting to " + host + ":" + port);
                NetClient netClient = vertx.createNetClient(new NetClientOptions());
                netClient.connect(port, host, result -> {
                    if (result.succeeded()) {
                        log.debug("writing: " + toHex(connectResponse));
                        socket.write(connectResponse);
                        log.debug("connected, starting pump");
                        NetSocket clientSocket = result.result();
                        socket.closeHandler(v -> clientSocket.close());
                        clientSocket.closeHandler(v -> socket.close());
                        Pump.pump(socket, clientSocket).start();
                        Pump.pump(clientSocket, socket).start();
                    } else {
                        log.error("exception", result.cause());
                        socket.handler(null);
                        log.debug("writing: " + toHex(errorResponse));
                        socket.write(errorResponse);
                        socket.close();
                    }
                });
            };
            if (useAuth) {
                socket.handler(buffer3 -> {
                    log.debug("auth handler");
                    log.debug("got request: " + toHex(buffer3));
                    Buffer authReply = Buffer.buffer(new byte[] { 1, (byte) username.length() });
                    authReply.appendString(username);
                    authReply.appendByte((byte) username.length());
                    authReply.appendString(username);
                    if (!buffer3.equals(authReply)) {
                        log.debug("expected " + toHex(authReply) + ", got " + toHex(buffer3));
                        socket.handler(null);
                        log.debug("writing: " + toHex(authFailed));
                        socket.write(authFailed);
                        socket.close();
                    } else {
                        socket.handler(handler);
                        log.debug("writing: " + toHex(authSuccess));
                        socket.write(authSuccess);
                    }
                });
                log.debug("writing: " + toHex(serverReplyAuth));
                socket.write(serverReplyAuth);
            } else {
                socket.handler(handler);
                log.debug("writing: " + toHex(serverReply));
                socket.write(serverReply);
            }
        });
    });
    CompletableFuture<Void> fut = new CompletableFuture<>();
    server.listen(ar -> {
        if (ar.succeeded()) {
            fut.complete(null);
        } else {
            fut.completeExceptionally(ar.cause());
        }
    });
    fut.get(10, TimeUnit.SECONDS);
    log.debug("socks5 server started");
    return this;
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Logger(io.vertx.core.impl.logging.Logger) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) Vertx(io.vertx.core.Vertx) CompletableFuture(java.util.concurrent.CompletableFuture) NetClientOptions(io.vertx.core.net.NetClientOptions) TimeUnit(java.util.concurrent.TimeUnit) NetServerOptions(io.vertx.core.net.NetServerOptions) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) Pump(io.vertx.core.streams.Pump) Handler(io.vertx.core.Handler) NetClient(io.vertx.core.net.NetClient) NetSocket(io.vertx.core.net.NetSocket) NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) CompletableFuture(java.util.concurrent.CompletableFuture) NetClient(io.vertx.core.net.NetClient) NetServerOptions(io.vertx.core.net.NetServerOptions)

Example 12 with NetClient

use of io.vertx.core.net.NetClient in project vert.x by eclipse.

the class Socks4Proxy method start.

/**
 * Start the server.
 *
 * @param vertx
 *          Vertx instance to use for creating the server and client
 */
@Override
public Socks4Proxy start(Vertx vertx) throws Exception {
    NetServerOptions options = new NetServerOptions();
    options.setHost("localhost").setPort(PORT);
    server = vertx.createNetServer(options);
    server.connectHandler(socket -> {
        socket.handler(buffer -> {
            if (!buffer.getBuffer(0, clientRequest.length()).equals(clientRequest)) {
                throw new IllegalStateException("expected " + toHex(clientRequest) + ", got " + toHex(buffer));
            }
            log.debug("got request: " + toHex(buffer));
            int port = buffer.getUnsignedShort(2);
            String ip = getByte4(buffer.getBuffer(4, 8));
            String authUsername = getString(buffer.getBuffer(8, buffer.length()));
            if (username != null && !authUsername.equals(username)) {
                log.debug("auth failed");
                log.debug("writing: " + toHex(errorResponse));
                socket.write(errorResponse);
                socket.close();
            } else {
                String host;
                if (ip.equals("0.0.0.1")) {
                    host = getString(buffer.getBuffer(9 + authUsername.length(), buffer.length()));
                } else {
                    host = ip;
                }
                log.debug("connect: " + host + ":" + port);
                socket.handler(null);
                lastUri = host + ":" + port;
                if (forceUri != null) {
                    host = forceUri.substring(0, forceUri.indexOf(':'));
                    port = Integer.valueOf(forceUri.substring(forceUri.indexOf(':') + 1));
                }
                log.debug("connecting to " + host + ":" + port);
                NetClient netClient = vertx.createNetClient(new NetClientOptions());
                netClient.connect(port, host, result -> {
                    if (result.succeeded()) {
                        log.debug("writing: " + toHex(connectResponse));
                        socket.write(connectResponse);
                        log.debug("connected, starting pump");
                        NetSocket clientSocket = result.result();
                        socket.closeHandler(v -> clientSocket.close());
                        clientSocket.closeHandler(v -> socket.close());
                        Pump.pump(socket, clientSocket).start();
                        Pump.pump(clientSocket, socket).start();
                    } else {
                        log.error("exception", result.cause());
                        socket.handler(null);
                        log.debug("writing: " + toHex(errorResponse));
                        socket.write(errorResponse);
                        socket.close();
                    }
                });
            }
        });
    });
    CompletableFuture<Void> fut = new CompletableFuture<>();
    server.listen(ar -> {
        if (ar.succeeded()) {
            fut.complete(null);
        } else {
            fut.completeExceptionally(ar.cause());
        }
    });
    fut.get(10, TimeUnit.SECONDS);
    log.debug("socks4a server started");
    return this;
}
Also used : NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) CompletableFuture(java.util.concurrent.CompletableFuture) NetClient(io.vertx.core.net.NetClient) NetServerOptions(io.vertx.core.net.NetServerOptions)

Example 13 with NetClient

use of io.vertx.core.net.NetClient in project vert.x by eclipse.

the class VertxImpl method createNetClient.

public NetClient createNetClient(NetClientOptions options) {
    CloseFuture closeFuture = new CloseFuture(log);
    NetClient client = createNetClient(options, closeFuture);
    CloseFuture fut = resolveCloseFuture();
    fut.add(closeFuture);
    return client;
}
Also used : NetClient(io.vertx.core.net.NetClient)

Example 14 with NetClient

use of io.vertx.core.net.NetClient in project vert.x by eclipse.

the class HostnameResolutionTest method testResolveMissingLocalhost.

@Test
public void testResolveMissingLocalhost() throws Exception {
    InetAddress localhost = InetAddress.getByName("localhost");
    // Set a dns resolver that won't resolve localhost
    dnsServer.testResolveASameServer("127.0.0.1");
    // Test using the resolver API
    VertxInternal vertx = (VertxInternal) vertx(new VertxOptions().setAddressResolverOptions(new AddressResolverOptions().addServer(dnsServerAddress.getAddress().getHostAddress() + ":" + dnsServerAddress.getPort()).setOptResourceEnabled(false)));
    CompletableFuture<Void> test1 = new CompletableFuture<>();
    vertx.resolveAddress("localhost", ar -> {
        if (ar.succeeded()) {
            InetAddress resolved = ar.result();
            if (resolved.equals(localhost)) {
                test1.complete(null);
            } else {
                test1.completeExceptionally(new AssertionError("Unexpected localhost value " + resolved));
            }
        } else {
            test1.completeExceptionally(ar.cause());
        }
    });
    test1.get(10, TimeUnit.SECONDS);
    CompletableFuture<Void> test2 = new CompletableFuture<>();
    vertx.resolveAddress("LOCALHOST", ar -> {
        if (ar.succeeded()) {
            InetAddress resolved = ar.result();
            if (resolved.equals(localhost)) {
                test2.complete(null);
            } else {
                test2.completeExceptionally(new AssertionError("Unexpected localhost value " + resolved));
            }
        } else {
            test2.completeExceptionally(ar.cause());
        }
    });
    test2.get(10, TimeUnit.SECONDS);
    // Test using bootstrap
    CompletableFuture<Void> test3 = new CompletableFuture<>();
    NetServer server = vertx.createNetServer(new NetServerOptions().setPort(1234).setHost(localhost.getHostAddress()));
    try {
        server.connectHandler(so -> {
            so.end(Buffer.buffer("hello"));
        });
        server.listen(ar -> {
            if (ar.succeeded()) {
                test3.complete(null);
            } else {
                test3.completeExceptionally(ar.cause());
            }
        });
        test3.get(10, TimeUnit.SECONDS);
        CompletableFuture<Void> test4 = new CompletableFuture<>();
        NetClient client = vertx.createNetClient();
        client.connect(1234, "localhost", ar -> {
            if (ar.succeeded()) {
                test4.complete(null);
            } else {
                test4.completeExceptionally(ar.cause());
            }
        });
        test4.get(10, TimeUnit.SECONDS);
    } finally {
        server.close();
    }
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) VertxInternal(io.vertx.core.impl.VertxInternal) NetClient(io.vertx.core.net.NetClient) NetServerOptions(io.vertx.core.net.NetServerOptions) NetServer(io.vertx.core.net.NetServer) InetAddress(java.net.InetAddress) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test)

Example 15 with NetClient

use of io.vertx.core.net.NetClient in project vert.x by eclipse.

the class HostnameResolutionTest method testNet.

private void testNet(String hostname) throws Exception {
    NetClient client = vertx.createNetClient();
    NetServer server = vertx.createNetServer().connectHandler(so -> {
        so.handler(buff -> {
            so.write(buff);
            so.close();
        });
    });
    try {
        CountDownLatch listenLatch = new CountDownLatch(1);
        server.listen(1234, hostname, onSuccess(s -> {
            listenLatch.countDown();
        }));
        awaitLatch(listenLatch);
        client.connect(1234, hostname, onSuccess(so -> {
            Buffer buffer = Buffer.buffer();
            so.handler(buffer::appendBuffer);
            so.closeHandler(v -> {
                assertEquals(Buffer.buffer("foo"), buffer);
                testComplete();
            });
            so.write(Buffer.buffer("foo"));
        }));
        await();
    } finally {
        client.close();
        server.close();
    }
}
Also used : VertxException(io.vertx.core.VertxException) RecordClass(org.apache.directory.server.dns.messages.RecordClass) java.util(java.util) HttpServer(io.vertx.core.http.HttpServer) CompletableFuture(java.util.concurrent.CompletableFuture) VertxTestBase(io.vertx.test.core.VertxTestBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) InetAddress(java.net.InetAddress) TestUtils(io.vertx.test.core.TestUtils) JsonObject(io.vertx.core.json.JsonObject) FakeDNSServer(io.vertx.test.fakedns.FakeDNSServer) NetClient(io.vertx.core.net.NetClient) ResourceRecord(org.apache.directory.server.dns.messages.ResourceRecord) VertxImpl(io.vertx.core.impl.VertxImpl) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) AddressResolver(io.vertx.core.impl.AddressResolver) DnsAttribute(org.apache.directory.server.dns.store.DnsAttribute) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) CountDownLatch(java.util.concurrent.CountDownLatch) NetServerOptions(io.vertx.core.net.NetServerOptions) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) HttpMethod(io.vertx.core.http.HttpMethod) RecordType(org.apache.directory.server.dns.messages.RecordType) HttpClient(io.vertx.core.http.HttpClient) Buffer(io.vertx.core.buffer.Buffer) NetClient(io.vertx.core.net.NetClient) NetServer(io.vertx.core.net.NetServer) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

NetClient (io.vertx.core.net.NetClient)52 NetSocket (io.vertx.core.net.NetSocket)35 Test (org.junit.Test)34 NetServerOptions (io.vertx.core.net.NetServerOptions)24 Vertx (io.vertx.core.Vertx)23 JsonObject (io.vertx.core.json.JsonObject)21 Async (io.vertx.ext.unit.Async)20 Handler (io.vertx.core.Handler)19 FrameParser (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameParser)19 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)19 NetClientOptions (io.vertx.core.net.NetClientOptions)17 BridgeOptions (io.vertx.ext.bridge.BridgeOptions)16 PermittedOptions (io.vertx.ext.bridge.PermittedOptions)16 Before (org.junit.Before)16 Message (io.vertx.core.eventbus.Message)15 BridgeEventType (io.vertx.ext.bridge.BridgeEventType)15 FrameHelper (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameHelper)15 TestContext (io.vertx.ext.unit.TestContext)15 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)15 After (org.junit.After)15