Example #1
0
function ClientRequest(options, cb) {
  OutgoingMessage.call(this);

  if (typeof options === 'string') {
    options = url.parse(options);
    if (!options.hostname) {
      throw new errors.Error('ERR_INVALID_DOMAIN_NAME');
    }
  } else if (options && options[searchParamsSymbol] &&
             options[searchParamsSymbol][searchParamsSymbol]) {
    // url.URL instance
    options = urlToOptions(options);
  } else {
    options = util._extend({}, options);
  }

  var agent = options.agent;
  var defaultAgent = options._defaultAgent || Agent.globalAgent;
  if (agent === false) {
    agent = new defaultAgent.constructor();
  } else if (agent === null || agent === undefined) {
    if (typeof options.createConnection !== 'function') {
      agent = defaultAgent;
    }
    // Explicitly pass through this statement as agent will not be used
    // when createConnection is provided.
  } else if (typeof agent.addRequest !== 'function') {
    throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'Agent option',
                               ['Agent-like object', 'undefined', 'false']);
  }
  this.agent = agent;

  var protocol = options.protocol || defaultAgent.protocol;
  var expectedProtocol = defaultAgent.protocol;
  if (this.agent && this.agent.protocol)
    expectedProtocol = this.agent.protocol;

  var path;
  if (options.path) {
    path = '' + options.path;
    var invalidPath;
    if (path.length <= 39) { // Determined experimentally in V8 5.4
      invalidPath = isInvalidPath(path);
    } else {
      invalidPath = /[\u0000-\u0020]/.test(path);
    }
    if (invalidPath)
      throw new errors.TypeError('ERR_UNESCAPED_CHARACTERS', 'Request path');
  }

  if (protocol !== expectedProtocol) {
    throw new errors.Error('ERR_INVALID_PROTOCOL', protocol, expectedProtocol);
  }

  var defaultPort = options.defaultPort ||
                    this.agent && this.agent.defaultPort;

  var port = options.port = options.port || defaultPort || 80;
  var host = options.host = validateHost(options.hostname, 'hostname') ||
                            validateHost(options.host, 'host') || 'localhost';

  var setHost = (options.setHost === undefined);

  this.socketPath = options.socketPath;
  this.timeout = options.timeout;

  var method = options.method;
  var methodIsString = (typeof method === 'string');
  if (method != null && !methodIsString) {
    throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'method',
                               'string', method);
  }

  if (methodIsString && method) {
    if (!common._checkIsHttpToken(method)) {
      throw new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Method');
    }
    method = this.method = method.toUpperCase();
  } else {
    method = this.method = 'GET';
  }

  this.path = options.path || '/';
  if (cb) {
    this.once('response', cb);
  }

  var headersArray = Array.isArray(options.headers);
  if (!headersArray) {
    if (options.headers) {
      var keys = Object.keys(options.headers);
      for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        this.setHeader(key, options.headers[key]);
      }
    }
    if (host && !this.getHeader('host') && setHost) {
      var hostHeader = host;

      // For the Host header, ensure that IPv6 addresses are enclosed
      // in square brackets, as defined by URI formatting
      // https://tools.ietf.org/html/rfc3986#section-3.2.2
      var posColon = hostHeader.indexOf(':');
      if (posColon !== -1 &&
          hostHeader.indexOf(':', posColon + 1) !== -1 &&
          hostHeader.charCodeAt(0) !== 91/*'['*/) {
        hostHeader = `[${hostHeader}]`;
      }

      if (port && +port !== defaultPort) {
        hostHeader += ':' + port;
      }
      this.setHeader('Host', hostHeader);
    }
  }

  if (options.auth && !this.getHeader('Authorization')) {
    this.setHeader('Authorization', 'Basic ' +
                   Buffer.from(options.auth).toString('base64'));
  }

  if (method === 'GET' ||
      method === 'HEAD' ||
      method === 'DELETE' ||
      method === 'OPTIONS' ||
      method === 'CONNECT') {
    this.useChunkedEncodingByDefault = false;
  } else {
    this.useChunkedEncodingByDefault = true;
  }

  if (headersArray) {
    this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n',
                      options.headers);
  } else if (this.getHeader('expect')) {
    if (this._header) {
      throw new errors.Error('ERR_HTTP_HEADERS_SENT');
    }

    this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n',
                      this[outHeadersKey]);
  }

  this._ended = false;
  this.res = null;
  this.aborted = undefined;
  this.timeoutCb = null;
  this.upgradeOrConnect = false;
  this.parser = null;
  this.maxHeadersCount = null;

  var called = false;

  var oncreate = (err, socket) => {
    if (called)
      return;
    called = true;
    if (err) {
      process.nextTick(() => this.emit('error', err));
      return;
    }
    this.onSocket(socket);
    this._deferToConnect(null, null, () => this._flush());
  };

  var newSocket;
  if (this.socketPath) {
    this._last = true;
    this.shouldKeepAlive = false;
    var optionsPath = {
      path: this.socketPath,
      timeout: this.timeout,
      rejectUnauthorized: !!options.rejectUnauthorized
    };
    newSocket = this.agent.createConnection(optionsPath, oncreate);
    if (newSocket && !called) {
      called = true;
      this.onSocket(newSocket);
    } else {
      return;
    }
  } else if (this.agent) {
    // If there is an agent we should default to Connection:keep-alive,
    // but only if the Agent will actually reuse the connection!
    // If it's not a keepAlive agent, and the maxSockets==Infinity, then
    // there's never a case where this socket will actually be reused
    if (!this.agent.keepAlive && !Number.isFinite(this.agent.maxSockets)) {
      this._last = true;
      this.shouldKeepAlive = false;
    } else {
      this._last = false;
      this.shouldKeepAlive = true;
    }
    this.agent.addRequest(this, options);
  } else {
    // No agent, default to Connection:close.
    this._last = true;
    this.shouldKeepAlive = false;
    if (typeof options.createConnection === 'function') {
      newSocket = options.createConnection(options, oncreate);
      if (newSocket && !called) {
        called = true;
        this.onSocket(newSocket);
      } else {
        return;
      }
    } else {
      debug('CLIENT use net.createConnection', options);
      this.onSocket(net.createConnection(options));
    }
  }

  this._deferToConnect(null, null, () => this._flush());
}
Example #2
0
        function handleClientData(data) {
            // Don't want to include passwords in logs.
            conn.log(2, "Client command:  " + (data + '').trim().toString('utf-8').replace(/^PASS\s+.*/, 'PASS ***'));

            var command = parseFTPCommand(data);
            
            // we alredy have a connection
            if (conn.serverSocket !== null) {
                
                // intercept ACTIVE 
                if (command.cmd === "PORT") {
                    
                    conn.log(3, "Trying to intercept active mode: " + command.arg);
                    var m = command.arg.match(/(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d{1,3})/);
                    if (m) {
                        var hostname = m[1] + '.' + m[2] + '.' + m[3] + '.' + m[4];
                        var port = parseInt(m[5]) * 256 + parseInt(m[6]);
                        
                        forwardActiveConnection(hostname, port, function(localHost, localPort) {
                            var i1 = parseInt(localPort / 256);
                            var i2 = parseInt(localPort % 256);
                            conn.log(0, "PORT " + localHost.split(".").join(",") + "," + i1 + "," + i2);
                            conn.serverSocket.write("PORT " + localHost.split(".").join(",") + "," + i1 + "," + i2 + "\r\n");
                        });
                        return;
                    } else {
                        conn.log(1, "Unable to parse PORT address.");
                    }
                }

                // everything else
                conn.serverSocket.write(data);
                return;
            }


            if (command.cmd !== "USER") {
                clientSocket.write("202 Not supported\r\n");
                return;
            }

            conn.destination = self.getHostFromUsername(command.arg);
            if (conn.destination === null) {
                clientSocket.write("530 Invalid username\r\n");
                clientSocket.close();
                return;
            }

            conn.serverSocket = net.createConnection(conn.destination.port, conn.destination.hostname);
            conn.serverSocket.setEncoding('ascii');
            conn.serverSocket.setNoDelay();
            conn.serverSocket.on('connect', function() {
                conn.serverSocket.write(data);
            });
            conn.serverSocket.on('data', function(data) {
                data.split('\r\n').forEach(function(data) {
                    if ((data + '').trim()) {
                        handleServerResponse(data + '\r\n');
                    }
                });
            });
            conn.serverSocket.on('end', function() {
                clientSocket.end();
            });
            conn.serverSocket.on('error', function(err) {
                conn.log(0, "Error from server connection: " + err);
                clientSocket.end();
            });
        }
Example #3
0
Connection.prototype.open = function() {
  // Assign variable to point to local scope object
  var self = this;
  // Create the associated connection
  this.connection = net.createConnection(this.port, this.host);    
  // Set up the net client
  this.connection.setEncoding("binary");
  // Add connnect listener
  this.connection.addListener("connect", function() {
    this.setEncoding("binary");
    this.setTimeout(0);
    this.setNoDelay();
    self.emit("connect");
  });
  
  this.connection.addListener("error", function(err) {
    self.emit("error", err);
  });
  
  this.connection.addListener("timeout", function(err) {
    self.emit("timeout", err);
  });
  
  // Add a close listener
  this.connection.addListener("close", function() {
    self.emit("close");
  });
  
  // Listener for receive data
  this.receiveListener = function(result) {
    // Check if we have an unfinished message
    if(self.bytesRead > 0 && self.sizeOfMessage > 0) {
      // Calculate remaing bytes to fetch
      var remainingBytes = self.sizeOfMessage - self.bytesRead;
      // Check if we have multiple packet messages and save the pieces otherwise emit the message
      if(remainingBytes > result.length) {
        self.buffer = self.buffer + result; self.bytesRead = self.bytesRead + result.length;
      } else {
        // Cut off the remaining message
        self.buffer = self.buffer + result.substr(0, remainingBytes);
        // Emit the message
        self.emit("data", self.buffer);
        // Reset the variables
        self.buffer = ''; self.bytesRead = 0; self.sizeOfMessage = 0;
        // If message is longer than the current one, keep parsing
        if(remainingBytes < result.length) {
          self.receiveListener(result.substr(remainingBytes, (result.length - remainingBytes)));
        }
      }
    } else {
      if(self.stubBuffer.length > 0) {
        result = self.stubBuffer + result;
        self.stubBuffer = '';
      }

      if(result.length > 4) {
        var sizeOfMessage = BinaryParser.toInt(result.substr(0, 4));
        // We got a partial message, store the result and wait for more
        if(sizeOfMessage > result.length) {
          self.buffer = self.buffer + result; self.bytesRead = result.length; self.sizeOfMessage = sizeOfMessage;
        } else if(sizeOfMessage == result.length) {
          self.emit("data", result);
        } else if(sizeOfMessage < result.length) {
          self.emit("data", result.substr(0, sizeOfMessage));
          self.receiveListener(result.substr(sizeOfMessage, (result.length - sizeOfMessage)));
        }
      } else {
        self.stubBuffer = result;
      }
    }
  };

  // Add a receieved data connection
  this.connection.addListener("data", this.receiveListener);
};
'use strict';
var common = require('../common');
var net = require('net');
var assert = require('assert');


// Hopefully nothing is running on common.PORT
var c = net.createConnection(common.PORT);

c.on('connect', function() {
  console.error('connected?!');
  assert.ok(false);
});

c.on('error', common.mustCall(function(e) {
  console.error('couldn\'t connect.');
  assert.equal('ECONNREFUSED', e.code);
}));
Example #5
0
function ClientRequest(options, cb) {
  var self = this;
  OutgoingMessage.call(self);

  if (util.isString(options)) {
    options = url.parse(options);
  } else {
    options = util._extend({}, options);
  }

  var agent = options.agent;
  var defaultAgent = options._defaultAgent || Agent.globalAgent;
  if (agent === false) {
    agent = new defaultAgent.constructor();
  } else if (util.isNullOrUndefined(agent) && !options.createConnection) {
    agent = defaultAgent;
  }
  self.agent = agent;

  var protocol = options.protocol || defaultAgent.protocol;
  var expectedProtocol = defaultAgent.protocol;
  if (self.agent && self.agent.protocol)
    expectedProtocol = self.agent.protocol;

  if (options.path && / /.test(options.path)) {
    // The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
    // with an additional rule for ignoring percentage-escaped characters
    // but that's a) hard to capture in a regular expression that performs
    // well, and b) possibly too restrictive for real-world usage. That's
    // why it only scans for spaces because those are guaranteed to create
    // an invalid request.
    throw new TypeError('Request path contains unescaped characters.');
  } else if (protocol !== expectedProtocol) {
    throw new Error('Protocol:' + protocol + ' not supported.');
  }

  var defaultPort = options.defaultPort || self.agent && self.agent.defaultPort;

  var port = options.port = options.port || defaultPort || 80;
  var host = options.host = options.hostname || options.host || 'localhost';

  if (util.isUndefined(options.setHost)) {
    var setHost = true;
  }

  self.socketPath = options.socketPath;

  var method = self.method = (options.method || 'GET').toUpperCase();
  self.path = options.path || '/';
  if (cb) {
    self.once('response', cb);
  }

  if (!util.isArray(options.headers)) {
    if (options.headers) {
      var keys = Object.keys(options.headers);
      for (var i = 0, l = keys.length; i < l; i++) {
        var key = keys[i];
        self.setHeader(key, options.headers[key]);
      }
    }
    if (host && !this.getHeader('host') && setHost) {
      var hostHeader = host;
      if (port && +port !== defaultPort) {
        hostHeader += ':' + port;
      }
      this.setHeader('Host', hostHeader);
    }
  }

  if (options.auth && !this.getHeader('Authorization')) {
    //basic auth
    this.setHeader('Authorization', 'Basic ' +
                   new Buffer(options.auth).toString('base64'));
  }

  if (method === 'GET' ||
      method === 'HEAD' ||
      method === 'DELETE' ||
      method === 'CONNECT') {
    self.useChunkedEncodingByDefault = false;
  } else {
    self.useChunkedEncodingByDefault = true;
  }

  if (util.isArray(options.headers)) {
    self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n',
                      options.headers);
  } else if (self.getHeader('expect')) {
    self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n',
                      self._renderHeaders());
  }

  if (self.socketPath) {
    self._last = true;
    self.shouldKeepAlive = false;
    var conn = self.agent.createConnection({ path: self.socketPath });
    self.onSocket(conn);
  } else if (self.agent) {
    // If there is an agent we should default to Connection:keep-alive,
    // but only if the Agent will actually reuse the connection!
    // If it's not a keepAlive agent, and the maxSockets==Infinity, then
    // there's never a case where this socket will actually be reused
    if (!self.agent.keepAlive && !Number.isFinite(self.agent.maxSockets)) {
      self._last = true;
      self.shouldKeepAlive = false;
    } else {
      self._last = false;
      self.shouldKeepAlive = true;
    }
    self.agent.addRequest(self, options);
  } else {
    // No agent, default to Connection:close.
    self._last = true;
    self.shouldKeepAlive = false;
    if (options.createConnection) {
      var conn = options.createConnection(options);
    } else {
      debug('CLIENT use net.createConnection', options);
      var conn = net.createConnection(options);
    }
    self.onSocket(conn);
  }

  self._deferToConnect(null, null, function() {
    self._flush();
    self = null;
  });
}
Example #6
0
psrpc.ipcConnect = function(path) {
	var ipcClient = net.createConnection(path);
	this.initIPCClient(ipcClient);
	return ipcClient;
};
Example #7
0
    flushInt = setInterval(function () {
      var statString = '';
      var ts = Math.round(new Date().getTime() / 1000);
      var numStats = 0;
      var key;
      var statsCounts = {};

      for (key in counters) {
        var value = counters[key];
        var valuePerSecond = value / (flushInterval / 1000); // calculate "per second" rate

        statString += 'stats.'        + key + ' ' + valuePerSecond + ' ' + ts + "\n";
        statString += 'stats_counts.' + key + ' ' + value          + ' ' + ts + "\n";

        statsCounts[key] = value;

        counters[key] = 0;
        numStats += 1;
      }

      for (key in timers) {
        if (timers[key].length > 0) {
          var values = timers[key].sort(function (a,b) { return a-b; });
          var count = values.length;
          var min = values[0];
          var max = values[count - 1];

          var mean = min;
          var maxAtThreshold = max;

          var message = "";

          var key2;

          for (key2 in pctThreshold) {
            var pct = pctThreshold[key2];
            if (count > 1) {
              var thresholdIndex = Math.round(((100 - pct) / 100) * count);
              var numInThreshold = count - thresholdIndex;
              var pctValues = values.slice(0, numInThreshold);
              maxAtThreshold = pctValues[numInThreshold - 1];

              // average the remaining timings
              var sum = 0;
              for (var i = 0; i < numInThreshold; i++) {
                sum += pctValues[i];
              }

              mean = sum / numInThreshold;
            }

            var clean_pct = '' + pct;
            clean_pct.replace('.', '_');
            message += 'stats.timers.' + key + '.mean_'  + clean_pct + ' ' + mean           + ' ' + ts + "\n";
            message += 'stats.timers.' + key + '.upper_' + clean_pct + ' ' + maxAtThreshold + ' ' + ts + "\n";
          }

          timers[key] = [];

          message += 'stats.timers.' + key + '.upper ' + max   + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.lower ' + min   + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.count ' + count + ' ' + ts + "\n";
          statString += message;

          numStats += 1;
        }
      }

      for (key in gauges) {
        statString += 'stats.gauges.' + key + ' ' + gauges[key] + ' ' + ts + "\n";
        numStats += 1;
      }

      statString += 'statsd.numStats ' + numStats + ' ' + ts + "\n";

      if (config.graphiteHost) {
        try {
          var graphite = net.createConnection(config.graphitePort, config.graphiteHost);
          graphite.addListener('error', function(connectionException){
            if (config.debug) {
              util.log(connectionException);
            }
          });
          graphite.on('connect', function() {
            this.write(statString);
            this.end();
            stats['graphite']['last_flush'] = Math.round(new Date().getTime() / 1000);
          });
        } catch(e){
          if (config.debug) {
            util.log(e);
          }
          stats['graphite']['last_exception'] = Math.round(new Date().getTime() / 1000);
        }
      }

      if (config.leftronicAccessKey) {
        var streams = [];

        locations.forEach(function(keyFields) {
          var key = keyFields[0];
          var fields = keyFields[1];
          var location = fields[0];

          if (location.match(/\(.+?,.+?\)/)) {
            var match = location.match(/\(:?(.+?),(.+?)\)/);
            var latitude = parseFloat(match[1], 10);
            var longitude = parseFloat(match[2], 10);

            streams.push({
              streamName: key,
              point: {
                latitude: latitude,
                longitude: longitude
              }
            });
            aggregateLocation(streams, key, latitude, longitude);
          } else {
            memoizedGeolocation({
              location: location,
              fetch: function(loc, callback) {
                geocoder.geocode(loc, function (err, response) {
                  if (response.status === 'OK') {
                    var results = response.results;
                    var result = results[0];
                    if(result && result.geometry && result.geometry.location) {
                      callback(result.geometry.location);
                    }
                  } else {
                    if (config.debug) {
                      util.log('Geolocation failed:', err);
                    }
                  }
                });
              },
              callback: function(latLong) {
                var streams = [];
                streams.push({
                  streamName: key,
                  point: {
                    latitude: latLong.lat,
                    longitude: latLong.lng
                  }
                });
                aggregateLocation(streams, key, latLong.lat, latLong.lng);
                flushLeftronic(streams);
              }
            });
          }
        });

        for (key in statsCounts) {
          var value = statsCounts[key];
          var aggregations = config.aggregations;
          if (aggregations) {
            for (replacement in aggregations) {
              var matcher = aggregations[replacement];
              if (key.match(matcher)) {
                var newKey = key.replace(matcher, replacement);
                if (!statsCounts[newKey]) {
                  statsCounts[newKey] = 0;
                }
                statsCounts[newKey] += value;
              }
            }
          }
        }

        for (key in statsCounts) {
          var value = statsCounts[key];
          streams.push({
            streamName: key,
            point: value
          });
        }

        flushLeftronic(streams);
      }

      locations = [];

    }, flushInterval);
Example #8
0
process.title = "pongenv";

console.log('Whattt'); // I get a stupid error when using forever if I am not doing this.

var net = require('net'),
    data_center_server_port = 8124;

Message = require('./objects/messages.js');
Game = require('./objects/game_logic.js');
Ticker = require('./objects/ticker.js');

var socket = net.createConnection( data_center_server_port, "localhost", function() {
  socket.setEncoding('utf8');
  socket.write('{"name": "env123"}');
  Message.socket = socket;
  Game.initialize();
  Ticker.initialize();
});

socket.on( 'data', function(data) {
  Game.queueData.push( data );
  Ticker.queue.push( Game.solveData );
}).on('connect', function() {
  console.log('Connected to DataCenter!');
}).on('close', function() {
  console.log('Disconnected from DataCenter!');
});

Example #9
0
Message.prototype.send = function(smtp, options, fnCallback) {

    var self = this;
    smtp = smtp || null;

    if (typeof(options) === 'function') {
        var tmp = fnCallback;
        fnCallback = options;
        options = tmp;
    }

    self.callback = fnCallback;

    options = utils.copy(options, { secure: false, port: 25, user: '', password: '', timeout: 10000 });

    if (smtp === null || smtp === '') {

        smtp = getHostName(self.addressFrom.address);
        resolveMx(smtp, function(err, socket) {

            if (err) {

                mailer.emit('error', err, self);

                if (fnCallback)
                    fnCallback(err);

                return;
            }

            socket.on('error', function(err) {

                mailer.emit('error', err, self);

                if (fnCallback)
                    fnCallback(err);

            });

            self._send(socket, options);
        });

        return self;
    }

    var socket = options.secure ? tls.connect(options.port, smtp, function() { self._send(this, options); }) : net.createConnection(options.port, smtp);

    socket.on('error', function(err) {
        mailer.emit('error', err, self);
    });

    socket.on('clientError', function(err) {
        mailer.emit('error', err, self);
    });

    socket.on('connect', function() {
        self._send(socket, options);
    });

    return self;
};
Example #10
0
/**
 * manage event stream for a watch
 * @constructor Watch
 * @param {} host
 * @param {} port
 * @param {} id
 * @return 
 */
function Watch(host,port,id ) {
	//console.log("Watch:",host,port,id)
	this.isConnected=false;
	this.stream = null;
	this.en = {};// names to notifiers
	var self = this;

	/**
	 * start to watch for named event
	 * @method add
	 * @param {} name to watch
	 * @param {} callback
	 * @return 
	 */
	this.add=function(name, callback){
		this.en[name] = callback
	};

	/**
	 * stop watching
	 * @method remove
	 * @param {} name
	 * @return 
	 */
	this.remove=function(name){
		delete this.en[name]
	};
    
	/**
	 * close the socket
	 * @method close
	 * @return 
	 */
	this.close=function(){
		if(self.stream) {
			// console.log(self.tag+": event stream closing");
			self.stream.destroySoon();
			self.stream = null;
		}
	};
	
	/**
	 * Description
	 * @method parse
	 * @return 
	 */
	this.parse = function() { // intial \0 from event
		var r = self.bxp.popByte()
		if (r.data!="\0")
			throw "Bad event protocol";
		this.isConnected=true;
		self.parse = self.parseEvent;
		self.emit("connect", 1);		
	};

 
	/**
	 * watch response
	 * @method parseEvent
	 * @return 
	 */
	this.parseEvent = function() {
		var r = self.bxp.need([ "name", "msg" ], false)
		if (r) {
			var f = self.en[r.name];
			f(r.name, r.msg)
		}
	};

	var stream = net.createConnection(port, host);
	this.bxp=new parser2.parse(stream);
	
	stream.on("data", function(reply) {
		if (exports.debug_mode) {
			console.log("event<<");
			console.dir(reply);
		}
		;
		self.parse()
	});

	stream.on("connect", function() {
		if (exports.debug_mode) {
			console.log("event connect")
		};
		stream.write(id + "\0");
	});
	
	stream.on("error", function() {
		console.log("event error")
	})
	this.stream = stream;
};
Example #11
0
Tessel.Port = function(name, socketPath, board) {
  var port = this;

  this.name = name;
  this.board = board;
  // Connection to the SPI daemon
  this.sock = net.createConnection({
    path: socketPath
  }, function(e) {
    if (e) {
      throw e;
    }
  });

  // Number of tasks occupying the socket
  this._pendingTasks = 0;

  // Unreference this socket so that the script will exit
  // if nothing else is waiting in the event queue.
  this.unref();

  this.sock.on('error', function(e) {
    console.log('we had a socket err', e);
  });

  this.sock.on('end', function() {
    console.log('the other socket end closed!');
  });

  this.sock.on('close', function() {
    throw new Error('Port socket closed');
  });

  var replyBuf = new Buffer(0);

  this.sock.on('readable', function() {
    var queued;
    // This value can potentially be `null`.
    var available = new Buffer(this.sock.read() || 0);

    // Copy incoming data into the reply buffer
    replyBuf = Buffer.concat([replyBuf, available]);

    // While we still have data to process in the buffer
    while (replyBuf.length !== 0) {
      // Grab the next byte
      var byte = replyBuf[0];
      // If the next byte equals the marker for a uart incoming
      if (byte === REPLY.ASYNC_UART_RX) {
        // Get the next byte which is the number of bytes
        var rxNum = replyBuf[1];
        // As long as the number of butes of rx buffer exists
        // and we have at least the number of bytes needed for a uart rx packet
        if (rxNum !== undefined && replyBuf.length >= 2 + rxNum) {
          // Read the incoming data
          var rxData = replyBuf.slice(2, 2 + rxNum);
          // Cut those bytes out of the reply buf packet so we don't
          // process them again
          replyBuf = replyBuf.slice(2 + rxNum);

          // If a uart port was instantiated
          if (this._uart) {
            // Push this data into the buffer
            this._uart.push(rxData.toString());
          }
          // Something went wrong and the packet is malformed
        } else {
          break;
        }
        // This is some other async transaction
      } else if (byte >= REPLY.MIN_ASYNC) {
        // If this is a pin change
        if (byte >= REPLY.ASYNC_PIN_CHANGE_N && byte < REPLY.ASYNC_PIN_CHANGE_N + 16) {
          // Pull out the pin number (requires clearing the value bit)
          var pin = this.pin[(byte - REPLY.ASYNC_PIN_CHANGE_N) & ~(1 << 3)];
          // Get the mode change
          var mode = pin.interruptMode;

          // If this was a one-time mode
          if (mode === 'low' || mode === 'high') {
            // Reset the pin interrupt state (prevent constant interrupts)
            pin.interruptMode = null;
            // Decrement the number of tasks waiting on the socket
            this.unref();
          }

          // Emit the change
          if (mode === 'change') {
            // "change" is otherwise ambiguous.
            pin.emit('change', (byte >> 3) & 1);
          } else {
            // high, low, rise & fall are _not_ ambiguous
            pin.emit(mode);
          }
        } else {
          // Some other async event
          this.emit('async-event', byte);
        }

        // Cut this byte off of the reply buffer
        replyBuf = replyBuf.slice(1);
      } else {
        // If there are no commands awaiting a response
        if (this.replyQueue.length === 0) {
          // Throw an error... something went wrong
          throw new Error('Received unexpected response with no commands pending: ' + byte);
        }

        // Get the size if the incoming packet
        var size = this.replyQueue[0].size;

        // If we have reply data
        if (byte === REPLY.DATA) {
          // Ensure that the packet size agrees
          if (!size) {
            throw new Error('Received unexpected data packet');
          }

          // The number of data bytes expected have been received.
          if (replyBuf.length >= 1 + size) {
            // Extract the data
            var data = replyBuf.slice(1, 1 + size);
            // Slice this data off of the buffer
            replyBuf = replyBuf.slice(1 + size);
            // Get the  queued command
            queued = this.dequeue();

            // If there is a callback for th ecommand
            if (queued.callback) {
              // Return the data in the callback
              queued.callback.call(this, null, queued.size ? data : byte);
            }
          } else {
            // The buffer does not have the correct number of
            // date bytes to fulfill the requirements of the
            // reply queue's next registered handler.
            break;
          }
          // If it's just one byte being returned
        } else if (byte === REPLY.HIGH || byte === REPLY.LOW) {
          // Slice it off
          replyBuf = replyBuf.slice(1);
          // Get the callback in the queue
          queued = this.dequeue();

          // If a callback was provided
          if (queued.callback) {
            // Return the byte in the callback
            queued.callback.call(this, null, byte);
          }
        }
      }
    }
  }.bind(this));

  // Active peripheral: 'none', 'i2c', 'spi', 'uart'
  this.mode = 'none';

  // Array of {size, callback} used to dispatch replies
  this.replyQueue = [];

  this.pin = [];
  for (var i = 0; i < 8; i++) {
    var interruptSupported = Tessel.Pin.interruptCapablePins.indexOf(i) !== -1;
    var adcSupported = (name === 'B' || Tessel.Pin.adcCapablePins.indexOf(i) !== -1);
    var pullSupported = Tessel.Pin.pullCapablePins.indexOf(i) !== -1;
    var pwmSupported = Tessel.Pin.pwmCapablePins.indexOf(i) !== -1;
    this.pin.push(new Tessel.Pin(i, this, interruptSupported, adcSupported, pullSupported, pwmSupported));
  }

  // Deprecated properties for Tessel 1 backwards compatibility:
  this.pin.G1 = this.pin.g1 = this.pin[5];
  this.pin.G2 = this.pin.g2 = this.pin[6];
  this.pin.G3 = this.pin.g3 = this.pin[7];
  this.digital = [this.pin[5], this.pin[6], this.pin[7]];

  this.pwm = [this.pin[5], this.pin[6]];

  this.I2C = function I2CInit(address, mode) {
    return new Tessel.I2C({
      addr: address,
      mode: mode,
      port: port
    });
  };

  this.I2C.enabled = false;

  this.SPI = function SPIInit(format) {
    if (port._spi) {
      port._spi.disable();
    }

    port._spi = new Tessel.SPI(format === null ? {} : format, port);

    return port._spi;
  };

  this.UART = function UARTInit(format) {
    if (port._uart) {
      port._uart.disable();
    }

    port._uart = new Tessel.UART(port, format || {});
    // Grab a reference to this socket so it doesn't close
    // if we're waiting for UART data
    port.ref();

    return port._uart;
  };
};
Example #12
0
JobServer.prototype.connect = function (callback) {
    var self = this;
    var eventNames;

    if (!(callback instanceof Function)) { return new Error('invalid callback (not a function)'); }

    if (this.connected) {
        callback();
    } else {
        this.socket = net.createConnection(this.port, this.host);

        // fallback event registration, only for debugging purposes
        eventNames = [ 'lookup', 'timeout', 'drain' ];
        eventNames.forEach(function (name) {
            self.socket.on(name, function() {
                JobServer.logger.log('warn', 'unhandled event, name=%s', name);
            });
        });

        // emitted when a socket connection is successfully established
        this.socket.on('connect', function () {
            self.socket.setKeepAlive(true);
            self.connected = true;
            self.wrongDisconnectAt = 0;
            self.failedConnectionCount = 0
            self.emit('ConnectInternal140319214558');
            self.clientOrWorker.emit('socketConnect', self.getUid()); // trigger event
            JobServer.logger.log('debug', 'connection established, uid=%s', self.getUid());
            callback();
        });

        // emitted when an error occurs
        this.socket.on('error', function (err) {
            JobServer.logger.log('error', 'socket error:', err);
            // ensures that no more I/O activity happens on this socket
            self.socket.destroy();

            // inform load balancer that this server is invalid
            if (self.clientOrWorker._type === 'Client') {
                self.clientOrWorker.loadBalancer.badOne(self.clientOrWorker._getJobServerIndexByUid(self.getUid()));
            }

            // ECONNREFUSED, EPIPE, ...
            self.clientOrWorker.emit('socketError', self.getUid(), err); // trigger event
            self.disconnect(err);

            callback(err);
        });

        this.socket.on('data', function (chunk) {
// BF#6 var orig = null;
// if (chunk.length > 500) {
//     JobServer.logger.log('verbose', '=======================================');
//     orig = chunk;
//     chunk = chunk.slice(0, 500);
// }
            if (JobServer.logger.isLevelEnabled('verbose')) {
                JobServer.logger.log('verbose', 'received packet, len=%d', chunk.length);
                JobServer.logger.log('verbose', 'received packet: %s', common.bufferAsHex(chunk));
            }
            self._processData(chunk);
// BF#6 if (orig != null) {
//     self.socket.emit('data', orig.slice(500));
// }
        });

        // emitted once the socket is fully closed
        this.socket.on('close', function (had_error) {
            if (had_error) { // if the socket was closed due to a transmission error
                JobServer.logger.log('warn', 'connection closed due to an transmission error, uid=%s', self.getUid());
                // inform load balancer that this server is invalid
                if (self.clientOrWorker._type === 'Client') {
                    self.clientOrWorker.loadBalancer.badOne(self.clientOrWorker._getJobServerIndexByUid(self.getUid()));
                }
                self.disconnect(true); // true => simulates an error to set `wrongDisconnectAt` attribute
            }
        });

        // emitted when the other end of the socket sends a FIN packet (termination of other end)
        this.socket.on('end', function (err) {
            JobServer.logger.log('warn', 'connection terminated, uid=%s', self.getUid());
            // inform load balancer that this server is invalid
            if (self.clientOrWorker._type === 'Client') {
                self.clientOrWorker.loadBalancer.badOne(self.clientOrWorker._getJobServerIndexByUid(self.getUid()));
            }
            self.disconnect(err);
        });
    }

    return this.socket;
};
Example #13
0
    sendRequest: function (port, buf, callback) {
        var that = this;
        var response = new Buffer(0);
        var chunk = 0;
        var length;

        var client = net.createConnection(port, this.options.ccuIp,
            function() { //'connect' listener
               //logger.verbose('sending to '+that.options.ccuIp+':'+port);
               //logger.silly(buf);
                client.write(buf.toString());
            });

        client.on('error', function (e) {
            logger.error("binrpc        "+JSON.stringify(e));
        })

        client.on('data', function(data) {
            logger.silly("binrpc    --> receiving chunk "+chunk+" data.length="+data.length);

            if (chunk == 0) {
                var vars = binary.parse(data)
                    .buffer("head", 3)
                    .word8("msgType")
                    .word32bu("msgSize")
                    .vars;
                length = vars.msgSize;
                response = data;
            } else {
                response = Buffer.concat([response, data]);

            }
            chunk = chunk + 1;

           //debug(0,"response.length="+response.length);

            if (response.length >= (length + 8)) {
                var name = client.remoteAddress+":"+client.remotePort;
                client.end();
                var res = that.parseResponse(response, name);
                logger.verbose('binrpc    --> '+name+ " closing connection");
                if (callback) {
                    callback(res, name);
                }
                response = new Buffer(0);
                chunk = 0;
            }

            /*logger.info("##############################\n\n\n");
           logger.verbose("receiving: ");
           logger.verbose(data.length);
            var res = this.parseResponse(data);
            //debug(0,res);
            client.end();
            if (callback) { callback(res); }*/

        });

        client.on('end', function() {


        });
    },
Connection.prototype.createSocket = function () {
  var socket = net.createConnection(this.port, this.host);
  socket.setNoDelay(true);
  socket.setMaxListeners(100);
  return socket;
};
const net = require("net");
const readline = require("readline");

const PORT = 8080;
const HOST = "127.0.0.1";

const r1 = readline.createInterface({
      input: process.stdin,
      output: process.stdout
});

const socket = net.createConnection({port: PORT, host: HOST});

socket.on("data", function(data){
  if (data.toString() == "too small")
  {
    console.log("This is too small");
    r1.question("Please give me a number: ", function(numberString){
      socket.write(numberString);
    });
  }
  else if (data.toString() == "too large") {
    console.log("This is too large");
    r1.question("Please give me a number: ", function(numberString){
      socket.write(numberString);
    });
  }
  else if (data.toString() == "correct")
  {
    console.log("This is correct");
    process.exit(0);
    if (!typeSet) { continue; }
    for (var t=0;t < typeSet.length;t++) {
      var name = typeSet[1];
      typesObj[name] = new Array();
      var eachType = typeSet[2].split(", ")
      for (var u=0; u < eachType.length; u++){
        var theName = eachType[u].split(":")[0];
        typesObj[name].push(theName);
      }
    }
  }
}


try {
  var graphite_connection = net.createConnection(2003, host=process.argv[2]);
} catch (error) {
  throw error;
}
graphite_connection.on("close", function() {
  throw new Error("Connection closed");
});
graphite_connection.on("error", function() {
  throw new Error("Connection error");
});

var fragment = ""

var request_handler = function(request, response) {
  var putval_re = /^PUTVAL ([^ ]+)(?: ([^ ]+=[^ ]+)?) ([0-9.]+)(:.*)/;
  request.addListener("data", function(chunk) {
Example #17
0
var net = require('net');
var buffer = require('buffy');

var socket = net.createConnection(5555, '192.168.1.1');
var fs = require('fs');

var file = fs.createWriteStream('pave.bin');
socket.pipe(file);

var size = 0;
socket.on('data', function(buffer) {
  size += buffer.length;
  console.log(size);

  if (size >= 1024 * 1024) {
    socket.end();
  }
});
Example #18
0
module.exports = function (socketPath, _callback) {
    var socket = net.createConnection(socketPath),
        response_obj = {};

    // because there's a possibility of multiple calls from the events
    // ensure it can't trigger a double-callback
    function callback (err, data) {
        if (_callback) {
            _callback(err, data);
            _callback = null;
        }
    }

    function collector (err, data) {
        if (err) {
            return callback(err);
        }

        var statuses = JSON.parse(data.toString()),
            hasHealthInfo = false;
        response_obj.hostname = os.hostname();
        response_obj.node_version = process.version;
        response_obj.os_type = os.type();
        response_obj.os_release = os.release();
        response_obj.currentTime = Date.now();
        if (process.clusterStartTime) {
            //Show Restart Time only if Process has the field clusterStartTime
            //this attribute should be set by the cluster master process
            response_obj.cluster_start_time = process.clusterStartTime.getTime();
            response_obj.cluster_uptime = Math.round((new Date().getTime() - process.clusterStartTime.getTime()) / 1000);
        }
        response_obj.total_memory = os.totalmem();
        response_obj.free_memory = os.freemem();
        response_obj.os_loadavg = os.loadavg();
        response_obj.worker = [];

        response_obj.total_requests = 0;
        response_obj.total_kbs_transferred = 0;
        response_obj.total_kbs_out = 0;
        response_obj.total_rps = 0;
        Object.keys(statuses).forEach(function(pid) {
            var worker_json = {
                "pid" : pid,
                "cpu" : statuses[pid].curr.cpu,
                "mem" : statuses[pid].curr.mem,
                "cpu_per_req" : statuses[pid].curr.cpuperreq,
                "jiffy_per_req" : statuses[pid].curr.jiffyperreq,
                "rps" : statuses[pid].curr.rps,
                "events" : statuses[pid].curr.events,
                "open_conns" : statuses[pid].curr.oconns,
                "open_requests" : statuses[pid].curr.oreqs,
                "total_requests" : statuses[pid].curr.reqstotal,
                "kbs_out" : statuses[pid].curr.kbs_out,
                "kbs_transferred" : statuses[pid].curr.kb_trans,
                "start_time" : statuses[pid].curr.utcstart * 1000, //convert sec in millis
                "start_time_format" : moment.unix(statuses[pid].curr.utcstart).fromNow()
            };
            if (statuses[pid].curr.health_status_timestamp) {
                //convert sec in millis
                worker_json.health_status_timestamp = statuses[pid].curr.health_status_timestamp * 1000;
                worker_json.health_time_format = moment.unix(statuses[pid].curr.health_status_timestamp).fromNow();
                worker_json.health_is_down = statuses[pid].curr.health_is_down;
                worker_json.health_status_code = statuses[pid].curr.health_status_code;
                hasHealthInfo = true;
                if(!response_obj.latest_health_timestamp ||
                   statuses[pid].curr.health_status_timestamp > response_obj.latest_health_timestamp) {
                    response_obj.latest_health_timestamp = statuses[pid].curr.health_status_timestamp;
                    response_obj.latest_health_is_down = worker_json.health_is_down;
                }
            }
            response_obj.worker.push(worker_json);
            response_obj.total_requests = response_obj.total_requests + statuses[pid].curr.reqstotal;
            response_obj.total_kbs_transferred = response_obj.total_kbs_transferred + statuses[pid].curr.kb_trans;
            response_obj.total_kbs_out = response_obj.total_kbs_out + statuses[pid].curr.kbs_out;
            response_obj.total_rps = response_obj.total_rps + statuses[pid].curr.rps;
        });
        response_obj.has_health_info = hasHealthInfo;
        return callback(null, response_obj);
    }

    socket.pipe(bl(collector));
    socket.on("close", function (error) {
        if (error) {
            callback(error);
        }
    });
};
global.sandbox.forkHandler = function(request, spawnRequestStream) {
	// need a more persistent sandbox for some of the
	// convenience functions
	var __spawnSandbox = {
		log : global.sandbox.log,
		sendMessage : global.sandbox.sendMessage
	};

	//__spawnSandbox.log("Fork setup code...");

	global.sandbox.spawnServer.removeAllListeners();
	global.sandbox.spawnServer.close();
	spawnRequestStream.removeAllListeners();
	spawnRequestStream.destroy();
	spawnRequestStream = null;
	process.env.NODE_PRETTY_ARGS = global.sandbox.prettyArgs;
	request.args.unshift(process.argv[0], request.script);

	//console.log("delete global.sandbox returns: " + delete global.sandbox);

	__spawnSandbox.log(process.pid + " successfully forked");
	{
		var isURL;
		process.argv = process.ARGV = request.args;

		// logic from node.js.  argv[0] doesn't need to be adjusted
		// since it's already adjusted when the fork daemon starts up
		if (process.argv[1].charAt(0) != "/" && !(isURL = process.argv[1].startsWith("http://"))) {
			process.argv[1] = path.join(cwd, process.argv[1]);
		}

		__spawnSandbox.originalScript = request.script;

		//require(process.argv[1]);
		//sandbox.endsWith = function(str, prefix) {
		//	if (str.length < prefix.length)
		//		return false;
		//	if (str.length == prefix.length)
		//		return str == prefix;
		//	for (var i = str.length - 1, j = prefix.length - 1; j >= 0; j--, i--) {
		//		if (str[i] != prefix[j--])
		//			return false;
		//	}
		//	return true;
		//}
		//if (isURL === undefined) {isURL = sandbox.startsWith(process.argv[1], "http://")}
		//if (!isURL && !sandbox.endsWith(process.argv[1], ".js")) {
		//	process.argv[1] = process.argv[1] + ".js";
		//}

		// NOTE: this will block the script from exiting even if it can
		// the fork server has to close stdin (which happens automatically
		// when the remote side goes away).
		var stdin = process.openStdin();
		stdin.on('error', function(e) {
			// EAGAIN is a weird error, but we don't care about it
		});
	}
	//__spawnSandbox.log("Running user script");
	// clear references to variables that aren't necessary in the child
	request = undefined;
        Module.runMain();
	if (parseInt(process.env.NODE_PRETTY_ARGS)) {
		process.argv.splice(0, 1);
		process.argv[0] = __spawnSandbox.originalScript;
		process.setArgs(process.argv);

		var friendlyName = process.basename(__spawnSandbox.originalScript);
		process.setName({name: process.argv[0], shortname: process.basename(__spawnSandbox.originalScript)});
	}

	//__spawnSandbox.log("Notifying child is ready");

	{
		var notifyReady = process.forked_script_notifier = net.createConnection(9000);
		notifyReady.on('connect', function() {
			//__spawnSandbox.log(process.argv[1] + " startup finished - notifying fork daemon");
			__spawnSandbox.sendMessage(this, {pid : process.pid, child_ready: true});
			this.end();
			this.removeAllListeners();
		});
		notifyReady.on('error', function(e) {
			__spawnSandbox.log("Trouble notifying fork daemon of startup - dying:\n" + e);
			process.exit(-1);
		});
		notifyReady.on('end', function() {
			this.destroy();
		});
	}
};
Example #20
0
dnode.prototype.connect = function () {
    var params = protocol.parseArgs(arguments);
    var stream = params.stream;
    var client = null;
    var self   = this;  
    
    if (params.port) {
        params.host = params.host || '127.0.0.1';
        if (params.key) {
            var options = { key: params.key, cert: params.cert };
            stream = tls.connect(params.port, params.host, options, function() {
                attachDnode();
            });
        }
        else {
            stream = net.createConnection(params.port, params.host);
            stream.on('connect', function() {
                attachDnode();
            });
        }
    }
    else if (params.path) {
        stream = net.createConnection(params.path);
        stream.on('connect', function() {
            attachDnode();
        });
    }
    else {
      attachDnode();
    } 
    
    stream.remoteAddress = params.host;
    stream.remotePort = params.port;
    
    var args = arguments; 
    
    if (params.reconnect) {
        stream.on('error', (function (err) {
            if (err.code === 'ECONNREFUSED') {
                if (client) client.emit('refused');
                
                setTimeout((function () {
                    if (client) client.emit('reconnect');
                    dnode.prototype.connect.apply(this, args);
                }).bind(this), params.reconnect);
            }
            else if (client) client.emit('error', err)
            else this.emit('error', err)
        }).bind(this));
        
        stream.once('end', (function () {
            if (!params.reconnect) return;
            client.emit('drop');
            
            setTimeout((function () {
                if (!params.reconnect) return;
                client.emit('reconnect');
                dnode.prototype.connect.apply(this, args);
            }).bind(this), params.reconnect);
        }).bind(this));
    }
    else {
        stream.on('error', (function (err) {
            if (client) client.emit('error', err)
            else this.emit('error', err)
        }).bind(this));
    }
    
    function attachDnode() {
      
        client = createClient(self.proto, stream);
        
        client.end = function () {
            if (params.reconnect) params.reconnect = 0;
            stream.end();
        };
        
        self.stack.forEach(function (middleware) {
            middleware.call(client.instance, client.remote, client);
        });
        
        if (params.block) {
            client.on('remote', function () {
                params.block.call(client.instance, client.remote, client);
            });
        }
        
        process.nextTick(function () {
            if (client.listeners('error').length === 0) {
                // default error handler to keep everything from crashing
                client.on('error', function (err) {
                    console.error(err && err.stack || err);
                })
            }
        });
        
        client.start();
    };
    
    return this;
};
Example #21
0
Client.prototype.connect = function (retryCount, callback) {
    // Organize args
    if (_.isFunction(retryCount)) {
        callback = retryCount;
        retryCount = undefined;
    }

    // Set default retry count
    retryCount = retryCount || 0;

    // Register call back with 'registered' event
    if (_.isFunction(callback)) this.once('registered', callback);

    // There is no place like home
    let self = this;

    // Create empty object to hold channel info in
    self.chans = {};

    // Build socket opts
    let connectionOpts = {
        // host: self.opt.server,
        // port: self.opt.port,
        family: self.opt.family
    };

    if (self.opt.socket === true) connectionOpts.path = self.opt.server;
    else {
        connectionOpts.host = self.opt.server;
        connectionOpts.port = self.opt.port;
    }

    // local address to bind to
    if (self.opt.jslocalAddress) connectionOpts.localAddress = self.opt.localAddress;

    // local port to bind to
    if (self.opt.localPort) connectionOpts.localPort = self.opt.localPort;


    if (self.opt.bustRfc3484) {
        // RFC 3484 attempts to sort address results by "locallity", taking
        //   into consideration the length of the common prefix between the
        //   candidate local source address and the destination. In practice
        //   this always sorts one or two servers ahead of all the rest, which
        //   isn't what we want for proper load balancing. With this option set
        //   we'll randomise the list of all results so that we can spread load
        //   between all the servers.
        connectionOpts.lookup = function (hostname, options, callback) {
            const optionsWithAll = Object.assign({
                all: true,
                verbatim: true,
                hints: dns.ADDRCONFIG | dns.V4MAPPED,
            }, options);
            dns.lookup(hostname, optionsWithAll, (err, addresses) => {
                if (err) {
                    if (options.all) return callback(err, addresses);
                    return callback(err, null, null);
                }

                if (options.all) {
                    const shuffled = [];
                    while (addresses.length) {
                        const i = randomInt(addresses.length);
                        shuffled.push(addresses.splice(i, 1)[0]);
                    }
                    callback(err, shuffled);
                } else {
                    const chosen = addresses[randomInt(addresses.length)];
                    callback(err, chosen.address, chosen.family);
                }
            });
        };
    }

    // try to connect to the server
    if (self.opt.secure) {
        connectionOpts.rejectUnauthorized = !self.opt.selfSigned;

        if (_.isObject(self.opt.secure)) {
            // copy "secure" opts to options passed to connect()
            for (let f in self.opt.secure) {
                connectionOpts[f] = self.opt.secure[f];
            }
        }

        self.conn = tls.connect(connectionOpts, function () {
            // callback called only after successful socket connection
            self.conn.connected = true;
            if (self.conn.authorized ||
                (self.opt.selfSigned &&
                    (self.conn.authorizationError === 'DEPTH_ZERO_SELF_SIGNED_CERT' ||
                        self.conn.authorizationError === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' ||
                        self.conn.authorizationError === 'SELF_SIGNED_CERT_IN_CHAIN')) ||
                (self.opt.certExpired &&
                    self.conn.authorizationError === 'CERT_HAS_EXPIRED')) {
                // authorization successful

                if (!self.opt.encoding) self.conn.setEncoding('utf-8');

                if (self.opt.certExpired &&
                    self.conn.authorizationError === 'CERT_HAS_EXPIRED') {
                    console.log('Connecting to server with expired certificate');
                }

                self._connectionHandler();
            } else {
                // authorization failed
                console.log(self.conn.authorizationError);
            }
        });
    } else self.conn = net.createConnection(connectionOpts, self._connectionHandler.bind(self));

    self.conn.requestedDisconnect = false;

    self.conn.setTimeout(0);

    // Each connection gets its own CyclingPingTimer. The connection forwards the timer's 'timeout' and 'wantPing' events
    // to the client object via calling the connectionTimedOut() and connectionWantsPing() functions.
    //
    // Since the client's "current connection" value changes over time because of retry functionality,
    // the client should ignore timeout/wantPing events that come from old connections.
    self.conn.cyclingPingTimer = new CyclingPingTimer(self);
    (function (conn) {
        conn.cyclingPingTimer.on('pingTimeout', function () {
            self.connectionTimedOut(conn);
        });
        conn.cyclingPingTimer.on('wantPing', function () {
            self.connectionWantsPing(conn);
        });
    }(self.conn));

    if (!self.opt.encoding) self.conn.setEncoding('utf8');

    let buffer = Buffer.from('');

    function handleData(chunk) {

        if (self.conn.cyclingPingTimer && self.conn.cyclingPingTimer.notifyOfActivity) self.conn.cyclingPingTimer.notifyOfActivity();

        buffer = _.isString(chunk) ? buffer + chunk : Buffer.concat([buffer, chunk]);

        // Do conversion
        const converted = self.convertEncoding(buffer);

        // Verify we are getting a string back
        if (!_.isString(converted)) {
            console.log('Something has gone wrong in the string encoding function');
            return;
        }

        // Split lines
        let lines = converted.split(lineDelimiter);

        // if buffer is not ended with \r\n, there's more chunks.
        if (lines.pop()) return;

        // Re-initialize the buffer.
        buffer = Buffer.from('');

        for (const line of _.filter(lines, line => line.length)) {
            try {
                self.emit('raw', parseMessage(line, self.opt.stripColors));
            } catch (err) {
                if (!self.conn.requestedDisconnect) throw err;
            }
        }
    }

    self.conn.addListener('data', handleData);

    self.conn.addListener('end', function () {
        if (self.opt.debug) console.log('Connection got "end" event');
        // Emit Connection End event
        self.emit('connectionEnd');
    });

    self.conn.addListener('close', function () {
        if (self.opt.debug) console.log('Connection got "close" event');

        if (self.conn && self.conn.requestedDisconnect) return;

        if (self.opt.debug) console.log('Disconnected: reconnecting');

        if (self.opt.retryCount !== null && retryCount >= self.opt.retryCount) {
            if (self.opt.debug) console.log('Maximum retry count (' + self.opt.retryCount + ') reached. Aborting');
            self.emit('abort', self.opt.retryCount);
            return;
        }

        if (self.opt.debug) console.log('Waiting ' + self.opt.retryDelay + 'ms before retrying');

        setTimeout(function () {
            self.connect(retryCount + 1);
        }, self.opt.retryDelay);
    });

    self.conn.addListener('error', function (exception) {
        self.emit('netError', exception);
        if (self.opt.debug) console.log('Network error: ' + exception);
    });
};
Example #22
0
 }).listen(0, function () {
   net.createConnection({port:this.address().port}, function () {
       this.end(Buffer([0x00, 0xFF, 0x00]));
   });
 });
Example #23
0
function ClientRequest(options, cb) {
  var self = this;
  OutgoingMessage.call(self);

  self.agent = options.agent === undefined ? globalAgent : options.agent;

  var defaultPort = options.defaultPort || 80;

  var port = options.port || defaultPort;
  var host = options.hostname || options.host || 'localhost';

  if (options.setHost === undefined) {
    var setHost = true;
  }

  self.socketPath = options.socketPath;

  var method = self.method = (options.method || 'GET').toUpperCase();
  self.path = options.path || '/';
  if (cb) {
    self.once('response', cb);
  }

  if (!Array.isArray(options.headers)) {
    if (options.headers) {
      var keys = Object.keys(options.headers);
      for (var i = 0, l = keys.length; i < l; i++) {
        var key = keys[i];
        self.setHeader(key, options.headers[key]);
      }
    }
    if (host && !this.getHeader('host') && setHost) {
      var hostHeader = host;
      if (port && +port !== defaultPort) {
        hostHeader += ':' + port;
      }
      this.setHeader('Host', hostHeader);
    }
  }

  if (options.auth && !this.getHeader('Authorization')) {
    //basic auth
    this.setHeader('Authorization', 'Basic ' +
                   new Buffer(options.auth).toString('base64'));
  }

  if (method === 'GET' || method === 'HEAD' || method === 'CONNECT') {
    self.useChunkedEncodingByDefault = false;
  } else {
    self.useChunkedEncodingByDefault = true;
  }

  if (Array.isArray(options.headers)) {
    self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n',
                      options.headers);
  } else if (self.getHeader('expect')) {
    self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n',
                      self._renderHeaders());
  }
  if (self.socketPath) {
    self._last = true;
    self.shouldKeepAlive = false;
    if (options.createConnection) {
      self.onSocket(options.createConnection(self.socketPath));
    } else {
      self.onSocket(net.createConnection(self.socketPath));
    }
  } else if (self.agent) {
    // If there is an agent we should default to Connection:keep-alive.
    self._last = false;
    self.shouldKeepAlive = true;
    self.agent.addRequest(self, host, port, options.localAddress);
  } else {
    // No agent, default to Connection:close.
    self._last = true;
    self.shouldKeepAlive = false;
    if (options.createConnection) {
      options.port = port;
      options.host = host;
      var conn = options.createConnection(options);
    } else {
      var conn = net.createConnection({
        port: port,
        host: host,
        localAddress: options.localAddress
      });
    }
    self.onSocket(conn);
  }

  self._deferToConnect(null, null, function() {
    self._flush();
    self = null;
  });

}
Example #24
0
RPC.TCP.ConnectBack.prototype.start = function(callback) {
  this.connection = Net.createConnection(this.port,this.host,callback);

  this.serve(this.connection);
}
server.listen(common.PORT, function() {
  console.log('listening...');

  net.createConnection(common.PORT);
});
Example #26
0
Connection.prototype.connect = function(_options) {
  var self = this;
  _options = _options || {};
  // Check if we are overriding the promoteLongs
  if(typeof _options.promoteLongs == 'boolean') {
    self.responseOptions.promoteLongs = _options.promoteLongs;
  }

  // Create new connection instance
  self.connection = self.domainSocket
    ? net.createConnection(self.host)
    : net.createConnection(self.port, self.host);

  // Set the options for the connection
  self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay);
  self.connection.setTimeout(self.connectionTimeout);
  self.connection.setNoDelay(self.noDelay);

  // If we have ssl enabled
  if(self.ssl) {
    var sslOptions = {
        socket: self.connection
      , rejectUnauthorized: self.rejectUnauthorized
    }

    if(self.ca) sslOptions.ca = self.ca;
    if(self.cert) sslOptions.cert = self.cert;
    if(self.key) sslOptions.key = self.key;
    if(self.passphrase) sslOptions.passphrase = self.passphrase;

    // Override checkServerIdentity behavior
    if(self.checkServerIdentity == false) {
      // Skip the identiy check by retuning undefined as per node documents
      // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback
      sslOptions.checkServerIdentity = function(servername, cert) {
        return undefined;
      }
    } else if(typeof self.checkServerIdentity == 'function') {
      sslOptions.checkServerIdentity = self.checkServerIdentity;
    }

    // Attempt SSL connection
    self.connection = tls.connect(self.port, self.host, sslOptions, function() {
      // Error on auth or skip
      if(self.connection.authorizationError && self.rejectUnauthorized) {
        return self.emit("error", self.connection.authorizationError, self, {ssl:true});
      }

      // Set socket timeout instead of connection timeout
      self.connection.setTimeout(self.socketTimeout);
      // We are done emit connect
      self.emit('connect', self);
    });
    self.connection.setTimeout(self.connectionTimeout);
  } else {
    self.connection.on('connect', function() {
      // Set socket timeout instead of connection timeout
      self.connection.setTimeout(self.socketTimeout);
      // Emit connect event
      self.emit('connect', self);
    });
  }

  // Add handlers for events
  self.connection.once('error', errorHandler(self));
  self.connection.once('timeout', timeoutHandler(self));
  self.connection.once('close', closeHandler(self));
  self.connection.on('data', dataHandler(self));
}
	var sshServer = setTimeout(function() {
		allreadyPiped = true;
		var proxy = net.createConnection(22, function() {
			conn.pipe(proxy).pipe(conn);
		});
	}, 2000);
var common = require('../common');
var net = require('net');
var assert = require('assert');

var c = net.createConnection(common.PORT, 'blah.blah');

c.on('connect', assert.fail);

c.on('error', common.mustCall(function(e) {
  assert.equal(e.code, 'ENOTFOUND');
  assert.equal(e.port, common.PORT);
  assert.equal(e.hostname, 'blah.blah');
}));
Example #29
0
Connection.prototype.start = function() {
  var self = this;

  // If we have a normal connection
  if(this.socketOptions.ssl) {
    // Create new connection instance
    if(this.domainSocket) {
      this.connection = net.createConnection(this.socketOptions.host);
    } else {
      this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host);
    }
    if(this.logger != null && this.logger.doDebug){
      this.logger.debug("opened connection", this.socketOptions);
    }

    // Set options on the socket
    this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout);
    // Work around for 0.4.X
    if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay);
    // Set keep alive if defined
    if(process.version.indexOf("v0.4") == -1) {
      if(this.socketOptions.keepAlive > 0) {
        this.connection.setKeepAlive(true, this.socketOptions.keepAlive);
      } else {
        this.connection.setKeepAlive(false);
      }
    }

    // Check if the driver should validate the certificate
    var validate_certificates = this.socketOptions.sslValidate == true ? true : false;

    // Create options for the tls connection
    var tls_options = {
        socket: this.connection
      , rejectUnauthorized: false
    }

    // If we wish to validate the certificate we have provided a ca store
    if(validate_certificates) {
      tls_options.ca = this.socketOptions.sslCA;
    }

    // If we have a certificate to present
    if(this.socketOptions.sslCert) {      
      tls_options.cert = this.socketOptions.sslCert;
      tls_options.key = this.socketOptions.sslKey;
    }

    // If the driver has been provided a private key password
    if(this.socketOptions.sslPass) {
      tls_options.passphrase = this.socketOptions.sslPass;
    }

    // Contains the cleartext stream
    var cleartext = null;
    // Attempt to establish a TLS connection to the server
    try {
      cleartext = tls.connect(this.socketOptions.port, this.socketOptions.host, tls_options, function() {      
        // If we have a ssl certificate validation error return an error
        if(cleartext.authorizationError && validate_certificates) {          
          // Emit an error
          return self.emit("error", cleartext.authorizationError, self, {ssl:true});        
        }
        
        // Connect to the server
        connectHandler(self)();
      })      
    } catch(err) {
      return self.emit("error", "SSL connection failed", self, {ssl:true});
    }

    // Save the output stream
    this.writeSteam = cleartext;

    // Set up data handler for the clear stream
    cleartext.on("data", createDataHandler(this));
    // Do any handling of end event of the stream
    cleartext.on("end", endHandler(this));
    cleartext.on("error", errorHandler(this));    

    // Handle any errors
    this.connection.on("error", errorHandler(this));    
    // Handle timeout
    this.connection.on("timeout", timeoutHandler(this));
    // Handle drain event
    this.connection.on("drain", drainHandler(this));
    // Handle the close event
    this.connection.on("close", closeHandler(this));
  } else {
    // Create new connection instance
    if(this.domainSocket) {
      this.connection = net.createConnection(this.socketOptions.host);
    } else {
      this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host);
    }
    if(this.logger != null && this.logger.doDebug){
      this.logger.debug("opened connection", this.socketOptions);
    }

    // Set options on the socket
    this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout);
    // Work around for 0.4.X
    if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay);
    // Set keep alive if defined
    if(process.version.indexOf("v0.4") == -1) {
      if(this.socketOptions.keepAlive > 0) {
        this.connection.setKeepAlive(true, this.socketOptions.keepAlive);
      } else {
        this.connection.setKeepAlive(false);
      }
    }

    // Set up write stream
    this.writeSteam = this.connection;
    // Add handlers
    this.connection.on("error", errorHandler(this));
    // Add all handlers to the socket to manage it
    this.connection.on("connect", connectHandler(this));
    // this.connection.on("end", endHandler(this));
    this.connection.on("data", createDataHandler(this));
    this.connection.on("timeout", timeoutHandler(this));
    this.connection.on("drain", drainHandler(this));
    this.connection.on("close", closeHandler(this));
  }
}
	connection.on('message', function(data) {
		data = encryptor.decrypt(data);
		logger.debug(`[${connectionId}]: read data[length = ${data.length}] from local connection at stage[${STAGE[stage]}]`);

		switch (stage) {

			case STAGE_INIT:
				if (data.length < 7) {
					stage = STAGE_DESTROYED;
					return connection.close();
				}
				addressHeader = parseAddressHeader(data, 0);
				if (!addressHeader) {
					stage = STAGE_DESTROYED;
					return connection.close();
				}

				logger.info(`[${connectionId}]: connecting to ${addressHeader.dstAddr}:${addressHeader.dstPort}`);
				stage = STAGE_CONNECTING;

				targetConnection = net.createConnection({
					port: addressHeader.dstPort,
					host: addressHeader.dstAddr,
					allowHalfOpen: true
				}, function() {
					logger.info(`[${connectionId}]: connecting to target`);

					dataCache = Buffer.concat(dataCache);
					targetConnection.write(dataCache, function() {
						logger.debug(`[${connectionId}]: write data[length = ${dataCache.length}] to target connection`);
						dataCache = null;
					});
					stage = STAGE_STREAM;
				});

				targetConnection.on('data', function(data) {
					logger.debug(`[${connectionId}]: read data[length = ${data.length}] from target connection`);
					if (connection.readyState == WebSocket.OPEN) {
						connection.send(encryptor.encrypt(data), {
							binary: true
						}, function() {
							logger.debug(`[${connectionId}]: write data[length = ${data.length}] to local connection`);
						});
					}
				});
				targetConnection.on('end', function() {
					logger.info(`[${connectionId}]: end event of target connection has been triggered`);
					stage = STAGE_DESTROYED;
					connection.close();
				});
				targetConnection.on('close', function(hadError) {
					logger.info(`[${connectionId}]: close event[had error = ${hadError}] of target connection has been triggered`);
					stage = STAGE_DESTROYED;
					connection.close();
				});
				targetConnection.on('error', function(error) {
					logger.error(`[${connectionId}]: an error of target connection occured`, error);
					stage = STAGE_DESTROYED;
					targetConnection.destroy();
					connection.close();
				});

				if (data.length > addressHeader.headerLen) {
					dataCache.push(data.slice(addressHeader.headerLen));
				}
				break;

			case STAGE_CONNECTING:
				dataCache.push(data);
				break;

			case STAGE_STREAM:
				targetConnection.write(data, function() {
					logger.debug(`[${connectionId}]: write data[length = ${data.length}] to target connection`);
				});
				break;
		}
	});