thelounge/src/identification.js

124 lines
2.7 KiB
JavaScript
Raw Normal View History

"use strict";
2018-06-15 22:31:06 +02:00
const log = require("./log");
const fs = require("fs");
const net = require("net");
2018-03-02 19:28:54 +01:00
const colors = require("chalk");
const Helper = require("./helper");
const Config = require("./config");
class Identification {
constructor(startedCallback) {
this.connectionId = 0;
this.connections = new Map();
if (typeof Config.values.oidentd === "string") {
this.oidentdFile = Helper.expandHome(Config.values.oidentd);
log.info(`Oidentd file: ${colors.green(this.oidentdFile)}`);
this.refresh();
}
if (Config.values.identd.enable) {
if (this.oidentdFile) {
2019-07-17 11:33:59 +02:00
log.warn(
"Using both identd and oidentd at the same time, this is most likely not intended."
);
}
2018-01-11 12:33:36 +01:00
const server = net.createServer(this.serverConnection.bind(this));
server.on("error", (err) => {
startedCallback(this, err);
});
2019-07-17 11:33:59 +02:00
server.listen(
{
port: Config.values.identd.port || 113,
host: Config.values.bind,
2019-07-17 11:33:59 +02:00
},
() => {
const address = server.address();
log.info(
`Identd server available on ${colors.green(
address.address + ":" + address.port
)}`
);
startedCallback(this);
}
);
} else {
startedCallback(this);
}
}
serverConnection(socket) {
2019-06-10 12:13:27 +02:00
socket.on("error", (err) => log.error(`Identd socket error: ${err}`));
socket.on("data", (data) => {
this.respondToIdent(socket, data);
socket.end();
});
}
respondToIdent(socket, data) {
data = data.toString().split(",");
2018-05-15 15:04:05 +02:00
const lport = parseInt(data[0], 10) || 0;
const fport = parseInt(data[1], 10) || 0;
if (lport < 1 || fport < 1 || lport > 65535 || fport > 65535) {
return;
}
2018-01-11 12:33:36 +01:00
for (const connection of this.connections.values()) {
if (connection.socket.remotePort === fport && connection.socket.localPort === lport) {
2019-07-17 11:33:59 +02:00
return socket.write(
`${lport}, ${fport} : USERID : TheLounge : ${connection.user}\r\n`
);
}
}
socket.write(`${lport}, ${fport} : ERROR : NO-USER\r\n`);
}
addSocket(socket, user) {
const id = ++this.connectionId;
this.connections.set(id, {socket, user});
if (this.oidentdFile) {
this.refresh();
}
return id;
}
removeSocket(id) {
this.connections.delete(id);
if (this.oidentdFile) {
this.refresh();
}
}
refresh() {
let file = "# Warning: file generated by The Lounge: changes will be overwritten!\n";
this.connections.forEach((connection) => {
2019-07-17 11:33:59 +02:00
file +=
`fport ${connection.socket.remotePort}` +
` lport ${connection.socket.localPort}` +
` { reply "${connection.user}" }\n`;
});
fs.writeFile(this.oidentdFile, file, {flag: "w+"}, function (err) {
if (err) {
log.error("Failed to update oidentd file!", err);
}
});
}
}
module.exports = Identification;