added RCON connection
This commit is contained in:
@@ -13,7 +13,7 @@ jobs:
|
||||
steps:
|
||||
- name: Hello world action step
|
||||
id: hello
|
||||
uses: Plagiatus/RCON-Action@v0.0.1
|
||||
uses: Plagiatus/RCON-Action@v0.0.2
|
||||
with:
|
||||
who-to-greet: 'Mona the Octocat'
|
||||
# Use the output from the `hello` step
|
||||
|
||||
+22
-8
@@ -1,13 +1,27 @@
|
||||
name: Hello World
|
||||
description: Greet someone and record the time
|
||||
name: Send RCON commands
|
||||
description: Send command(s) via RCON connection to a RCON server
|
||||
inputs:
|
||||
who-to-greet:
|
||||
server:
|
||||
required: true
|
||||
description: Who to greet
|
||||
default: World
|
||||
outputs:
|
||||
time:
|
||||
description: The time we greeted you
|
||||
description: The server IP address
|
||||
port:
|
||||
required: true
|
||||
description: The server's RCON port
|
||||
default: 25575
|
||||
password:
|
||||
required: true
|
||||
description: The RCON password to authenticate
|
||||
commands:
|
||||
required: true
|
||||
description: Additional commands to send
|
||||
send-push-info:
|
||||
required: false
|
||||
description: Sends information about the push to the server as a tellraw
|
||||
default: true
|
||||
push-info-recipient:
|
||||
required: false
|
||||
description: Changes the selector of who should be getting the server info.
|
||||
default: "@a"
|
||||
runs:
|
||||
using: node12
|
||||
main: index.js
|
||||
@@ -1,16 +1,45 @@
|
||||
const core = require("@actions/core")
|
||||
const github = require("@actions/github")
|
||||
const core = require("@actions/core");
|
||||
const github = require( "@actions/github");
|
||||
const rcon = require( "./node-rcon/RCON.js" );
|
||||
|
||||
try {
|
||||
|
||||
const nameToGreet = core.getInput("who-to-greet");
|
||||
console.log("Hello", nameToGreet);
|
||||
const time = (new Date()).toTimeString();
|
||||
core.setOutput("time", time);
|
||||
run()
|
||||
async function run() {
|
||||
console.log("❤ thank you for using RCON-Action (https://github.com/Plagiatus/RCON-Action).");
|
||||
console.log("⭐ if you find this helpful, why not drop a star on the repo? Much appreciated!");
|
||||
console.log("❓ if you have any questions or issues, please let us know by writing an issue");
|
||||
|
||||
const payload = JSON.stringify(github.context.payload, undefined, 2);
|
||||
console.log("The event payload", payload);
|
||||
|
||||
} catch (error) {
|
||||
core.setFailed(error.message)
|
||||
try {
|
||||
const inputs = {
|
||||
server: core.getInput("server"),
|
||||
port: core.getInput("port"),
|
||||
password: core.getInput("password"),
|
||||
commands: core.getInput("commands"),
|
||||
sendPushInfo: core.getInput("send-push-info"),
|
||||
pushInfoRecipient: core.getInput("push-info-recipient"),
|
||||
}
|
||||
const payload = JSON.stringify(github.context.payload, undefined, 2);
|
||||
|
||||
console.log(inputs);
|
||||
console.log(payload);
|
||||
|
||||
const srvr = new rcon();
|
||||
console.log("Connecting to server via RCON...");
|
||||
await srvr.connect(inputs.server, inputs.port, inputs.password)
|
||||
console.log("🟢 connected and authenticated");
|
||||
|
||||
if (inputs.sendPushInfo) {
|
||||
await srvr.send(`tellraw ${inputs.pushInfoRecipient} [{"text":"[GitHub] New push from ","color":"#6D0599"},{"text":"${github.context.payload.sender.login}","color":"#330080"},{"text":" detected and added to the server via ftp."}]`)
|
||||
}
|
||||
if (inputs.commands.length > 0) {
|
||||
for (let command of inputs.commands) {
|
||||
await srvr.send(command);
|
||||
}
|
||||
console.log(`📬 Sent all ${inputs.commands.length} to the server.`)
|
||||
}
|
||||
|
||||
srvr.end();
|
||||
} catch (error) {
|
||||
core.setFailed(error.message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Functions for managing packets used by the RCON protocol
|
||||
*/
|
||||
class Packet {
|
||||
/**
|
||||
* Generate a unique max 32 bit ID integer
|
||||
* @return {Number} Generated ID
|
||||
*/
|
||||
static id () {
|
||||
return Number.parseInt(Math.random().toString(2).substring(2, 32), 2);
|
||||
}
|
||||
/**
|
||||
* Create a new packet buffer with given ID, type and payload
|
||||
* @param {Number} id A unique max 32 bit client generated request ID
|
||||
* @param {[type]} type Type of the packet
|
||||
* @param {String} payload Data to be sent encoded in 'ASCII'
|
||||
* @return {Buffer} Created packet
|
||||
*/
|
||||
static write (id, type, payload) {
|
||||
// Length of payload in bytes when encoded in ASCII
|
||||
const length = Buffer.byteLength(payload, 'ascii');
|
||||
// 14 bytes for the length, ID, type and 2-byte padding
|
||||
const buffer = Buffer.allocUnsafe(14 + length);
|
||||
// Offsets are hardcoded for speed
|
||||
buffer.writeInt32LE(10 + length, 0); // Length
|
||||
buffer.writeInt32LE(id, 4); // Request ID
|
||||
buffer.writeInt32LE(type, 8); // Type
|
||||
buffer.write(payload, 12, 'ascii'); // Payload
|
||||
buffer.writeInt16LE(0, 12 + length); // Two null bytes of padding
|
||||
return buffer;
|
||||
}
|
||||
/**
|
||||
* Parse the given packet into a JSON object
|
||||
* @param {Buffer} packet
|
||||
* @return {Object} Parsed packet
|
||||
*/
|
||||
static read (packet) {
|
||||
// Length of the rest of the packet
|
||||
const length = packet.readInt32LE(0);
|
||||
// Check if we have a valid packet with 2 null bytes of padding in the end
|
||||
if (packet.length === 4 + length && !packet.readInt16LE(packet.length - 2)) {
|
||||
// Offsets are hardcoded for speed
|
||||
return {
|
||||
length: length,
|
||||
id: packet.readInt32LE(4),
|
||||
type: packet.readInt32LE(8),
|
||||
payload: packet.toString('ascii', 12, packet.length - 2)
|
||||
};
|
||||
} else {
|
||||
throw new Error(`Invalid packet! [${packet}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* RCON packet type Integers understood by the Mineccraft Server
|
||||
* https://wiki.vg/RCON#Packets
|
||||
* @type {Object}
|
||||
*/
|
||||
Packet.type = {
|
||||
AUTH: 3,
|
||||
AUTH_RES: 2,
|
||||
COMMAND: 2,
|
||||
COMMAND_RES: 0,
|
||||
// Invalid type that can be used to detect when the full response has been received
|
||||
COMMAND_END: 255
|
||||
};
|
||||
/**
|
||||
* Predefined responses the Minecraft Server can send
|
||||
* @type {Object}
|
||||
*/
|
||||
Packet.payload = {
|
||||
// Response the server sends after receiving a packet with above invalid type
|
||||
COMMAND_END: `Unknown request ${Packet.type['COMMAND_END'].toString(16)}`
|
||||
};
|
||||
|
||||
module.exports = Packet;
|
||||
@@ -0,0 +1,140 @@
|
||||
const net = require('net');
|
||||
const EventEmitter = require('events');
|
||||
|
||||
const Packet = require('./Packet.js');
|
||||
/**
|
||||
* Used to create and send commands through a console using the RCON protocol
|
||||
*/
|
||||
module.exports = class RCON {
|
||||
/**
|
||||
* @param {Number} [timeout=3000] Timeout for connections and responses
|
||||
*/
|
||||
constructor (timeout = 3000) {
|
||||
this.timeout = timeout;
|
||||
this.online = false;
|
||||
this.authenticated = false;
|
||||
this.queue = {
|
||||
drained: true,
|
||||
sending: [],
|
||||
pending: {}
|
||||
};
|
||||
this.events = new EventEmitter()
|
||||
.on('removeListener', (id, listener) => {
|
||||
clearTimeout(this.queue.pending[id].timer);
|
||||
delete this.queue.pending[id];
|
||||
})
|
||||
.on('newListener', (id, listener) => {
|
||||
this.queue.pending[id] = {
|
||||
timer: setTimeout(() => {
|
||||
this.events.emit(id, new Error(`Packet timed out!`));
|
||||
this.events.off(id, listener);
|
||||
}, this.timeout),
|
||||
payloads: []
|
||||
};
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Ends the connection, but doesn't destroy it
|
||||
*/
|
||||
end () {
|
||||
this.socket.end();
|
||||
}
|
||||
/**
|
||||
* Immediately sends out as many queued packets as possible
|
||||
*/
|
||||
drain () {
|
||||
while (this.queue.drained && this.queue.sending.length > 0) {
|
||||
this.queue.drained = this.socket.write(this.queue.sending.shift());
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Connects and authenticates the RCON instance
|
||||
* @param {String} server IP from where to find the server
|
||||
* @param {Number} port Port from where to connect
|
||||
* @param {String} password Password with which to connect
|
||||
* @return {Promise} Resolves if succesful or Rejects an Error if one occured
|
||||
*/
|
||||
connect (server, port, password) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let data = Buffer.allocUnsafe(0);
|
||||
this.socket = net.connect({ host: server, port: port })
|
||||
.on('data', (chunk) => {
|
||||
data = Buffer.concat([data, chunk]);
|
||||
try {
|
||||
let length = data.readInt32LE(0);
|
||||
while (data.length >= 4 + length) {
|
||||
const response = Packet.read(data.slice(0, 4 + length));
|
||||
this.events.emit('' + response.id, response);
|
||||
data = data.slice(4 + length);
|
||||
length = data.readInt32LE(0);
|
||||
}
|
||||
} catch (error) { /* We don't have enough data yet */ }
|
||||
})
|
||||
.on('drain', () => { this.drain(); })
|
||||
.on('close', () => { this.authenticated = false; this.online = false; })
|
||||
.on('error', error => { throw error; })
|
||||
.setTimeout(this.timeout, () => {
|
||||
this.socket.destroy();
|
||||
reject(new Error(`Socket timed out when connecting to [${server}:${port}]`));
|
||||
})
|
||||
.once('connect', () => {
|
||||
this.online = true;
|
||||
this.socket.setTimeout(0);
|
||||
// Send and process authentication packet
|
||||
this.socket.write(Packet.write(0, Packet.type['AUTH'], password));
|
||||
this.events.on(0, result => {
|
||||
if (result instanceof Error) {
|
||||
reject(result);
|
||||
} else {
|
||||
if (result.type !== Packet.type['AUTH_RES']) {
|
||||
reject(new Error(`Packet is of wrong type! [${result.type}]`));
|
||||
} else {
|
||||
this.events.removeAllListeners(0);
|
||||
if (result.id === -1) {
|
||||
reject(new Error(`Authentication failed!`));
|
||||
} else {
|
||||
this.authenticated = true;
|
||||
resolve();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Send the given command through authenticated RCON connection
|
||||
* @param {String} command
|
||||
* @return {Promise} Resolves to response or Rejects an Error if one occured
|
||||
*/
|
||||
send (command) {
|
||||
if (!this.online || !this.authenticated) {
|
||||
return Promise.reject(new Error('The connection needs to be made and authenticated first!'));
|
||||
} else {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = Packet.id();
|
||||
this.queue.sending.push(Packet.write(id, Packet.type['COMMAND'], command));
|
||||
this.queue.sending.push(Packet.write(id, Packet.type['COMMAND_END'], ''));
|
||||
this.drain();
|
||||
this.events.on(id, result => {
|
||||
if (result instanceof Error) {
|
||||
reject(result);
|
||||
} else {
|
||||
if (result.type !== Packet.type['COMMAND_RES']) {
|
||||
reject(new Error(`Packet is of wrong type! [${result.type}]`));
|
||||
} else {
|
||||
if (result.payload === Packet.payload['COMMAND_END']) {
|
||||
const response = this.queue.pending[result.id].payloads
|
||||
.reduce((data, chunk) => data + chunk);
|
||||
this.events.removeAllListeners(id);
|
||||
resolve(response);
|
||||
} else {
|
||||
this.queue.pending[result.id].payloads.push(result.payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
node-rcon by https://github.com/tehbeard/node-rcon
|
||||
@@ -0,0 +1,22 @@
|
||||
var RCON = require('../RCON');
|
||||
var rcon = new RCON();
|
||||
|
||||
rcon.connect('localhost', 22575, 'supersecret')
|
||||
.then(() => {
|
||||
console.log('Connected and authenticated.');
|
||||
return rcon.send('/op superman');
|
||||
})
|
||||
.then(response => {
|
||||
console.log(`Result of op: ${response}`);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(`An error occured: ${error}`);
|
||||
});
|
||||
|
||||
rcon.send('/deop superman')
|
||||
.then(response => {
|
||||
console.log(`Result of deop: ${response}`);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(`An error occured: ${error}`);
|
||||
});
|
||||
@@ -1,66 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Basic Options */
|
||||
// "incremental": true, /* Enable incremental compilation */
|
||||
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
|
||||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
|
||||
// "lib": [], /* Specify library files to be included in the compilation. */
|
||||
// "allowJs": true, /* Allow javascript files to be compiled. */
|
||||
// "checkJs": true, /* Report errors in .js files. */
|
||||
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
||||
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
||||
// "sourceMap": true, /* Generates corresponding '.map' file. */
|
||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
||||
// "outDir": "./", /* Redirect output structure to the directory. */
|
||||
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
||||
// "composite": true, /* Enable project compilation */
|
||||
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
|
||||
// "removeComments": true, /* Do not emit comments to output. */
|
||||
// "noEmit": true, /* Do not emit outputs. */
|
||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
||||
|
||||
/* Strict Type-Checking Options */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* Enable strict null checks. */
|
||||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
||||
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
|
||||
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
|
||||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
||||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
||||
|
||||
/* Additional Checks */
|
||||
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
||||
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
||||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
||||
|
||||
/* Module Resolution Options */
|
||||
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
||||
// "types": [], /* Type declaration files to be included in compilation. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
||||
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
|
||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
|
||||
/* Source Map Options */
|
||||
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
||||
|
||||
/* Experimental Options */
|
||||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
||||
|
||||
/* Advanced Options */
|
||||
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user