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);
});
}
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);
});
}
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();
}
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;
}
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;
}
Aggregations