Search in sources :

Example 16 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 17 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 18 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)

Example 19 with NetSocket

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

the class NetSocketImpl method sendFile.

@Override
public NetSocket sendFile(String filename, long offset, long length, final Handler<AsyncResult<Void>> resultHandler) {
    File f = vertx.resolveFile(filename);
    if (f.isDirectory()) {
        throw new IllegalArgumentException("filename must point to a file and not to a directory");
    }
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(f, "r");
        ChannelFuture future = super.sendFile(raf, Math.min(offset, f.length()), Math.min(length, f.length() - offset));
        if (resultHandler != null) {
            future.addListener(fut -> {
                final AsyncResult<Void> res;
                if (future.isSuccess()) {
                    res = Future.succeededFuture();
                } else {
                    res = Future.failedFuture(future.cause());
                }
                vertx.runOnContext(v -> resultHandler.handle(res));
            });
        }
    } catch (IOException e) {
        try {
            if (raf != null) {
                raf.close();
            }
        } catch (IOException ignore) {
        }
        if (resultHandler != null) {
            vertx.runOnContext(v -> resultHandler.handle(Future.failedFuture(e)));
        } else {
            log.error("Failed to send file", e);
        }
    }
    return this;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) RandomAccessFile(java.io.RandomAccessFile) ContextImpl(io.vertx.core.impl.ContextImpl) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) NetworkMetrics(io.vertx.core.spi.metrics.NetworkMetrics) LoggerFactory(io.vertx.core.logging.LoggerFactory) Unpooled(io.netty.buffer.Unpooled) ByteBuf(io.netty.buffer.ByteBuf) Charset(java.nio.charset.Charset) ChannelFutureListener(io.netty.channel.ChannelFutureListener) CharsetUtil(io.netty.util.CharsetUtil) AsyncResult(io.vertx.core.AsyncResult) Logger(io.vertx.core.logging.Logger) SocketAddress(io.vertx.core.net.SocketAddress) VertxInternal(io.vertx.core.impl.VertxInternal) Message(io.vertx.core.eventbus.Message) IOException(java.io.IOException) UUID(java.util.UUID) X509Certificate(javax.security.cert.X509Certificate) Future(io.vertx.core.Future) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Handler(io.vertx.core.Handler) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) NetSocket(io.vertx.core.net.NetSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) RandomAccessFile(java.io.RandomAccessFile) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 20 with NetSocket

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

the class VertxHttp2NetSocket method sendFile.

@Override
public NetSocket sendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
    synchronized (conn) {
        Context resultCtx = resultHandler != null ? vertx.getOrCreateContext() : null;
        File file = vertx.resolveFile(filename);
        if (!file.exists()) {
            if (resultHandler != null) {
                resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(new FileNotFoundException())));
            } else {
            // log.error("File not found: " + filename);
            }
            return this;
        }
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");
        } catch (IOException e) {
            if (resultHandler != null) {
                resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(e)));
            } else {
            //log.error("Failed to send file", e);
            }
            return this;
        }
        long contentLength = Math.min(length, file.length() - offset);
        FileStreamChannel fileChannel = new FileStreamChannel(ar -> {
            if (resultHandler != null) {
                resultCtx.runOnContext(v -> {
                    resultHandler.handle(Future.succeededFuture());
                });
            }
        }, this, offset, contentLength);
        drainHandler(fileChannel.drainHandler);
        handlerContext.channel().eventLoop().register(fileChannel);
        fileChannel.pipeline().fireUserEventTriggered(raf);
    }
    return this;
}
Also used : Context(io.vertx.core.Context) RandomAccessFile(java.io.RandomAccessFile) MultiMap(io.vertx.core.MultiMap) IOException(java.io.IOException) X509Certificate(javax.security.cert.X509Certificate) Context(io.vertx.core.Context) Future(io.vertx.core.Future) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Unpooled(io.netty.buffer.Unpooled) Nullable(io.vertx.codegen.annotations.Nullable) Buffer(io.vertx.core.buffer.Buffer) Charset(java.nio.charset.Charset) Http2Stream(io.netty.handler.codec.http2.Http2Stream) CharsetUtil(io.netty.util.CharsetUtil) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) StreamResetException(io.vertx.core.http.StreamResetException) NetSocket(io.vertx.core.net.NetSocket) SocketAddress(io.vertx.core.net.SocketAddress) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) RandomAccessFile(java.io.RandomAccessFile) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Aggregations

NetSocket (io.vertx.core.net.NetSocket)21 Buffer (io.vertx.core.buffer.Buffer)14 Test (org.junit.Test)12 Handler (io.vertx.core.Handler)11 AsyncResult (io.vertx.core.AsyncResult)8 Future (io.vertx.core.Future)8 Vertx (io.vertx.core.Vertx)8 ByteBuf (io.netty.buffer.ByteBuf)7 Context (io.vertx.core.Context)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 NetClient (io.vertx.core.net.NetClient)6 NetClientOptions (io.vertx.core.net.NetClientOptions)6 ReadStream (io.vertx.core.streams.ReadStream)6 Base64 (java.util.Base64)6 Map (java.util.Map)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6