All files server.ts

61.18% Statements 52/85
47.56% Branches 39/82
50% Functions 9/18
61.18% Lines 52/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 2071x           1x   1x     14x                   14x 14x 14x                 14x 14x   14x       14x       14x                 14x 24x         24x       24x                             24x       14x 7x               7x                                     10x         10x       10x       10x                   2x 2x                                   14x 14x   14x 7x       14x 14x 14x     14x 14x 14x         2x       24x   24x             24x 24x   24x 22x   22x 22x 22x 22x 22x 22x 22x       22x   2x        
import * as HTTP from 'http';
import * as HTTPS from 'https';
 
import { Socket } from 'net';
import { WebSocket } from './client';
import { ServerConfigs } from './index';
import { native, noop, setupNative, APP_PING_CODE, PERMESSAGE_DEFLATE, SLIDING_DEFLATE_WINDOW, DEFAULT_PAYLOAD_LIMIT } from './shared';
 
export class WebSocketServer {
  public upgradeCb: (ws: WebSocket) => void;
  public upgradeReq: HTTP.IncomingMessage;
  public registeredEvents: any = {
    close: noop,
    error: noop,
    connection: noop,
  };
 
  private httpServer: HTTP.Server | HTTPS.Server;
  private serverGroup: any;
  private onUpgradeRequest: (req: HTTP.IncomingMessage, socket: Socket) => void;
 
  constructor(private options: ServerConfigs, cb: () => void = noop) {
    let nativeOptions: number = 0;
    Iif (this.options.perMessageDeflate) {
      // tslint:disable-next-line
      nativeOptions |= PERMESSAGE_DEFLATE;
      if ((this.options.perMessageDeflate as { serverNoContextTakeover: boolean }).serverNoContextTakeover === false) {
        // tslint:disable-next-line
        nativeOptions |= SLIDING_DEFLATE_WINDOW;
      }
    }
 
    this.serverGroup = native.server.group.create(nativeOptions, this.options.maxPayload || DEFAULT_PAYLOAD_LIMIT);
    setupNative(this.serverGroup, 'server', this);
 
    Iif (this.options.noServer) {
      return;
    }
 
    Iif (this.options.path && this.options.path[0] !== '/') {
      this.options.path = `/${this.options.path}`;
    }
 
    this.httpServer = this.options.server || HTTP.createServer((_: any, res: HTTP.ServerResponse): void => {
      const body: string = HTTP.STATUS_CODES[426];
      res.writeHead(426, {
        'Content-Length': body.length,
        'Content-Type': 'text/plain'
      });
      return res.end(body);
    });
 
    this.httpServer.on('upgrade', this.onUpgradeRequest = ((req: HTTP.IncomingMessage, socket: Socket): void => {
      socket.on('error', (): void => {
        // this is how `ws` handles socket error
        socket.destroy();
      });
 
      Iif (this.options.path && this.options.path !== req.url.split('?')[0].split('#')[0]) {
        return this.abortConnection(socket, 400, 'URL not supported');
      }
 
      Iif (this.options.verifyClient) {
        const info: any = {
          origin: req.headers.origin,
          secure: !!((req.connection as any).authorized || (req.connection as any).encrypted),
          req
        };
 
        this.options.verifyClient(info, (verified?: boolean, code?: number, message?: string): void => {
          if (!verified) {
            return this.abortConnection(socket, code || 401, message || 'Client verification failed');
          }
 
          this.upgradeConnection(req, socket);
        });
      } else {
        this.upgradeConnection(req, socket);
      }
    }));
 
    if (this.options.port && !this.options.server) {
      this.httpServer.on('error', (err: Error): void => {
        // listen on http server error only if server has been
        // created by cws, in case if server passed from the
        // user than user is responsible for listening for 'error' event
        // on passed http server
        this.registeredEvents['error'](err);
      });
 
      this.httpServer.listen(this.options.port, this.options.host, cb);
    }
  }
 
  get clients(): { length: number, forEach: (cb: (ws: WebSocket) => void) => void } {
    return {
      length: this.serverGroup ? native.server.group.getSize(this.serverGroup) : 0,
      forEach: (cb: (ws: WebSocket) => void): void => {
        if (this.serverGroup) {
          native.server.group.forEach(this.serverGroup, cb);
        }
      }
    };
  }
 
  public on(event: 'error', listener: (err: Error) => void): void;
  public on(event: 'connection', listener: (socket: WebSocket, req: HTTP.IncomingMessage) => void): void;
  public on(event: 'connection', listener: (socket: WebSocket) => void): void;
  public on(event: string, listener: (...args: any[]) => void): void {
    Iif (this.registeredEvents[event] === undefined) {
      console.warn(`cWS does not support '${event}' event`);
      return;
    }
 
    Iif (typeof listener !== 'function') {
      throw new Error(`Listener for '${event}' event must be a function`);
    }
 
    Iif (this.registeredEvents[event] !== noop) {
      console.warn(`cWS does not support multiple listeners for the same event. Old listener for '${event}' event will be overwritten`);
    }
 
    this.registeredEvents[event] = listener;
  }
 
  public emit(event: string, ...args: any[]): void {
    if (this.registeredEvents[event]) {
      this.registeredEvents[event](...args);
    }
  }
 
  public broadcast(message: string | Buffer, options?: { binary: boolean }): void {
    Eif (this.serverGroup) {
      native.server.group.broadcast(this.serverGroup, message, options && options.binary || false);
    }
  }
 
  public startAutoPing(interval: number, appLevel?: boolean): void {
    if (this.serverGroup) {
      native.server.group.startAutoPing(this.serverGroup, interval, appLevel ? APP_PING_CODE : null);
    }
  }
 
  public handleUpgrade(req: HTTP.IncomingMessage, socket: Socket, upgradeHead: any, cb: (ws: WebSocket) => void): void {
    // `ws` compatibility
    if (this.options.noServer) {
      this.upgradeConnection(req, socket, cb);
    }
  }
 
  public close(cb: () => void = noop): void {
    Eif (this.httpServer) {
      this.httpServer.removeListener('upgrade', this.onUpgradeRequest);
 
      if (!this.options.server) {
        this.httpServer.close();
      }
    }
 
    Eif (this.serverGroup) {
      native.server.group.close(this.serverGroup);
      this.serverGroup = null;
    }
 
    setTimeout((): void => {
      this.registeredEvents['close']();
      cb();
    }, 0);
  }
 
  private abortConnection(socket: Socket, code: number, message: string): void {
    return socket.end(`HTTP/1.1 ${code} ${message}\r\n\r\n`);
  }
 
  private upgradeConnection(req: HTTP.IncomingMessage, socket: Socket, cb?: (ws: WebSocket) => void): void {
    const secKey: any = req.headers['sec-websocket-key'];
 
    Iif ((socket as any)._isNative) {
      if (this.serverGroup) {
        this.upgradeCb = cb;
        this.upgradeReq = req;
        native.upgrade(this.serverGroup, (socket as any).external, secKey, req.headers['sec-websocket-extensions'], req.headers['sec-websocket-protocol']);
      }
    } else {
      const socketAsAny: any = socket as any;
      const socketHandle: any = socketAsAny.ssl ? socketAsAny._parent._handle : socketAsAny._handle;
 
      if (socketHandle && secKey && secKey.length === 24) {
        const sslState: any = socketAsAny.ssl ? native.getSSLContext(socketAsAny.ssl) : null;
 
        socket.setNoDelay(this.options.noDelay === false ? false : true);
        const ticket: any = native.transfer(socketHandle.fd === -1 ? socketHandle : socketHandle.fd, sslState);
        socket.on('close', (): void => {
          Eif (this.serverGroup) {
            this.upgradeCb = cb;
            this.upgradeReq = req;
            native.upgrade(this.serverGroup, ticket, secKey, req.headers['sec-websocket-extensions'], req.headers['sec-websocket-protocol']);
          }
        });
 
        socket.destroy();
      } else {
        return this.abortConnection(socket, 400, 'Bad Request');
      }
    }
  }
}