Search in sources :

Example 21 with NetSocket

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

the class WebsocketTest method testContinuationWriteFromConnectHandler.

private void testContinuationWriteFromConnectHandler(WebsocketVersion version) throws Exception {
    String path = "/some/path";
    String firstFrame = "AAA";
    String continuationFrame = "BBB";
    server = vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT)).requestHandler(req -> {
        NetSocket sock = getUpgradedNetSocket(req, path);
        Buffer buff = Buffer.buffer();
        buff.appendByte((byte) 0x01);
        buff.appendByte((byte) firstFrame.length());
        buff.appendString(firstFrame);
        sock.write(buff);
        buff = Buffer.buffer();
        buff.appendByte((byte) (0x00 | 0x80));
        buff.appendByte((byte) continuationFrame.length());
        buff.appendString(continuationFrame);
        sock.write(buff);
    });
    server.listen(ar -> {
        assertTrue(ar.succeeded());
        client.websocket(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path, null, version, ws -> {
            AtomicBoolean receivedFirstFrame = new AtomicBoolean();
            ws.frameHandler(received -> {
                Buffer receivedBuffer = Buffer.buffer(received.textData());
                if (!received.isFinal()) {
                    assertEquals(firstFrame, receivedBuffer.toString());
                    receivedFirstFrame.set(true);
                } else if (receivedFirstFrame.get() && received.isFinal()) {
                    assertEquals(continuationFrame, receivedBuffer.toString());
                    ws.close();
                    testComplete();
                }
            });
        });
    });
    await();
}
Also used : Arrays(java.util.Arrays) MessageDigest(java.security.MessageDigest) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cert(io.vertx.test.core.tls.Cert) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestUtils(io.vertx.test.core.TestUtils) Map(java.util.Map) ReadStream(io.vertx.core.streams.ReadStream) AsyncResult(io.vertx.core.AsyncResult) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) java.util.concurrent(java.util.concurrent) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Test(org.junit.Test) Future(io.vertx.core.Future) io.vertx.core.http(io.vertx.core.http) Consumer(java.util.function.Consumer) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) AbstractVerticle(io.vertx.core.AbstractVerticle) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Handler(io.vertx.core.Handler) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Collections(java.util.Collections) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) NetSocket(io.vertx.core.net.NetSocket) Buffer(io.vertx.core.buffer.Buffer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 22 with NetSocket

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

the class WebsocketTest method getUpgradedNetSocket.

private NetSocket getUpgradedNetSocket(HttpServerRequest req, String path) {
    assertEquals(path, req.path());
    assertEquals("upgrade", req.headers().get("Connection"));
    NetSocket sock = req.netSocket();
    String secHeader = req.headers().get("Sec-WebSocket-Key");
    String tmp = secHeader + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    String encoded = sha1(tmp);
    sock.write("HTTP/1.1 101 Web Socket Protocol Handshake\r\n" + "Upgrade: WebSocket\r\n" + "Connection: upgrade\r\n" + "Sec-WebSocket-Accept: " + encoded + "\r\n" + "\r\n");
    return sock;
}
Also used : NetSocket(io.vertx.core.net.NetSocket)

Example 23 with NetSocket

use of io.vertx.core.net.NetSocket 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
   * @param finishedHandler
   *          will be called when the start has started
   */
@Override
public void start(Vertx vertx, Handler<Void> finishedHandler) {
    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();
                    }
                });
            }
        });
    });
    server.listen(result -> {
        log.debug("socks4a server started");
        finishedHandler.handle(null);
    });
}
Also used : NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) NetClient(io.vertx.core.net.NetClient) NetServerOptions(io.vertx.core.net.NetServerOptions)

Example 24 with NetSocket

use of io.vertx.core.net.NetSocket 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
   * @param finishedHandler
   *          will be called when the start has started
   */
@Override
public void start(Vertx vertx, Handler<Void> finishedHandler) {
    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 stringLen = buffer2.getUnsignedByte(4);
                log.debug("string len " + stringLen);
                if (buffer2.length() != 7 + stringLen) {
                    throw new IllegalStateException("format error in client request, got " + toHex(buffer2));
                }
                String host = buffer2.getString(5, 5 + stringLen);
                int port = buffer2.getUnsignedShort(5 + stringLen);
                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);
            }
        });
    });
    server.listen(result -> {
        log.debug("socks5 server started");
        finishedHandler.handle(null);
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) NetServerOptions(io.vertx.core.net.NetServerOptions) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) Vertx(io.vertx.core.Vertx) Pump(io.vertx.core.streams.Pump) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) NetClient(io.vertx.core.net.NetClient) LoggerFactory(io.vertx.core.logging.LoggerFactory) NetClientOptions(io.vertx.core.net.NetClientOptions) NetSocket(io.vertx.core.net.NetSocket) NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) NetClient(io.vertx.core.net.NetClient) NetServerOptions(io.vertx.core.net.NetServerOptions)

Example 25 with NetSocket

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

the class Http2ServerTest method testNetSocketConnect.

@Test
public void testNetSocketConnect() throws Exception {
    waitFor(2);
    server.requestHandler(req -> {
        NetSocket socket = req.netSocket();
        AtomicInteger status = new AtomicInteger();
        socket.handler(buff -> {
            switch(status.getAndIncrement()) {
                case 0:
                    assertEquals(Buffer.buffer("some-data"), buff);
                    socket.write(buff);
                    break;
                case 1:
                    assertEquals(Buffer.buffer("last-data"), buff);
                    break;
                default:
                    fail();
                    break;
            }
        });
        socket.endHandler(v -> {
            assertEquals(2, status.getAndIncrement());
            socket.write(Buffer.buffer("last-data"));
        });
        socket.closeHandler(v -> {
            assertEquals(3, status.getAndIncrement());
            complete();
        });
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.decoder.frameListener(new Http2EventAdapter() {

            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals("200", headers.status().toString());
                    assertFalse(endStream);
                });
                request.encoder.writeData(request.context, id, Buffer.buffer("some-data").getByteBuf(), 0, false, request.context.newPromise());
                request.context.flush();
            }

            StringBuilder received = new StringBuilder();

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
                String s = data.toString(StandardCharsets.UTF_8);
                received.append(s);
                if (received.toString().equals("some-data")) {
                    received.setLength(0);
                    vertx.runOnContext(v -> {
                        assertFalse(endOfStream);
                    });
                    request.encoder.writeData(request.context, id, Buffer.buffer("last-data").getByteBuf(), 0, true, request.context.newPromise());
                } else if (endOfStream) {
                    vertx.runOnContext(v -> {
                        assertEquals("last-data", received.toString());
                        complete();
                    });
                }
                return data.readableBytes() + padding;
            }
        });
        request.encoder.writeHeaders(request.context, id, GET("/"), 0, false, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}
Also used : NetSocket(io.vertx.core.net.NetSocket) ChannelFuture(io.netty.channel.ChannelFuture) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) HttpServer(io.vertx.core.http.HttpServer) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Context(io.vertx.core.Context) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ReadStream(io.vertx.core.streams.ReadStream) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) StreamResetException(io.vertx.core.http.StreamResetException) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) IOException(java.io.IOException) SSLHelper(io.vertx.core.net.impl.SSLHelper) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2Connection(io.netty.handler.codec.http2.Http2Connection) HttpMethod(io.vertx.core.http.HttpMethod) HttpUtils(io.vertx.core.http.impl.HttpUtils) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) Test(org.junit.Test)

Aggregations

NetSocket (io.vertx.core.net.NetSocket)33 Test (org.junit.Test)23 NetClient (io.vertx.core.net.NetClient)16 Buffer (io.vertx.core.buffer.Buffer)14 Handler (io.vertx.core.Handler)13 Async (io.vertx.ext.unit.Async)11 Vertx (io.vertx.core.Vertx)10 JsonObject (io.vertx.core.json.JsonObject)10 AsyncResult (io.vertx.core.AsyncResult)9 Context (io.vertx.core.Context)9 Future (io.vertx.core.Future)9 FrameParser (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameParser)9 ByteBuf (io.netty.buffer.ByteBuf)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 Unpooled (io.netty.buffer.Unpooled)6 Channel (io.netty.channel.Channel)6 SslHandler (io.netty.handler.ssl.SslHandler)6 MultiMap (io.vertx.core.MultiMap)6 VertxInternal (io.vertx.core.impl.VertxInternal)6 NetClientOptions (io.vertx.core.net.NetClientOptions)6