Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

extensions: Switch to NIO sockets & cleanup #39

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 25 additions & 29 deletions G-Earth/src/main/java/gearth/extensions/Extension.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import gearth.ui.extensions.Extensions;

import java.io.*;
import java.net.Socket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Expand All @@ -23,16 +25,17 @@ public interface FlagsCheckListener {
void act(String[] args);
}

protected boolean canLeave; // can you disconnect the ext
protected boolean canDelete; // can you delete the ext (will be false for some built-in extensions)
private boolean canLeave; // can you disconnect the ext
private boolean canDelete; // can you delete the ext (will be false for some built-in extensions)

private String[] args;
private boolean isCorrupted = false;
private static final String[] PORT_FLAG = {"--port", "-p"};
private static final String[] FILE_FLAG = {"--filename", "-f"};
private static final String[] COOKIE_FLAG = {"--auth-token", "-c"}; // don't add a cookie or filename when debugging

private OutputStream out = null;
private SocketChannel gEarthExtensionServer = null;

private final Map<Integer, List<MessageListener>> incomingMessageListeners = new HashMap<>();
private final Map<Integer, List<MessageListener>> outgoingMessageListeners = new HashMap<>();
private FlagsCheckListener flagRequestCallback = null;
Expand Down Expand Up @@ -87,37 +90,29 @@ public void run() {
String file = getArgument(args, FILE_FLAG);
String cookie = getArgument(args, COOKIE_FLAG);

Socket gEarthExtensionServer = null;
try {
gEarthExtensionServer = new Socket("127.0.0.1", port);
gEarthExtensionServer.setTcpNoDelay(true);
InputStream in = gEarthExtensionServer.getInputStream();
DataInputStream dIn = new DataInputStream(in);
out = gEarthExtensionServer.getOutputStream();
gEarthExtensionServer = SocketChannel.open();
gEarthExtensionServer.connect(new InetSocketAddress("127.0.0.1", port));
gEarthExtensionServer.socket().setTcpNoDelay(true);

while (!gEarthExtensionServer.isClosed()) {
ByteBuffer bbLength = ByteBuffer.allocateDirect(4);

while (gEarthExtensionServer.isOpen()) {
int length;
try {
length = dIn.readInt();
}
catch(EOFException exception) {
//g-earth closed the extension

if (gEarthExtensionServer.read(bbLength) == -1)
break;
}

byte[] headerandbody = new byte[length + 4];
length = bbLength.getInt(0);
bbLength.flip();

int amountRead = 0;
ByteBuffer headerAndBody = ByteBuffer.allocateDirect(4 + length);
headerAndBody.putInt(0); // this will be the length
gEarthExtensionServer.read(headerAndBody);

while (amountRead < length) {
amountRead += dIn.read(headerandbody, 4 + amountRead, Math.min(dIn.available(), length - amountRead));
}

HPacket packet = new HPacket(headerandbody);
HPacket packet = new HPacket(headerAndBody);
packet.fixLength();


if (packet.headerId() == Extensions.OUTGOING_MESSAGES_IDS.INFOREQUEST) {
ExtensionInfo info = getInfoAnnotations();

Expand All @@ -132,7 +127,9 @@ public void run() {
.appendString(cookie == null ? "" : cookie)
.appendBoolean(canLeave)
.appendBoolean(canDelete);
writeToStream(response.toBytes());

ByteBuffer extInfo = ByteBuffer.wrap(response.toBytes());
gEarthExtensionServer.write(extInfo);
}
else if (packet.headerId() == Extensions.OUTGOING_MESSAGES_IDS.CONNECTIONSTART) {
String host = packet.readString();
Expand Down Expand Up @@ -204,7 +201,6 @@ else if (packet.headerId() == Extensions.OUTGOING_MESSAGES_IDS.PACKETINTERCEPT)
response.appendLongString(habboMessage.stringify());

writeToStream(response.toBytes());

}
}

Expand All @@ -213,7 +209,7 @@ else if (packet.headerId() == Extensions.OUTGOING_MESSAGES_IDS.PACKETINTERCEPT)
// e.printStackTrace();
}
finally {
if (gEarthExtensionServer != null && !gEarthExtensionServer.isClosed()) {
if (gEarthExtensionServer != null && gEarthExtensionServer.isOpen()) {
try {
gEarthExtensionServer.close();
} catch (IOException e) {
Expand All @@ -225,7 +221,7 @@ else if (packet.headerId() == Extensions.OUTGOING_MESSAGES_IDS.PACKETINTERCEPT)

private void writeToStream(byte[] bytes) throws IOException {
synchronized (this) {
out.write(bytes);
gEarthExtensionServer.write(ByteBuffer.wrap(bytes));
}
}

Expand Down
7 changes: 7 additions & 0 deletions G-Earth/src/main/java/gearth/protocol/HPacket.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ public class HPacket implements StringifyAble {
public HPacket(byte[] packet) {
packetInBytes = packet.clone();
}

public HPacket(ByteBuffer packet) {
packetInBytes = new byte[packet.capacity()];
for (int i = 0; i < packetInBytes.length; i++)
packetInBytes[i] = packet.get(i);
}

public HPacket(HPacket packet) {
packetInBytes = packet.packetInBytes.clone();
isEdited = packet.isEdited;
Expand Down
136 changes: 66 additions & 70 deletions G-Earth/src/main/java/gearth/ui/extensions/Extensions.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,21 @@
* Why? Because Habbo relies on the TCP protocol, which ENSURES that packets get received in the right order, so we will not be fucking that up.
* That means that all packets following the packet you're manipulating in your extension will be blocked from being sent untill you're done.
* TIP: If you're trying to replace a packet in your extension but you know it will take time, just block the packet, end the method, and let something asynchronous send
* the editted packet when you're done.
* the edited packet when you're done.
*
*
* You may ignore everything beneath this line if you're extending the abstract Extension class we provide in Java.
* -----------------------------------------------------------------------------------------------------------------
*
* (0. We recommend to use a cross-platform language for your extension)
*
* 1. An extension will run as a seperate process on your device and has to be called with the flag "-p <PORT>",
* 1. An extension will run as a separate process on your device and has to be called with the flag "-p <PORT>",
* where <PORT> is a random port where the G-Earth local extension server will run on. Your extension has to connect with this server.
*
* 2. G-Earth will open your program only ONCE, that is on the boot of G-Earth or when you install the exension.
* 2. G-Earth will open your program only ONCE, that is on the boot of G-Earth or when you install the extension.
* Same story goes for closing the connection between the program and G-Earth, only once (on uninstall or close of G-Earth).
*
* You may also run your extension completely seperate from G-Earth for debugging purpose for example, then it won't be installed in G-Earth
* You may also run your extension completely separate from G-Earth for debugging purpose for example, then it won't be installed in G-Earth
* (but you have to configure the port yourself, which will be displayed in the extension page)
*
* 3. Once a connection is made, your extension will have to deal with the following incoming & outgoing messages as described (follows the same protocol structure as Habbo communication does):
Expand Down Expand Up @@ -209,7 +209,6 @@ public void act(HPacket packet) {
}
}
}

}
};
extension.addOnReceiveMessageListener(respondCallback);
Expand Down Expand Up @@ -250,83 +249,80 @@ public void act(HPacket packet) {


HashMap<GEarthExtension, GEarthExtension.ReceiveMessageListener> messageListeners = new HashMap<>();
try {
extensionsRegistrer = new GEarthExtensionsRegistrer(new GEarthExtensionsRegistrer.ExtensionRegisterObserver() {
@Override
public void onConnect(GEarthExtension extension) {
synchronized (gEarthExtensions) {
gEarthExtensions.add(extension);
}
extensionsRegistrer = new GEarthExtensionsRegistrer(new GEarthExtensionsRegistrer.ExtensionRegisterObserver() {
@Override
public void onConnect(GEarthExtension extension) {
synchronized (gEarthExtensions) {
gEarthExtensions.add(extension);
}

GEarthExtension.ReceiveMessageListener receiveMessageListener = message -> {
if (message.headerId() == INCOMING_MESSAGES_IDS.REQUESTFLAGS) { // no body
HPacket packet = new HPacket(OUTGOING_MESSAGES_IDS.FLAGSCHECK);
packet.appendInt(Main.args.length);
for (String arg : Main.args) {
packet.appendString(arg);
}
extension.sendMessage(packet);
GEarthExtension.ReceiveMessageListener receiveMessageListener = message -> {
if (message.headerId() == INCOMING_MESSAGES_IDS.REQUESTFLAGS) { // no body
HPacket packet = new HPacket(OUTGOING_MESSAGES_IDS.FLAGSCHECK);
packet.appendInt(Main.args.length);
for (String arg : Main.args) {
packet.appendString(arg);
}
else if (message.headerId() == INCOMING_MESSAGES_IDS.SENDMESSAGE) {
Byte side = message.readByte();
int byteLength = message.readInteger();
byte[] packetAsByteArray = message.readBytes(byteLength);

HPacket packet = new HPacket(packetAsByteArray);
if (!packet.isCorrupted()) {
if (side == 0) { // toclient
getHConnection().sendToClientAsync(packet);
}
else if (side == 1) { // toserver
getHConnection().sendToServerAsync(packet);
}
extension.sendMessage(packet);
}
else if (message.headerId() == INCOMING_MESSAGES_IDS.SENDMESSAGE) {
Byte side = message.readByte();
int byteLength = message.readInteger();
byte[] packetAsByteArray = message.readBytes(byteLength);

HPacket packet = new HPacket(packetAsByteArray);
if (!packet.isCorrupted()) {
if (side == 0) { // toclient
getHConnection().sendToClientAsync(packet);
}
else if (side == 1) { // toserver
getHConnection().sendToServerAsync(packet);
}
}
};
synchronized (messageListeners) {
messageListeners.put(extension, receiveMessageListener);
}
extension.addOnReceiveMessageListener(receiveMessageListener);
};
synchronized (messageListeners) {
messageListeners.put(extension, receiveMessageListener);
}
extension.addOnReceiveMessageListener(receiveMessageListener);

extension.sendMessage(new HPacket(OUTGOING_MESSAGES_IDS.INIT));
if (getHConnection().getState() == HConnection.State.CONNECTED) {
extension.sendMessage(
new HPacket(OUTGOING_MESSAGES_IDS.CONNECTIONSTART)
.appendString(getHConnection().getDomain())
.appendInt(getHConnection().getPort())
.appendString(getHConnection().getHotelVersion())
.appendString(HarbleAPIFetcher.HARBLEAPI == null ? "null" : HarbleAPIFetcher.HARBLEAPI.getPath())
);
}

extension.sendMessage(new HPacket(OUTGOING_MESSAGES_IDS.INIT));
if (getHConnection().getState() == HConnection.State.CONNECTED) {
extension.sendMessage(
new HPacket(OUTGOING_MESSAGES_IDS.CONNECTIONSTART)
.appendString(getHConnection().getDomain())
.appendInt(getHConnection().getPort())
.appendString(getHConnection().getHotelVersion())
.appendString(HarbleAPIFetcher.HARBLEAPI == null ? "null" : HarbleAPIFetcher.HARBLEAPI.getPath())
);
extension.onRemoveClick(observable -> {
try {
extension.getConnection().close();
extension.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
});
extension.onClick(observable -> extension.sendMessage(new HPacket(OUTGOING_MESSAGES_IDS.ONDOUBLECLICK)));

extension.onRemoveClick(observable -> {
try {
extension.getConnection().close();
} catch (IOException e) {
e.printStackTrace();
}
});
extension.onClick(observable -> extension.sendMessage(new HPacket(OUTGOING_MESSAGES_IDS.ONDOUBLECLICK)));
Platform.runLater(() -> producer.extensionConnected(extension));
}

Platform.runLater(() -> producer.extensionConnected(extension));
@Override
public void onDisconnect(GEarthExtension extension) {
synchronized (gEarthExtensions) {
gEarthExtensions.remove(extension);
}

@Override
public void onDisconnect(GEarthExtension extension) {
synchronized (gEarthExtensions) {
gEarthExtensions.remove(extension);
}

synchronized (messageListeners) {
extension.removeOnReceiveMessageListener(messageListeners.get(extension));
messageListeners.remove(extension);
}
Platform.runLater(extension::delete);
synchronized (messageListeners) {
extension.removeOnReceiveMessageListener(messageListeners.get(extension));
messageListeners.remove(extension);
}
});
} catch (IOException e) {
e.printStackTrace();
}
Platform.runLater(extension::delete);
}
});

producer.setPort(extensionsRegistrer.getPort());
ext_port.setText(extensionsRegistrer.getPort()+"");
Expand Down
Loading