2021-10-02 00:16:34 +00:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
import net from 'net';
|
|
|
|
import { EventEmitter, once } from 'events';
|
|
|
|
|
|
|
|
import l from 'log';
|
|
|
|
import nexline from 'nexline';
|
|
|
|
|
|
|
|
import settings from '../../settings.mjs';
|
2021-10-02 02:02:49 +00:00
|
|
|
import rekey from './rekey.mjs';
|
|
|
|
import { write_safe } from '../io/StreamHelpers.mjs';
|
|
|
|
import { encrypt_bytes, decrypt_bytes } from '../crypto/secretbox.mjs';
|
2021-10-02 00:16:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Represents a connection to a single endpoint.
|
|
|
|
*/
|
|
|
|
class Connection extends EventEmitter {
|
2021-10-02 02:02:49 +00:00
|
|
|
constructor(secret_join) {
|
2021-10-02 00:16:34 +00:00
|
|
|
super();
|
2021-10-02 02:02:49 +00:00
|
|
|
|
|
|
|
this.session_key = Buffer.from(secret_join, "base64");
|
2021-10-02 00:16:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Connects to a peer and initialises a secure TCP connection thereto.
|
|
|
|
* @param {string} address The address to connect to.
|
|
|
|
* @param {string} port The TCP port to connect to.
|
|
|
|
* @return {net.Socket} A socket setup for secure communication.
|
|
|
|
*/
|
|
|
|
async connect(address, port) {
|
|
|
|
this.address = address; this.port = port;
|
|
|
|
this.socket = new new.Socket();
|
|
|
|
this.socket.connect({
|
|
|
|
address, port
|
|
|
|
});
|
|
|
|
await once(this.socket, "connect");
|
|
|
|
this.socket.setKeepAlive(true);
|
|
|
|
|
2021-10-02 02:02:49 +00:00
|
|
|
this.session_key = await rekey(this.socket, this.session_key);
|
2021-10-02 00:16:34 +00:00
|
|
|
|
2021-10-02 02:02:49 +00:00
|
|
|
this.reader = nexline({
|
|
|
|
input: this.socket
|
|
|
|
});
|
2021-10-02 00:16:34 +00:00
|
|
|
|
2021-10-02 02:02:49 +00:00
|
|
|
this.read_task = read_loop();
|
2021-10-02 00:16:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
destroy() {
|
|
|
|
this.socket.destroy();
|
|
|
|
this.emit("destroy");
|
|
|
|
}
|
|
|
|
|
|
|
|
async read_loop() {
|
|
|
|
try {
|
|
|
|
for await (let line of this.reader) {
|
|
|
|
handle_message(line);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
catch(error) {
|
|
|
|
l.warn(`Warning: Killing connection to ${this.address}:${this.port} after error: ${settings.cli.verbose ? error : error.message}`);
|
|
|
|
}
|
|
|
|
finally {
|
|
|
|
this.destroy();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
handle_message(text) {
|
|
|
|
let message = JSON.parse(text);
|
|
|
|
|
|
|
|
}
|
2021-10-02 02:02:49 +00:00
|
|
|
|
|
|
|
async send(message) {
|
|
|
|
// TODO: Implement a binary frame-based protocol here instead? It would be 33% more bandwidth efficient.
|
|
|
|
// Perhaps <length> <data>? If messages are too long, we'll have to do something about that though....
|
|
|
|
let payload = JSON.stringify(message);
|
|
|
|
payload = encrypt_bytes(this.session_key, payload);
|
|
|
|
|
|
|
|
await write_safe(this.socket, payload);
|
|
|
|
}
|
2021-10-02 00:16:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export default Connection;
|