const fs = require('fs/promises') const uuid = require('uuid') const { Unit } = require('libflitter') const CoreIDAuthentication = require('../classes/radius/CoreIDAuthentication') const net = require("net"); class RadiusUnit extends Unit { static get services() { return [...super.services, 'configs', 'output', 'models'] } async go(app) { if ( !this.configs.get('radius.enable') ) return; const CoreIDRadiusServer = (await import('../classes/radius/CoreIDRadiusServer.mjs')).default // Load the certificates const pubkey = await fs.readFile(this.configs.get('radius.cert_file.public')) const privkey = await fs.readFile(this.configs.get('radius.cert_file.private')) this.radius = new CoreIDRadiusServer({ // logger secret: this.configs.get('radius.secret', uuid.v4()), port: this.configs.get('radius.port', 1812), address: this.configs.get('radius.interface', '0.0.0.0'), tlsOptions: { cert: pubkey, key: privkey, }, authentication: new CoreIDAuthentication(), }) if ( await this.port_free() ) { this.output.info('Starting RADIUS server...') await this.radius.start() } else { this.output.error('Will not start RADIUS server. Reason: configured port is already in use') delete this.radius } } async cleanup(app) { if ( this.radius ) { await this.radius.server.close() } } async port_free() { return new Promise((res, rej) => { const server = net.createServer() server.once('error', (e) => { res(false) }) server.once('listening', () => { server.close() res(true) }) server.listen(this.configs.get('radius.port', 1812)) }) } } module.exports = exports = RadiusUnit