all files / dist/servers/ tcp.js

79.43% Statements 139/175
61.54% Branches 56/91
81.82% Functions 27/33
78.67% Lines 118/150
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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469          10×                                                                                                                                                                                                 119×     119×     119×     119×   71× 19×   52×         119× 119×                                                                                                                         146×         145×     73× 73×         57×     57× 57×     57×   57× 146× 146× 146×                                             19× 19× 19×                                   73×   73×     73×   73×               73× 70×   39× 31×   19×   19×     12× 10×   10× 12×         12× 12×           19× 19×     19×     12×                                                                               57× 57×   57×   57×       57×                                                                                                    
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
 
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; Eif ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { Eif (protoProps) defineProperties(Constructor.prototype, protoProps); Iif (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
 
var _net = require('net');
 
var _net2 = _interopRequireDefault(_net);
 
var _tls = require('tls');
 
var _tls2 = _interopRequireDefault(_tls);
 
var _genericServer = require('../genericServer');
 
var _genericServer2 = _interopRequireDefault(_genericServer);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _classCallCheck(instance, Constructor) { Iif (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
function _possibleConstructorReturn(self, call) { Iif (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
 
function _inherits(subClass, superClass) { Iif (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); Eif (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
 
// server type
var type = 'tcp';
 
// server attributes
var attributes = {
  canChat: true,
  logConnections: true,
  logExits: true,
  pendingShutdownWaitLimit: 5000,
  sendWelcomeMessage: true,
  verbs: ['quit', 'exit', 'paramAdd', 'paramDelete', 'paramView', 'paramsView', 'paramsDelete', 'roomAdd', 'roomLeave', 'roomView', 'detailsView', 'say']
};
 
/**
 * TCP server implementation.
 */
 
var Tcp = function (_GenericServer) {
  _inherits(Tcp, _GenericServer);
 
  /**
   * Create a new server instance.
   *
   * @param api       API object reference.
   * @param options   Server options.
   */
 
  function Tcp(api, options) {
    _classCallCheck(this, Tcp);
 
    // define events
 
    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Tcp).call(this, api, type, options, attributes));
    // call super constructor
 
 
    _this.server = null;
    _this._defineEvents();
    return _this;
  }
 
  // ------------------------------------------------------------------------------------------------ [Required Methods]
 
  /**
   * Start server.
   *
   * @param callback callback
   */
 
 
  /**
   * TCP server socket.
   */
 
 
  _createClass(Tcp, [{
    key: 'start',
    value: function start(callback) {
      var self = this;
 
      Eif (self.options.secure === false) {
        self.server = _net2.default.createServer(self.api.config.servers.tcp.serverOptions, function (rawConnection) {
          self._handleConnection(rawConnection);
        });
      } else {
        self.server = _tls2.default.createServer(self.api.config.servers.tcp.serverOptions, function (rawConnection) {
          self._handleConnection(rawConnection);
        });
      }
 
      // on server error
      self.server.on('error', function (e) {
        return callback(new Error('Cannot start tcp server @ ' + self.options.bindIP + ':' + self.options.port + ' => ' + e.message));
      });
 
      // server listener
      self.server.listen(self.options.port, self.options.bindIP, function () {
        process.nextTick(callback);
      });
    }
 
    /**
     * Stop server.
     *
     * @param next
     */
 
  }, {
    key: 'stop',
    value: function stop(next) {
      this._gracefulShutdown(next);
    }
 
    /**
     * Send a message to a client.
     *
     * @param connection    Client connection object.
     * @param message       Message to be sent.
     * @param messageCount  Number of messages already sent for this client.
     */
 
  }, {
    key: 'sendMessage',
    value: function sendMessage(connection, message, messageCount) {
      var self = this;
 
      // if is an error message serialize the object
      if (message.error) {
        message.error = self.api.config.errors.serializers.servers.tcp(message.error);
      }
 
      Iif (connection.respondingTo) {
        message.messageCount = messageCount;
        connection.respondingTo = null;
      } else if (message.context === 'response') {
        // if the messageCount isn't defined use the connection.messageCount
        if (messageCount) {
          message.messageCount = messageCount;
        } else {
          message.messageCount = connection.messageCount;
        }
      }
 
      // try send the message to the client
      try {
        connection.rawConnection.write(JSON.stringify(message) + '\r\n');
      } catch (e) {
        self.api.log('socket write error: ' + e, 'error');
      }
    }
 
    /**
     * Close the connection with the client sending a 'Bye!' message.
     *
     * @param connection  Client connection.
     */
 
  }, {
    key: 'goodbye',
    value: function goodbye(connection) {
      var self = this;
 
      try {
        connection.rawConnection.end(JSON.stringify({
          status: connection.localize(self.api.config.servers.tcp.goodbeyMessage),
          context: 'api'
        }) + '\r\n');
      } catch (e) {}
    }
 
    /**
     * Send a file to the client.
     *
     * If the error is defined send a error message instead.
     *
     * @param connection  Client connection object.
     * @param error       Error object.
     * @param fileStream  FileStream object.
     */
 
  }, {
    key: 'sendFile',
    value: function sendFile(connection, error, fileStream) {
      var self = this;
 
      // if is an error response send a message with the error
      if (error) {
        self.server.sendMessage(connection, error, connection.messageCount);
      } else {
        // send the file to client
        fileStream.pipe(connection.rawConnection, { end: false });
      }
    }
 
    // ---------------------------------------------------------------------------------------------------------- [Events]
 
    /**
     * Define server events.
     *
     * @private
     */
 
  }, {
    key: '_defineEvents',
    value: function _defineEvents() {
      var self = this;
 
      // on connection event
      self.on('connection', function (connection) {
        connection.params = {};
 
        var parseLine = function parseLine(line) {
          // check the message length if the maxDataLength is active
          if (self.api.config.servers.tcp.maxDataLength > 0) {
            var bufferLen = Buffer.byteLength(line, 'utf8');
 
            if (bufferLen > self.api.config.servers.tcp.maxDataLength) {
              var error = self.api.config.errors.dataLengthTooLarge(self.api.config.servers.tcp.maxDataLength, bufferLen);
              self.log(error, 'error');
              return self.sendMessage(connection, { status: 'error', error: error, context: 'response' });
            }
          }
 
          if (line.length > 0) {
            // increment at the start of the request so that responses can be caught in order
            // on the client, this is not handled by the genericServer
            connection.messageCount++;
            self._parseRequest(connection, line);
          }
        };
 
        // on data event
        connection.rawConnection.on('data', function (chunk) {
          Iif (self._checkBreakChars(chunk)) {
            connection.destroy();
          } else {
            connection.rawConnection.socketDataString += chunk.toString('utf-8').replace(/\r/g, '\n');
            var index = void 0;
 
            // get delimiter
            var delimiter = String(self.api.config.servers.tcp.delimiter);
 
            while ((index = connection.rawConnection.socketDataString.indexOf(delimiter)) > -1) {
              var data = connection.rawConnection.socketDataString.slice(0, index);
              connection.rawConnection.socketDataString = connection.rawConnection.socketDataString.slice(index + delimiter.length);
              data.split(delimiter).forEach(parseLine);
            }
          }
        });
 
        // on end event
        connection.rawConnection.on('end', function () {
          // if the connection isn't destroyed do it now
          if (connection.destroyed !== true) {
            try {
              connection.rawConnection.end();
            } catch (e) {}
            connection.destroy();
          }
        });
 
        // on error event
        connection.rawConnection.on('error', function (e) {
          Iif (connection.destroyed !== true) {
            self.log('server error: ' + e, 'error');
 
            try {
              connection.rawConnection.end();
            } catch (e) {}
            connection.destroy();
          }
        });
      });
 
      // on actionComplete event
      self.on('actionComplete', function (data) {
        Eif (data.toRender === true) {
          data.response.context = 'response';
          self.sendMessage(data.connection, data.response, data.messageCount);
        }
      });
    }
 
    // --------------------------------------------------------------------------------------------------------- [Helpers]
 
    /**
     * Parse client request.
     *
     * @param connection  Client connection object.
     * @param line        Request line to be parsed.
     * @private
     */
 
  }, {
    key: '_parseRequest',
    value: function _parseRequest(connection, line) {
      var self = this;
 
      var words = line.split(' ');
 
      // get the verb how are
      var verb = words.shift();
 
      Iif (verb === 'file') {
        if (words.length > 0) {
          connection.params.file = words[0];
        }
        self.processFile(connection);
        return;
      }
 
      connection.verbs(verb, words, function (error, data) {
        if (!error) {
          // send an success response message
          self.sendMessage(connection, { status: 'OK', context: 'response', data: data });
        } else if (error.match('verb not found or not allowed')) {
          // check for and attempt to check single-use params
          try {
            // parse JSON request
            var requestHash = JSON.parse(line);
 
            // pass all founded params to the connection object
            if (requestHash.params !== undefined) {
              connection.params = {};
 
              for (var v in requestHash.params) {
                connection.params[v] = requestHash.params[v];
              }
            }
 
            // pass action name to the connection object, if exists
            Eif (requestHash.action) {
              connection.params.action = requestHash.action;
            }
          } catch (e) {
            connection.params.action = verb;
          }
 
          // reset some connection properties
          connection.error = null;
          connection.response = {};
 
          // process actions
          self.processAction(connection);
        } else {
          // send an error message
          self.sendMessage(connection, { status: error, context: 'response', data: data });
        }
      });
    }
 
    /**
     * Handle new connection.
     *
     * @param rawConnection Client raw connection object.
     * @private
     */
 
  }, {
    key: '_handleConnection',
    value: function _handleConnection(rawConnection) {
      var self = this;
 
      // if the options are enabled, set keepAlive to true
      Iif (self.api.config.servers.tcp.setKeepAlive === true) {
        rawConnection.setKeepAlive(true);
      }
 
      // reset socket data
      rawConnection.socketDataString = '';
 
      // build a new connection object (will emit 'connection')
      self.buildConnection({
        rawConnection: rawConnection,
        remoteAddress: rawConnection.remoteAddress,
        remotePort: rawConnection.remotePort
      });
    }
 
    /**
     * Check if the chunk contains the break chars.
     *
     * @param chunk         Chunk to the analysed.
     * @returns {boolean}   True if found, false otherwise.
     * @private
     */
 
  }, {
    key: '_checkBreakChars',
    value: function _checkBreakChars(chunk) {
      var found = false;
      var hexChunk = chunk.toString('hex', 0, chunk.length);
 
      Iif (hexChunk === 'fff4fffd06') {
        found = true; // CTRL + C
      } else Iif (hexChunk === '04') {
        found = true; // CTRL + D
      }
 
      return found;
    }
 
    /**
     * Try a graceful shutdown.
     *
     * We will wait a while to Stellar try response to the pending connections.
     *
     * @param next              Callback.
     * @param alreadyShutdown   Informs if the server was already shutdown.
     * @private
     */
 
  }, {
    key: '_gracefulShutdown',
    value: function _gracefulShutdown(next) {
      var alreadyShutdown = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
 
      var self = this;
 
      // if the server isn't already shutdown do it now
      Eif (!alreadyShutdown || alreadyShutdown === false) {
        self.server.close();
      }
 
      var pendingConnections = 0;
 
      // finish all pending connections
      self.connections().forEach(function (connection) {
        // if there is no pending actions destroy the connection
        if (connection.pendingActions === 0) {
          connection.destroy();
          return;
        }
 
        // increment the pending connections
        pendingConnections++;
 
        if (!connection.rawConnection.shutDownTimer) {
          connection.rawConnection.shutDownTimer = setTimeout(function () {
            connection.destroy();
          }, attributes.pendingShutdownWaitLimit);
        }
      });
 
      Iif (pendingConnections > 0) {
        self.log('waiting on shutdown, there are still ' + pendingConnections + ' connected clients waiting on a response', 'notice');
        setTimeout(function () {
          self._gracefulShutdown(next, true);
        }, 1000);
      } else Eif (typeof next === 'function') {
        next();
      }
    }
  }]);
 
  return Tcp;
}(_genericServer2.default);
 
exports.default = Tcp;
//# sourceMappingURL=tcp.js.map