Mumble connection

@param {Socket} socket - SSL socket connected to the server.
@param {Object} options - Connection options.
975844
function( socket, options ) {
    var self = this;
    this.socket = new MumbleSocket( socket );
    this.options = options;
    socket.on( 'close', this.disconnect.bind( this ) );
    socket.on( 'error', function( err ) {
        self.emit( 'error', err );
    } );

    // Set up the encoders we use for encoding our audio.
    this.opusEncoder = new OpusEncoder( this.SAMPLING_RATE );
    this.celtEncoder = new CeltEncoder( this.SAMPLING_RATE, this.FRAME_SIZE );

    this.currentEncoder = this.opusEncoder;
    this.codec = MumbleConnection.codec.Opus;

    // Set up the ping loop.
    this.pingInterval = setInterval( function() { self._ping(); }, 1000 );

    // Member fields.
    this.channels = {};
    this.users = {};
    this.packetBuffer = new Buffer( this.FRAME_SIZE * 2 );
    this.voiceBuffer = [];
    this.voiceBufferLength = 0;
    this.voiceSequence = 0;
    this.authSent = false;

    this.lastProcess = Date.now();
    this.processInterval = setInterval(
        this._processAudio.bind( this ),
        this.FRAME_LENGTH );

    // Initialize the debug files if we specified MUMBLE_FILEOUT option.
    if( process.env.MUMBLE_FILEOUT ) {
        var fs = require( 'fs' );
        var fname = process.env.MUMBLE_FILEOUT;
        this.out_pcm = fs.createWriteStream( fname + '_out.pcm' );
        this.out_celt = fs.createWriteStream( fname + '_out.celt' );
        this.in_celt = fs.createWriteStream( fname + '_in.celt' );
        this.in_jitter_celt = fs.createWriteStream( fname + '_in_jitter.celt' );
    }

    // Start waiting for the init messages.
    this.initPending = [ 'ServerSync', 'ServerConfig' ];

    // Start queueing for a message prefix.
    this._waitForPrefix( this );
}
1099280
function connect(options, connectListener)
{
	var socket = net.connect(options, () => {
		if ( connectListener )
		{
			connectListener();
		}
	});
	
	return new Client(socket, options);
}
334492
function SocketPeer (opts) {
  var self = this;

  if (!(self instanceof SocketPeer)) {
    return new SocketPeer(opts);
  }

  opts = opts || {};

  EventEmitter.call(self);

  self._connections = {
    socket: {success: 0, error: 0, attempt: 0},
    rtc: {success: 0, error: 0, attempt: 0}
  };
  self.peer = null;
  self.rtcConnected = false;
  self.socketConnected = false;

  extend(self, {
    pairCode: 'pairCode' in opts ? opts.pairCode : null,
    socketFallback: 'socketFallback' in opts ? opts.socketFallback : true,
    socket: 'socket' in opts ? opts.socket : null,
    stream: 'stream' in opts ? opts.stream : null,
    url: 'url' in opts ? opts.url : 'http://localhost',
    reconnect: 'reconnect' in opts ? opts.reconnect : true,
    reconnectDelay: 'reconnectDelay' in opts ? opts.reconnectDelay : 1000,
    timeout: 'timeout' in opts ? opts.timeout : 0,
    autoconnect: 'autoconnect' in opts ? opts.autoconnect : true,
    debug: 'debug' in opts ? opts.debug : false
  }, opts);

  self._debug('New peer');

  self.on('peer.found', function (data) {
    self.socketConnected = true;
    clearTimeout(self._socketConnectTimeout);
    clearTimeout(self._socketReconnectDelayTimeout);
    self._connections.socket.attempt = 0;
    self._connections.socket.success++;

    self.emit('connect');
    if (self._connections.socket.success > 0) {
      self.emit('reconnect');
    }

    self.initiator = data.initiator;

    if (data.initiator) {
      self._send('rtc.connect');
      self._rtcInit();
    }
  });
  self.on('rtc.signal', self._rtcSignal);
  self.on('rtc.connect', function () {
    self._rtcInit();
  });

  self.on('busy', function () {
    self._socketError(new Error('Pair code "' + self.pairCode + '" already in use'));
    self.socket.close();
  });

  if (self.autoconnect) {
    setTimeout(function () {
      self.connect();
    }, 0);
  }
}
507832
function createSocket(socket, options = {}) {
  if (!isSocket(socket)) {
    options = socket; // eslint-disable-line no-param-reassign

    if (isSocket(options.socket)) {
      // eslint-disable-next-line no-param-reassign, prefer-destructuring
      socket = options.socket;
    } else {
      socket = dgram.createSocket(options); // eslint-disable-line no-param-reassign
      socket.bind(options.port || 0, options.address || '0.0.0.0');
    }
  }

  return new Socket(Object.assign({}, options, { socket }));
}
449933
function onConnection(socket) {
  var endpoint = new http2.Endpoint(log, 'SERVER', {});
  endpoint.pipe(socket).pipe(endpoint);

  endpoint.on('stream', function(stream) {
    stream.on('headers', function(headers) {
      var path = headers[':path'];
      var filename = join(__dirname, path);

      // Serving server.js from cache. Useful for microbenchmarks.
      if (path == cachedUrl) {
        stream.headers({ ':status': 200 });
        stream.end(cachedFile);
      }

      // Reading file from disk if it exists and is safe.
      else if ((filename.indexOf(__dirname) === 0) && exists(filename) && stat(filename).isFile()) {
        stream.headers({ ':status': 200 });

        // If they download the certificate, push the private key too, they might need it.
        if (path === '/localhost.crt') {
          var push = stream.promise({
            ':method': 'GET',
            ':scheme': headers[':scheme'],
            ':authority': headers[':authority'],
            ':path': '/localhost.key'
          });
          push.headers({ ':status': 200 });
          read(join(__dirname, '/localhost.key')).pipe(push);
        }

        read(filename).pipe(stream);
      }

      // Otherwise responding with 404.
      else {
        stream.headers({ ':status': 404 });
        stream.end();
      }
    });
  });
}
459076
function ClientConnection(options) {

    if (options.udp4 === true && options.tcp === true) {
        throw new Error('Both udp and tcp are set as protocol.  Devices can only communicate in one protocol.');
    }
    if (options.udp4 === false && options.tcp === false) {
        throw new Error('Neither UDP or TCP is set.  Devices must communicate in one protocol.');
    }

    if (options.udp4) {
        this.enable_compression = true;
        this.createProxySocket('udp4', options.proxyUrl, options.port);
    } else {
        this.enable_compression = false;
        this.createProxySocket('tcp', options.proxyUrl, options.port);
    }

    this.log = options.log;

    EventEmitter.call(this);
}
744255
function GameServer(options, channel) {
    EventEmitter.call(this);
    this.setMaxListeners(0);

    /**
     * ### GameServer.options
     *
     * Reference to the user options defined in the server channel
     */
    this.options = options;

    /**
     * ### GameServer.channel
     *
     * Reference to the _ServerChannel_ in which the game server is created
     *
     * @see ServerChannel
     */
    this.channel = channel;

    /**
     * ### GameServer.servernode
     *
     * Reference to the _ServerNode_
     *
     * @see ServerNode
     */
    this.servernode = this.channel.servernode;

    /**
     * ### GameServer.registry
     *
     * Reference to _ChannelRegistry_ inside the server channel
     *
     * @see GameServer.channel
     * @see ChannelRegistry
     */
    this.registry = channel.registry;

    /**
     * ### GameServer.session
     *
     * The session ID as created by the channel.
     */
    this.session = channel.session;

    /**
     * ### GameServer.endpoint
     *
     * The endpoint under which the server is reachable
     */
    this.endpoint = '/' + options.endpoint;

    /**
     * ### GameServer.name
     *
     * The name of the server
     */
    this.name = options.name;

    /**
     * ### GameServer.serverid
     *
     * A random id for the server
     */
    this.serverid = '' + Math.random()*1000000000;

    /**
     * ### GameServer.sysLogger
     *
     * Logger of system events
     */
    this.sysLogger = Logger.get('channel', { name: this.name });

    /**
     * ### GameServer.msgLogger
     *
     * Logger of incoming / outgoing game messages
     */
    this.msgLogger = Logger.get('messages', { name: this.name });

    /**
     * ### GameServer.socket
     *
     * Socket manager for the server
     *
     * @see SocketManager
     */
    this.socketManager = new SocketManager(this);

    /**
     * ### GameServer.msg
     *
     * Game message generator
     *
     * @see GameMsgGenerator
     */
    this.msg = new GameMsgGenerator(this);

    /**
     * ### GameServer.partner
     *
     * The partner game server (Admin or Player)
     *
     * @see AdminServer
     * @see PlayerServer
     */
    this.partner = null;

    /**
     * ### GameServer.sio
     *
     * Reference to the Socket.io App in the ServerNode
     *
     * @see ServerNode
     * @see ServerChannel
     */
    this.sio = channel.sio;

    /**
     * ### GameServer.authCb
     *
     * An authorization callback
     */
    this.authCb = null;

    /**
     * ### GameServer.accessDeniedUrl
     *
     * The url of the page to which unauthorized clients will be redirected
     */
    this.accessDeniedUrl = options.accessDeniedUrl;

    /**
     * ### GameServer.generateClientId
     *
     * Client IDs generator callback.
     */
    this.generateClientId = null;

    /**
     * ### GameServer.enableReconnections
     *
     * If TRUE, clients can reconnect to same game room
     *
     * Clients will be matched with previous game history based on
     * the clientId found in their cookies.
     */
    this.enableReconnections = !!options.enableReconnections;

    /**
     * ### GameServer.antiSpoofing
     *
     * If TRUE, server asks clients to send along their sid in each msg
     */
    this.antiSpoofing = !!options.antiSpoofing;


}
1056160
function HybridConnectionsWebSocketServer(options, callback) {
  if (this instanceof HybridConnectionsWebSocketServer === false) {
    return new HybridConnectionsWebSocketServer(options, callback);
  }

  EventEmitter.call(this);

  options = Object.assign({
    server: null,
    token: null,
    id: null,
    verifyClient: null,
    handleProtocols: null,
    disableHixie: false,
    clientTracking: true,
    perMessageDeflate: true,
    maxPayload: 100 * 1024 * 1024,
    backlog: null // use default (511 as implemented in net.js)
  }, options);

  if (!isDefinedAndNonNull(options, 'server')) {
    throw new TypeError('\'server\' must be provided');
  }

  if (!isDefinedAndNonNull(options, 'token')) {
    throw new TypeError('A \'token\' string or function must be provided');
  }

  var self = this;

  this.listenUri = options.server;
  if (isDefinedAndNonNull(options, 'id')) {
    this.listenUri = listenUri + '&id=' + options.id;
  }

  this.closeRequested = false;
  this.options = options;
  this.path = options.path;
  this.clients = [];

  connectControlChannel(this);
}
199418
function _e2p(emitter, event, options) {
  let p = e2p(emitter, event, options);

  return p.then(() => {
    p.cancel();
    return p;
  })
  .catch(err => {
    p.cancel();
    throw err;
  });
}
258159
function Socket (options) {
    this.options = {
        port: 80
      , secure: false
      , document: 'document' in global ? document : false
      , resource: 'socket.io'
      , transports: io.transports
      , 'connect timeout': 10000
      , 'try multiple transports': true
      , 'reconnect': true
      , 'reconnection delay': 500
      , 'reconnection limit': Infinity
      , 'reopen delay': 3000
      , 'max reconnection attempts': 10
      , 'sync disconnect on unload': true
      , 'auto connect': true
      , 'flash policy port': 10843
    };

    io.util.merge(this.options, options);

    this.connected = false;
    this.open = false;
    this.connecting = false;
    this.reconnecting = false;
    this.namespaces = {};
    this.buffer = [];
    this.doBuffer = false;

    if (this.options['sync disconnect on unload'] &&
        (!this.isXDomain() || io.util.ua.hasCORS)) {
      var self = this;

      io.util.on(global, 'unload', function () {
        self.disconnectSync();
      }, false);
    }

    if (this.options['auto connect']) {
      this.connect();
    }
}
196367
function BufferLayer(socket) {
	//for ssl connection
	this.securePair = null;
	this.socket = socket;

	var self = this;
	// bind event
	this.socket.on('data', function(data) {
		try {
			self.recv(data);
		}
		catch(e) {
			self.socket.destroy();
			self.emit('error', e);
		}
	}).on('close', function() {
		self.emit('close');
	}).on('error', function (err) {
		self.emit('error', err);
	});

	//buffer data
	this.buffers = [];
	this.bufferLength = 0;
	//expected size
	this.expectedSize = 0;
}
589084
function handleConnection(self, options) {
	if (TRACE)	console.log('Connected to ' + options.host + ':' + options.port)
    	//self.socket = socket;
	self.emit("connect");
}
1308054
function CBSocketWrapper(config) {

    this.config = config;

    var self = this;

    // Connection status flag
    this.connected = false;

    // Socket Wrapper listeners
    this.on('connect', function() {
        self.connected = true;
        logger.info('Connected to Continuum Bridge', self.config.cbSocket);
    });
    this.on('connecting', function() {
        self.connected = false;
        logger.info('Connecting..');
    });
    this.on('error', function(error) {
        self.connected = false;
        logger.log('Error', error);
    });
    this.on('disconnect', function() {
        self.connected = false;
        logger.info('Disconnected from Continuum Bridge:', self.config.cbSocket);
    });
}
851019
function Connection(socket) {
  events.EventEmitter.call(this);

  // underlying socket
  this._socket = socket;

  // flag whether this connection is paused
  this._paused = false;

  // external or in-process client connection
  this._tcp = (this._socket instanceof Socket);

  // state information
  this._client = new Client(socket);

  this.data = this.data.bind(this);

  this._socket.once('close', this._close.bind(this));
  this._socket.on('data', this.data);

  // using a tcp socket connection
  if(this._tcp) {
    this.encoder = new Encoder({return_buffers: true})
    this.encoder.on('push', onPush.bind(this));
    this.encoder.pipe(this._socket);
    this.decoder = new Decoder({return_buffers: true});
    this.decoder.on('reply', this.decoded.bind(this));
    this.decoder.on('error', this.decoded.bind(this));

    function onSocketError(err) {
      log.warning(err.message);
    }

    this._socket.on('error', onSocketError.bind(this));
  }

  this.onWrite = this.onWrite.bind(this);
}
287985
function connect(dbUri, debugFlag, mongos) {
    var deferred = Q.defer();
    var opts = {
        server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
        replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } }
    };

    if (mongos) {
        opts.mongos = true;
    }

    mongoose.set('debug', debugFlag);

    // make sure we disconnect any other existing connections
    mongoose.disconnect(function () {
        mongoose.connect(dbUri, opts, function (err)  {
            err ? deferred.reject(err) : deferred.resolve();
        });
    });

    return deferred.promise;
}
1208684
function createHttpsServer(options, requestHandler, keys) {
  net
    .createServer(function(socket){
      socket.once('data', function(buffer){
        // Pause the socket
        socket.pause();

        // Determine if this is an HTTP(s) request
        var byte = buffer[0];
        var proxy;

        if (byte === 22)
          proxy = server.https;
        else if (32 < byte && byte < 127)
          proxy = server.http;

        if (proxy)
        {
          // Push the buffer back onto the front of the data stream
          socket.unshift(buffer);

          // Emit the socket to the HTTP(s) server
          proxy.emit('connection', socket);
        }

        // Resume the socket data stream
        socket.resume();
      });
    })
    .on('error', function(error){
      onError(error, options);
    })
    .listen(options.port, function(){
      onListen(this, options);
    });

  var server = {
    http: http.createServer(requestHandler),
    https: https.createServer(keys, requestHandler)
  };

  return server;
}
1053385
function ServerConnect (socket) {
        var simulator= this.simulator;

        socket.uid = "Socket://" + socket.remoteAddress +":" + socket.remotePort;
        socket.num = CLsockid ++;
        simulator.Debug(3, "New Client Id-%d Server=[%s] Client: [%s]",CLsockid,this.uid,socket.uid);

        // keep track of active clients inside TCP server
        ActiveClients[socket.num] = socket;

        // Normaly gpsd client does not talk to server
        socket.on("data", function(buffer) {
            simulator.Debug(1, "%s Data=[%s]", socket.uid, buffer);
            socket.write ('GeoGate Simulator Ignored:' + buffer );
        });

        // On error close socket
        socket.on('error', function (err) {
            simulator.Debug(1, "%s ERROR=[%s]", socket.uid, err);
            socket.end();
        });

        // Remove the device from daemon active device list and notify adapter for eventual cleanup
        socket.on('end', function () {
            simulator.Debug(3, "Tcp-Client Quit %s/%d uid=%s", socket.countid, simulator.clientCount, socket.uid);
            delete ActiveClients[socket.num];
        });
    }