Skip to content

Commit

Permalink
feat: Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
AshCorr committed Jun 14, 2022
0 parents commit 9dff517
Show file tree
Hide file tree
Showing 6 changed files with 265 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"deno.enable": true,
"deno.lint": true,
"deno.unstable": false
}
7 changes: 7 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2022 AshCorr

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# byond_client

> **byond_client** is a Deno implementation of the byond topic protocol used for communicating between byond servers.
### Import

Replace `LATEST_VERSION` with
[current latest version](https://deno.land/x/byond_client)

```ts
import {
ByondClient
} from "https://deno.land/x/byond_client@LATEST_VERSION/mod.ts";
```

### Usage

```ts
const client = new ByondClient();

await client.connect({
hostname: "game.yogstation.net",
port: "4133"
});

// Basic Example: ?ping
const playersOnline = client.send("ping");
console.log(`Players Online: ${playersOnline}`);
/// Players Online: 47

// Using parameters and parsing Byond response: ?status&comms_key=SuperSecretPassword
const info = new URLSearchParams(await client.send("status", {
comms_key: "SuperSecretPassword"
}));
console.log(`Current Gamemode: ${info.gamemode}`)
/// Current Gamemode: Shadowlings

client.close();
```

### Todo
1. Locking or Queuing topic requests for thread safety
2. Connecting pooling
3. Documentation
3 changes: 3 additions & 0 deletions deps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { varnum } from "https://deno.land/std@0.143.0/encoding/binary.ts";

export { assertEquals } from "https://deno.land/std@0.143.0/testing/asserts.ts";
126 changes: 126 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { varnum } from "./deps.ts";

const BYOND_RESPONSE_HEADER_SIZE = 5;

const BYOND_FLOAT_TYPE = 0x2a;
const BYOND_TEXT_TYPE = 0x06;

export class ByondClient {
#connection?: Deno.TcpConn;

constructor() {}

async connect(connectionOptions: Deno.ConnectTlsOptions) {
this.#connection = await Deno.connect(connectionOptions);
}

#urlEncode(topic: string, parameters?: { [key: string]: string }) {
if (topic[0] !== "?") topic = "?" + topic;

if (parameters === undefined) return topic;

Object.keys(parameters).forEach((parameter) => {
const value = parameters[parameter];

if (value === undefined) {
topic = topic += `&${parameter}`;
} else {
topic = topic += `&${parameter}=${encodeURIComponent(
parameters[parameter]
)}`;
}
});

return topic;
}

#createByondPacket(topic: string) {
const size = 2 + 2 + 5 + topic.length + 1;
const dataBuffer = new Uint8Array(2 + 2 + 5 + topic.length + 1);
dataBuffer[0] = 0x00;
dataBuffer[1] = 0x83;
dataBuffer[2] = 0x00;
dataBuffer[3] = 5 + topic.length + 1;
dataBuffer[4] = 0x00;
dataBuffer[5] = 0x00;
dataBuffer[6] = 0x00;
dataBuffer[7] = 0x00;
dataBuffer[8] = 0x00;

const utfEncoded = new TextEncoder().encode(topic);
dataBuffer.set(utfEncoded, 9);

dataBuffer[size] = 0x00;

return dataBuffer;
}

#decodeByondRespose(
headerBuffer: Uint8Array,
dataBuffer: Uint8Array
): number | string {
const dataType = headerBuffer[4];

switch (dataType) {
case BYOND_FLOAT_TYPE: {
const number = varnum(dataBuffer, {
dataType: "float32",
endian: "little",
});

if (number === null) {
throw new Error(
`Unexpected data from server, was expecting 4 bytes but received ${dataBuffer}`
);
}

return number;
}
case BYOND_TEXT_TYPE:
return new TextDecoder().decode(dataBuffer);
default:
throw new Error(
`Unexpected type header returned by server: ${dataType}`
);
}
}

#decodeByondResponseSize(headerBuffer: Uint8Array) {
const responseSize = varnum(headerBuffer.slice(2, 4), {
dataType: "uint16",
});

if (responseSize === null) {
throw new Error(`Unexpected header returned by server ${headerBuffer}`);
}

return responseSize;
}

async send(
topic: string,
parameters?: { [key: string]: string }
): Promise<string | number> {
if (this.#connection === undefined)
throw new Error("Tried using send() without open()ing first.");

const byondPacket = this.#createByondPacket(
this.#urlEncode(topic, parameters)
);
await this.#connection.write(byondPacket);

const headerBuffer = new Uint8Array(BYOND_RESPONSE_HEADER_SIZE);
await this.#connection.read(headerBuffer);

const responseSize = this.#decodeByondResponseSize(headerBuffer);

const dataBuffer = new Uint8Array(responseSize);
await this.#connection.read(dataBuffer);

return this.#decodeByondRespose(headerBuffer, dataBuffer);
}

close() {
this.#connection?.close();
}
}
80 changes: 80 additions & 0 deletions mod_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { assertEquals } from "./deps.ts";
import { ByondClient } from "./mod.ts";

const TEST_HOSTNAME = "localhost";
const TEST_PORT = 5613;

let listener: Deno.Listener;
let connection: Deno.Conn;

async function mockByondServer(
expectedPayload: Uint8Array,
response: Uint8Array
) {
listener = Deno.listen({
hostname: TEST_HOSTNAME,
port: TEST_PORT,
});
connection = await listener.accept();

const payload = new Uint8Array(expectedPayload.length);
await connection.read(payload);
assertEquals(payload, expectedPayload);

await connection.write(response);

connection.close();
listener.close();
}

Deno.test("?ping", async () => {
mockByondServer(
// ?ping
Uint8Array.from([0, 131, 0, 11, 0, 0, 0, 0, 0, 63, 112, 105, 110, 103, 0]),
Uint8Array.from([0, 131, 0, 5, 42, 0, 0, 60, 66])
);

const connector = new ByondClient();
await connector.connect({ hostname: TEST_HOSTNAME, port: TEST_PORT });
const response = await connector.send("?ping");
connector.close();

assertEquals(47, response);
});

Deno.test("ping", async () => {
// ?ping
mockByondServer(
Uint8Array.from([0, 131, 0, 11, 0, 0, 0, 0, 0, 63, 112, 105, 110, 103, 0]),
Uint8Array.from([0, 131, 0, 5, 42, 0, 0, 60, 66])
);

const connector = new ByondClient();
await connector.connect({ hostname: TEST_HOSTNAME, port: TEST_PORT });
const response = await connector.send("ping");
connector.close();

assertEquals(47, response);
});

Deno.test("?status&comms_key=SuperSecretPassword", async () => {
mockByondServer(
// ?ping&comms_key=Super%26Secret%3FPassword
Uint8Array.from([
0, 131, 0, 47, 0, 0, 0, 0, 0, 63, 112, 105, 110, 103, 38, 99, 111, 109,
109, 115, 95, 107, 101, 121, 61, 83, 117, 112, 101, 114, 37, 50, 54, 83,
101, 99, 114, 101, 116, 37, 51, 70, 80, 97, 115, 115, 119, 111, 114, 100,
0,
]),
Uint8Array.from([0, 131, 0, 5, 42, 0, 0, 60, 66])
);

const connector = new ByondClient();
await connector.connect({ hostname: TEST_HOSTNAME, port: TEST_PORT });
const response = await connector.send("?ping", {
comms_key: "Super&Secret?Password",
});
connector.close();

assertEquals(47, response);
});

0 comments on commit 9dff517

Please sign in to comment.