X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2Fui-server%2FUIWebSocketServer.ts;h=b973cf45b6663aa43be9fda38a2dd43ca04ad9a7;hb=eb3abc4fe41400debcf894e53f91937498e77571;hp=66980f610f08e86a4f111ded7db26a9bab7ec41e;hpb=02a6943a30a9a6c93e5dcbdb79aa8d9746ae368e;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ui-server/UIWebSocketServer.ts b/src/charging-station/ui-server/UIWebSocketServer.ts index 66980f61..b973cf45 100644 --- a/src/charging-station/ui-server/UIWebSocketServer.ts +++ b/src/charging-station/ui-server/UIWebSocketServer.ts @@ -1,81 +1,151 @@ -import { IncomingMessage } from 'http'; +import { IncomingMessage, createServer } from 'http'; +import type internal from 'stream'; -import WebSocket from 'ws'; +import { StatusCodes } from 'http-status-codes'; +import WebSocket, { RawData, WebSocketServer } from 'ws'; -import { ServerOptions } from '../../types/ConfigurationData'; -import { Protocol, ProtocolVersion } from '../../types/UIProtocol'; -import Configuration from '../../utils/Configuration'; +import BaseError from '../../exception/BaseError'; +import type { UIServerConfiguration } from '../../types/ConfigurationData'; +import type { ProtocolRequest, ProtocolResponse } from '../../types/UIProtocol'; +import { WebSocketCloseEventStatusCode } from '../../types/WebSocket'; import logger from '../../utils/Logger'; import Utils from '../../utils/Utils'; import { AbstractUIServer } from './AbstractUIServer'; import UIServiceFactory from './ui-services/UIServiceFactory'; +import { UIServiceUtils } from './ui-services/UIServiceUtils'; const moduleName = 'UIWebSocketServer'; export default class UIWebSocketServer extends AbstractUIServer { - public constructor(options?: ServerOptions) { - super(); - this.server = new WebSocket.Server(options ?? Configuration.getUIServer().options); + private readonly webSocketServer: WebSocketServer; + + public constructor(protected readonly uiServerConfiguration: UIServerConfiguration) { + super(uiServerConfiguration); + this.httpServer = createServer(); + this.webSocketServer = new WebSocketServer({ + handleProtocols: UIServiceUtils.handleProtocols, + noServer: true, + }); } public start(): void { - this.server.on('connection', (socket: WebSocket, request: IncomingMessage): void => { - const protocolIndex = socket.protocol.indexOf(Protocol.UI); - const version = socket.protocol.substring( - protocolIndex + Protocol.UI.length - ) as ProtocolVersion; - if (!this.uiServices.has(version)) { + this.webSocketServer.on('connection', (ws: WebSocket, req: IncomingMessage): void => { + const [protocol, version] = UIServiceUtils.getProtocolAndVersion(ws.protocol); + if (UIServiceUtils.isProtocolAndVersionSupported(protocol, version) === false) { + logger.error( + `${this.logPrefix( + moduleName, + 'start.server.onconnection' + )} Unsupported UI protocol version: '${protocol}${version}'` + ); + ws.close(WebSocketCloseEventStatusCode.CLOSE_PROTOCOL_ERROR); + } + if (this.uiServices.has(version) === false) { this.uiServices.set(version, UIServiceFactory.getUIServiceImplementation(version, this)); } - // FIXME: check connection validity - socket.on('message', (messageData) => { + ws.on('message', (rawData) => { + const [messageId, procedureName, payload] = this.validateRawDataRequest(rawData); this.uiServices .get(version) - .requestHandler(messageData) - .catch((error) => { - logger.error( - `${this.logPrefix( - moduleName, - 'start.socket.onmessage' - )} Error while handling message:`, - error - ); + .requestHandler(this.buildProtocolRequest(messageId, procedureName, payload)) + .catch(() => { + /* Error caught by AbstractUIService */ }); }); - socket.on('error', (error) => { - logger.error( - `${this.logPrefix(moduleName, 'start.socket.onerror')} Error on WebSocket:`, - error + ws.on('error', (error) => { + logger.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error); + }); + ws.on('close', (code, reason) => { + logger.debug( + `${this.logPrefix( + moduleName, + 'start.ws.onclose' + )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString( + code + )}' - '${reason.toString()}'` ); }); }); + this.httpServer.on( + 'upgrade', + (req: IncomingMessage, socket: internal.Duplex, head: Buffer): void => { + this.authenticate(req, (err) => { + if (err) { + socket.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`); + socket.destroy(); + return; + } + this.webSocketServer.handleUpgrade(req, socket, head, (ws: WebSocket) => { + this.webSocketServer.emit('connection', ws, req); + }); + }); + } + ); + if (this.httpServer.listening === false) { + this.httpServer.listen(this.uiServerConfiguration.options); + } } public stop(): void { - this.server.close(); + this.chargingStations.clear(); } - public sendRequest(request: string): void { - this.broadcastToClients(request); + public sendRequest(request: ProtocolRequest): void { + this.broadcastToClients(JSON.stringify(request)); } - public sendResponse(response: string): void { - this.broadcastToClients(response); + public sendResponse(response: ProtocolResponse): void { + // TODO: send response only to the client that sent the request + this.broadcastToClients(JSON.stringify(response)); } - public logPrefix(modName?: string, methodName?: string): string { + public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string { + const logMsgPrefix = prefixSuffix + ? `UI WebSocket Server ${prefixSuffix}` + : 'UI WebSocket Server'; const logMsg = - modName && methodName - ? ` UI WebSocket Server | ${modName}.${methodName}:` - : ' UI WebSocket Server |'; + modName && methodName ? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`; return Utils.logPrefix(logMsg); } private broadcastToClients(message: string): void { - for (const client of (this.server as WebSocket.Server).clients) { + for (const client of this.webSocketServer.clients) { if (client?.readyState === WebSocket.OPEN) { client.send(message); } } } + + private authenticate(req: IncomingMessage, next: (err: Error) => void): void { + if (this.isBasicAuthEnabled() === true) { + if (this.isValidBasicAuth(req) === false) { + next(new Error('Unauthorized')); + } else { + next(undefined); + } + } else { + next(undefined); + } + } + + private validateRawDataRequest(rawData: RawData): ProtocolRequest { + // logger.debug( + // `${this.logPrefix( + // moduleName, + // 'validateRawDataRequest' + // )} Raw data received in string format: ${rawData.toString()}` + // ); + + const request = JSON.parse(rawData.toString()) as ProtocolRequest; + + if (Array.isArray(request) === false) { + throw new BaseError('UI protocol request is not an array'); + } + + if (request.length !== 3) { + throw new BaseError('UI protocol request is malformed'); + } + + return request; + } }