Example #1
0
function startClient() {
  var s = new net.Stream();

  var sslcontext = crypto.createCredentials({key: key, cert: cert});
  sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA');

  var pair = tls.createSecurePair(sslcontext, false);

  assert.ok(pair.encrypted.writable);
  assert.ok(pair.cleartext.writable);

  pair.encrypted.pipe(s);
  s.pipe(pair.encrypted);

  s.connect(PORT);

  s.on('connect', function() {
    console.log('client connected');
  });

  pair.on('secure', function() {
    console.log('client: connected+secure!');
    console.log('client pair.cleartext.getPeerCertificate(): %j',
                pair.cleartext.getPeerCertificate());

    // "TLS Web Client Authentication"
    assert.equal(pair.cleartext.getPeerCertificate().ext_key_usage.length, 1);
    assert.equal(pair.cleartext.getPeerCertificate().ext_key_usage[0], '1.3.6.1.5.5.7.3.2');

    console.log('client pair.cleartext.getCipher(): %j',
                pair.cleartext.getCipher());
    setTimeout(function() {
      pair.cleartext.write('hello\r\n', function () {
        gotWriteCallback = true;
      });
    }, 500);
  });

  pair.cleartext.on('data', function(d) {
    console.log('cleartext: %s', d.toString());
  });

  s.on('close', function() {
    console.log('client close');
  });

  pair.encrypted.on('error', function(err) {
    console.log('encrypted error: ' + err);
  });

  s.on('error', function(err) {
    console.log('socket error: ' + err);
  });

  pair.on('error', function(err) {
    console.log('secure error: ' + err);
  });
}
Example #2
0
exports['client/server'] = function (assert) {
    var BufferList = require('bufferlist');
    var bufs = new BufferList;
    var elems = [];

    client.addListener('data', function (data) {
        bufs.push(data);
        elems.push(data);
        
        assert.equal(bufs.take(3), elems[0], 'take first 3 bytes');
        assert.equal(bufs.take(100), elems.join(''), 'take past length of buffer');
    });

    client.addListener('end', function (data) {
        assert.equal(bufs.length, elems.join('').length, 'verify length');
        assert.equal(bufs.take(bufs.length), elems.join(''), 'take to the end');
        client.end();
    });

    var port = 1e4 + Math.random() * ((1 << 16) - 1 - 1e4);
    var server = net.createServer(function (stream) {
        stream.addListener('connect', function () {
            stream.write('foo');
            setTimeout(function () {
                stream.write('bar');
                setTimeout(function () {
                    stream.write('baz');
                    stream.end();
                    server.close();
                }, 500);
            }, 500);
        });
    });
    server.listen(port);

    client.connect(port);
};
Example #3
0
MetadataAgent.prototype.createKVMServer = function (zopts, callback) {
  var self = this;
  var zlog = self.zlog[zopts.zone];
  var kvmstream = new net.Stream();
  self.zoneConnections[zopts.zone]
  = { conn: new net.Stream()
    , done: false
    , end: function () {
        if (this.done) return;
        this.done = true;
        zlog.info("Closing kvm stream for " + zopts.zone);
        kvmstream.end();
      }
    };

  var buffer = '';
  var handler = self.makeMetadataHandler(zopts.zone, kvmstream);

  kvmstream.on('data', function (data) {
    var chunk, chunks;
    buffer += data.toString();
    chunks = buffer.split('\n');
    while (chunks.length > 1) {
      chunk = chunks.shift();
      handler(chunk);
    }
    buffer = chunks.pop();
  });

  kvmstream.on('error', function(e) {
    zlog.error("KVM Socket error: " + e.message);
    zlog.error(e.stack);
  });

  kvmstream.connect(zopts.sockpath)
}
  function startClient() {
    const s = new net.Stream();

    const sslcontext = tls.createSecureContext({ key, cert });
    sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA');

    const pair = tls.createSecurePair(sslcontext, false);

    assert.ok(pair.encrypted.writable);
    assert.ok(pair.cleartext.writable);

    pair.encrypted.pipe(s);
    s.pipe(pair.encrypted);

    s.connect(common.PORT);

    s.on('connect', function() {
      console.log('client connected');
    });

    pair.on('secure', function() {
      console.log('client: connected+secure!');
      console.log('client pair.cleartext.getPeerCertificate(): %j',
                  pair.cleartext.getPeerCertificate());
      console.log('client pair.cleartext.getCipher(): %j',
                  pair.cleartext.getCipher());
      if (check) check(pair);
      setTimeout(function() {
        pair.cleartext.write('hello\r\n', function() {
          gotWriteCallback = true;
        });
      }, 500);
    });

    pair.cleartext.on('data', function(d) {
      console.log('cleartext: %s', d.toString());
    });

    s.on('close', function() {
      console.log('client close');
    });

    pair.encrypted.on('error', function(err) {
      console.log(`encrypted error: ${err}`);
    });

    s.on('error', function(err) {
      console.log(`socket error: ${err}`);
    });

    pair.on('error', function(err) {
      console.log(`secure error: ${err}`);
    });
  }
Example #5
0
function Client() {
  net.Stream.call(this);
  var protocol = this.protocol = new Protocol(this);
  this._reqCallbacks = [];
  var socket = this;

  this.currentFrame = NO_FRAME;
  this.currentSourceLine = -1;
  this.handles = {};
  this.scripts = {};
  this.breakpoints = [];

  // Note that 'Protocol' requires strings instead of Buffers.
  socket.setEncoding('utf8');
  socket.on('data', function(d) {
    protocol.execute(d);
  });

  protocol.onResponse = this._onResponse.bind(this);
}
Example #6
0
  this.connect = function( hollaback ) {
    // Client setup
    var not_open
    if ( !stream || ( not_open = ( ['open', 'opening'].indexOf( stream.readyState ) < 0 ) ) ) {
      if ( not_open ) {
        stream.end()
        stream.removeAllListeners()
        stream = null
      }

      stream = new net.Stream()
      stream.setEncoding( this.options.encoding )
      stream.setTimeout( 0 )

      // Forward network errors
      stream.addListener( 'error', function( er ) {
        emitter.emit( 'error', er )
        emitter.emit( 'error:network', er )
      })

      // Receive data
      stream.addListener( 'data', parseMessage.bind( this ) )

      // Timeout
      stream.addListener( 'timeout', do_disconnect.bind( this ) )

      // End
      stream.addListener( 'end', do_disconnect.bind( this ) )

      stream.connect(this.options.port, this.options.server)
    }

    // Holla
    if ( typeof hollaback === 'function' )
      this.listenOnce( 'connected', hollaback )
    return this;
  }
Example #7
0
 Array(50+1).join('x').split('').forEach(function () {
     var stream = new Stream;
     stream.readable = true;
     
     parsley(stream, function (req) {
         req.on('headers', function (headers) {
             t.equal(req.url, '/');
             
             t.deepEqual(headers, {
                 host : 'beep.boop',
                 connection : 'close',
             });
         });
         
         req.on('end', function () {
             if (--pending === 0) {
                 t.end();
             }
         });
     });
     
     var msg = new Buffer([
         'GET / HTTP/1.1',
         'Host: beep.boop',
         'Connection: close',
         '',
         ''
     ].join('\r\n'));
     
     var chunks = chunky(msg);
     var iv = setInterval(function () {
         stream.emit('data', chunks.shift());
         if (chunks.length === 0) {
             stream.emit('end');
             clearInterval(iv);
         }
     }, 10);
 });
Example #8
0
function client(options) {
	var _fastcgi = this;
	var connection = new net.Stream();
	var htparser = new HTTPParser("response");
	var queue = [];
	var reqid = 0;
	var requests = {};
	var stats = {
		connections: 0
	}
	_fastcgi.stats = stats;
	var phprx = new RegExp("Status: (\\d{3}) (.*?)\\r\\n");
	var port = options.port || "/tmp/php.sock";
	var host = options.host;
	options.php = options.php || {};
	var SERVER_ADDR = options.php.SERVER_ADDR || "127.0.0.1";
	var SERVER_PORT = options.php.SERVER_PORT || "80";
	var SERVER_NAME = options.php.SERVER_NAME || "localhost";	
	var keepalive = options.keepAlive || false;
	var sredirectstatus = options.redirectStatus || null;
	var _current = null;
	
	connection.setNoDelay(true);
	connection.setTimeout(0);
	connection.params = [
		["DOCUMENT_ROOT", options.root || "/var/www/html"],
		["SERVER_PROTOCOL", "HTTP/1.1"],
		["GATEWAY_INTERFACE", "CGI/1.1"],
		["SERVER_SOFTWARE", "node.js"],
		["SERVER_ADDR", SERVER_ADDR.toString()],
		["SERVER_PORT", SERVER_PORT.toString()],
		["SERVER_NAME", SERVER_NAME.toString()],
	];
	connection.writer = new fastcgi.writer();
	connection.parser = new fastcgi.parser();
	connection.parser.encoding = "binary";
	connection.writer.encoding = "binary";
	
	htparser.onHeaderField = function (b, start, len) {
		var slice = b.toString('ascii', start, start+len).toLowerCase();
		if (htparser.value != undefined) {
			var dest = _current.fcgi.headers;
			if (htparser.field in dest) {
				dest[htparser.field].push(htparser.value);
			} else {
				dest[htparser.field] = [htparser.value];
			}
			htparser.field = "";
			htparser.value = "";
		}
		if (htparser.field) {
			htparser.field += slice;
		} else {
			htparser.field = slice;
		}
	};
	
	htparser.onHeaderValue = function (b, start, len) {
		var slice = b.toString('ascii', start, start+len);
		if (htparser.value) {
			htparser.value += slice;
		} else {
			htparser.value = slice;
		}
	};

	htparser.onHeadersComplete = function (info) {
		if (htparser.field && (htparser.value != undefined)) {
			var dest = _current.fcgi.headers;
			if (htparser.field in dest) {
				dest[htparser.field].push(htparser.value);
			} else {
				dest[htparser.field] = [htparser.value];
			}
			htparser.field = null;
			htparser.value = null;
		}
		_current.fcgi.info = info;
		_current.resp.statusCode = info.statusCode;
		for(header in _current.fcgi.headers) {
			var head = _current.fcgi.headers[header];
			if(head.length > 1) {
				_current.resp.setHeader(header, head);
			}
			else {
				_current.resp.setHeader(header, head[0]);
			}
		}
	}

	htparser.onBody = function(buffer, start, len) {
		_current.resp.write(buffer.slice(start, start + len));
	}
	
	connection.parser.onHeader = function(header) {
		_current = requests[header.recordId];
	}
	
	connection.parser.onBody = function(buffer, start, len) {
		//console.log(buffer.toString("utf8", start, start + len));
		if(!_current.fcgi.body) {
			htparser.reinitialize("response");
			_current.fcgi.headers = {};
			var status = buffer.slice(start, 100).toString();
			var match = status.match(phprx);
			if(match) {
				var header = match[0];
				var buff = buffer.slice(start + header.length, start + len);
				status = new Buffer("HTTP/1.1 " + match[1] + " " + match[2] + "\r\n");
				try {
					var parsed = htparser.execute(status, 0, status.length);
					var parsed = htparser.execute(buff, 0, buff.length);
					if(parsed.bytesParsed) {
						_current.resp.write(buff.slice(start + parsed.bytesParsed, start + len));
					}
				}
				catch(ex) {
					_current.cb(ex);
				}
			}
			else {
				status = new Buffer("HTTP/1.1 200 OK\r\n");
				try {
					var parsed = htparser.execute(status, 0, status.length);
					var parsed = htparser.execute(buffer, start, len);
					if(parsed.bytesParsed) {
						_current.resp.write(buffer.slice(start + parsed.bytesParsed, start + len));
					}
				}
				catch(ex) {
					_current.cb(ex);
				}
			}
			_current.fcgi.body = true;
		}
		else {
			try {
				var parsed = htparser.execute(buffer, start, len);
				if(parsed.message == "Parse Error" && ("bytesParsed" in parsed)) {
					_current.resp.write(buffer.slice(start + parsed.bytesParsed, start + len));
				}
			}
			catch(ex) {
				_current.cb(ex);
			}
		}
	}
		
	connection.parser.onRecord = function(record) {
		//console.log(record);
		var recordId = parseInt(record.header.recordId);
		var request = requests[recordId];
		switch(record.header.type) {
			case fastcgi.constants.record.FCGI_END:
				request.fcgi.status = record.body;
				if(record.body.status == 0 && record.body.protocolStatus == 0) {
					request.resp.end();
					
//					request.cb(null, request.resp);
					delete requests[recordId];
					//request.cb(null, request.resp);
				}
				else {
					// error from fastcgi app - return 500;
					// if we want to use this (php doesn't) we need to buffer the whole response and wait to inspect this before sending any headers. that's just nasty!!
				}
				if(keepalive && queue.length > 0){
					_next();
				}
				break;
			default:
				break;
		}
	};
	
	connection.parser.onError = function(err) {
		_fastcgi.emit("error", err);
	};
	
	if(sredirectstatus) {
		connection.params.push(["REDIRECT_STATUS", sredirectstatus.toString()]);
	}

	connection.ondata = function (buffer, start, end) {
		connection.parser.execute(buffer, start, end);
	};
	
	connection.addListener("connect", function() {
		stats.connections++;
		if(queue.length > 0) {
			_next();
		}
	});
	
	connection.addListener("timeout", function() {
		connection.end();
	});
	
	connection.addListener("end", function() {
		if(queue.length > 0) {
			process.nextTick(_fastcgi.connect);
		}
	});
	
	connection.addListener("error", function(err) {
		_fastcgi.emit("error", err);
		connection.end();
	});
	
	this.connect = function() {
		if(!connection.fd) connection.connect(port, host);
	}
	
	this.end = function() {
		connection.end();
	}
	
	function _next() {
		var request = queue.shift();
		var req = request.req;
		req.resume();
		var params = connection.params.slice(0);
		params.push(["REMOTE_ADDR", req.connection.remoteAddress]);
		params.push(["REMOTE_PORT", req.connection.remotePort.toString()]);
		req.url = url.parse(req.url);
		params.push(["SCRIPT_FILENAME", options.root + req.url.pathname]);
		params.push(["QUERY_STRING", req.url.query || ""]);
		params.push(["REQUEST_METHOD", req.method]);
		params.push(["SCRIPT_NAME", req.url.pathname]);
		params.push(["REQUEST_URI", req.url.pathname + (req.url.query || "")]);
		params.push(["DOCUMENT_URI", req.url.pathname]);
		//TODO: probably better to find a generic way of translating all http headers on request into PHP headers
		if("user-agent" in req.headers) {
			params.push(["HTTP_USER_AGENT", req.headers["user-agent"]]);
		}
		if("accept-encoding" in req.headers) {
			params.push(["HTTP_ACCEPT_ENCODING", req.headers["accept-encoding"]]);
		}
		if("cookie" in req.headers) {
			params.push(["HTTP_COOKIE", req.headers["cookie"]]);
		}
		if("connection" in req.headers) {
			params.push(["HTTP_CONNECTION", req.headers["connection"]]);
		}
		if("accept" in req.headers) {
			params.push(["HTTP_ACCEPT", req.headers["accept"]]);
		}
		if("host" in req.headers) {
			params.push(["HTTP_HOST", req.headers["host"]]);
		}
		if("content-type" in req.headers) {
			params.push(["CONTENT_TYPE", req.headers["content-type"]]);
		}
		if("content-length" in req.headers) {
			params.push(["CONTENT_LENGTH", req.headers["content-length"]]);
		}
		try {
			connection.writer.writeHeader({
				"version": fastcgi.constants.version,
				"type": fastcgi.constants.record.FCGI_BEGIN,
				"recordId": request.id,
				"contentLength": 8,
				"paddingLength": 0
			});
			connection.writer.writeBegin({
				"role": fastcgi.constants.role.FCGI_RESPONDER,
				"flags": keepalive?fastcgi.constants.keepalive.ON:fastcgi.constants.keepalive.OFF
			});
			connection.write(connection.writer.tobuffer());
			connection.writer.writeHeader({
				"version": fastcgi.constants.version,
				"type": fastcgi.constants.record.FCGI_PARAMS,
				"recordId": request.id,
				"contentLength": fastcgi.getParamLength(params),
				"paddingLength": 0
			});
			connection.writer.writeParams(params);
			connection.write(connection.writer.tobuffer());
			connection.writer.writeHeader({
				"version": fastcgi.constants.version,
				"type": fastcgi.constants.record.FCGI_PARAMS,
				"recordId": request.id,
				"contentLength": 0,
				"paddingLength": 0
			});
			connection.write(connection.writer.tobuffer());
			switch(req.method) {
				case "GET":
					connection.writer.writeHeader({
						"version": fastcgi.constants.version,
						"type": fastcgi.constants.record.FCGI_STDIN,
						"recordId": request.id,
						"contentLength": 0,
						"paddingLength": 0
					});
					connection.write(connection.writer.tobuffer());
					break;
				case "PUT":
					request.cb(new Error("not implemented"));
					break;
				case "POST":
					req.on("data", function(chunk) {
						connection.writer.writeHeader({
							"version": fastcgi.constants.version,
							"type": fastcgi.constants.record.FCGI_STDIN,
							"recordId": request.id,
							"contentLength": chunk.length,
							"paddingLength": 0
						});
						connection.writer.writeBody(chunk);
						connection.write(connection.writer.tobuffer());
					});
					req.on("end", function() {
						connection.writer.writeHeader({
							"version": fastcgi.constants.version,
							"type": fastcgi.constants.record.FCGI_STDIN,
							"recordId": request.id,
							"contentLength": 0,
							"paddingLength": 0
						});
						connection.write(connection.writer.tobuffer());
					});
					break;
				case "DELETE":
					request.cb(new Error("not implemented"));
					break;
			}
		}
		catch(ex) {
			connection.end();
			request.cb(ex);
		}
	}
	
	this.request = function(req, resp, cb) {
		requests[reqid] = {
			"id": reqid,
			"req": req,
			"resp": resp,
			"cb": function(){
			cb(req, resp);
			},
			"fcgi": {}
		};
		queue.push(requests[reqid]);
		reqid++;
		if(reqid == 65535) {
			reqid = 0;
		}
		if(!connection.fd) {
			req.pause();
			_fastcgi.connect();
		}
		else if(keepalive && queue.length == 1){
			_next();
		}
	}
}
Example #9
0
 setTimeout(function () {
     stream.emit('data', '...I am a computer.');
     stream.emit('end');
 }, 20);
Example #10
0
 setTimeout(function () {
     stream.emit('data', 'Beep boop.\r\n');
 }, 10);
Example #11
0
function Connection (options) {
  net.Stream.call(this);

  var self = this;

  this.setOptions(options);

  var state = 'handshake';
  var parser;

  this._defaultExchange = null;

  self.addListener('connect', function () {
    // channel 0 is the control channel.
    self.channels = [self];
    self.queues = {};
    self.exchanges = {};

    parser = new AMQPParser('0-8', 'client');

    parser.onMethod = function (channel, method, args) {
      self._onMethod(channel, method, args);
    };

    parser.onContent = function (channel, data) {
      debug(channel + " > content " + data.length);
      if (self.channels[channel] && self.channels[channel]._onContent) {
        self.channels[channel]._onContent(channel, data);
      } else {
        debug("unhandled content: " + data);
      }
    };

    parser.onContentHeader = function (channel, classInfo, weight, properties, size) {
      debug(channel + " > content header " + JSON.stringify([classInfo.name, weight, properties, size]));
      if (self.channels[channel] && self.channels[channel]._onContentHeader) {
        self.channels[channel]._onContentHeader(channel, classInfo, weight, properties, size);
      } else {
        debug("unhandled content header");
      }
    };

    parser.onHeartBeat = function () {
      debug("heartbeat");
    };

    //debug("connected...");
    // Time to start the AMQP 7-way connection initialization handshake!
    // 1. The client sends the server a version string
    self.write("AMQP" + String.fromCharCode(1,1,8,0));
    state = 'handshake';
  });

  self.addListener('data', function (data) {
    parser.execute(data);
  });

  self.addListener('end', function () {
    self.end();
    // in order to allow reconnects, have to clear the
    // state.
    parser = null;
  });
}
Example #12
0
File: http.js Project: ehaas/node
function Client ( ) {
  net.Stream.call(this);
  var self = this;

  httpSocketSetup(self);

  var parser;

  function initParser () {
    if (!parser) parser = parsers.alloc();
    parser.reinitialize('response');
    parser.socket = self;
    parser.onIncoming = function (res) {
      debug("incoming response!");

      var req = self._outgoing[0];

      // Responses to HEAD requests are AWFUL. Ask Ryan.
      // A major oversight in HTTP. Hence this nastiness.
      var isHeadResponse = req.method == "HEAD";
      debug('isHeadResponse ' + isHeadResponse);

      res.addListener('end', function ( ) {
        debug("request complete disconnecting. readyState = " + self.readyState);
        // For the moment we reconnect for every request. FIXME!
        // All that should be required for keep-alive is to not reconnect,
        // but outgoingFlush instead.
        if (req.shouldKeepAlive) {
          outgoingFlush(self)
          self._outgoing.shift()
          outgoingFlush(self)
        } else {
          self.end();
        }
      });

      req.emit("response", res);

      return isHeadResponse;
    };
  };

  self.ondata = function (d, start, end) {
    if (!parser) {
      throw new Error("parser not initialized prior to Client.ondata call");
    }
    var ret = parser.execute(d, start, end - start);
    if (ret instanceof Error) {
      self.destroy(ret);
    } else if (parser.incoming && parser.incoming.upgrade) {
      var bytesParsed = ret;
      self.ondata = null;
      self.onend = null

      var req = self._outgoing[0];

      var upgradeHead = d.slice(start + bytesParsed + 1, end);

      if (self.listeners('upgrade').length) {
        self.emit('upgrade', req, self, upgradeHead);
      } else {
        self.destroy();
      }
    }
  };

  self.addListener("connect", function () {
    debug('client connected');
    if (this.https) {
      this.setSecure(this.credentials);
    } else {
      initParser();
      debug('requests: ' + sys.inspect(self._outgoing));
      outgoingFlush(self);
    }
  });

  self.addListener("secure", function () {
    initParser();
    debug('requests: ' + sys.inspect(self._outgoing));
    outgoingFlush(self);
  });

  self.onend = function () {
    if (parser) parser.finish();
    debug("self got end closing. readyState = " + self.readyState);
    self.end();
  };

  self.addListener("close", function (e) {
    if (e) return;

    debug("HTTP CLIENT onClose. readyState = " + self.readyState);

    // finally done with the request
    self._outgoing.shift();

    // If there are more requests to handle, reconnect.
    if (self._outgoing.length) {
      self._reconnect();
    } else if (parser) {
      parsers.free(parser);
      parser = null;
    }
  });
};
Example #13
0
exports.listen = function(options, server){
	var isMaster;
	if(process.env._IS_CHILD_){
	    var stdin = new net.Stream(0, 'unix');
	    var descriptorType;
	    stdin.addListener('data', function(message){
	        descriptorType = message;
	    });
	    var siblingIn;
	    stdin.addListener('fd', function(fd){
	    	if(descriptorType == "tcp"){
	    		server.listenFD(fd, 'tcp4');
	    	}
	    	else if(descriptorType == "sibling"){
	    		var stream = new net.Stream(fd, "unix");
	    		emitter.emit("node", stream);
	    		stream.resume();
	    	}
	    	else{
    			throw new Error("Unknown file descriptor " + descriptorType);
	    	}
	    });
	    stdin.resume();		
	}else{
		isMaster = true;
		var children = [],
			tcpDescriptor = netBinding.socket("tcp4");
		netBinding.bind(tcpDescriptor, options.port || 80);
		netBinding.listen(tcpDescriptor, 128);
		server.listenFD(tcpDescriptor, 'tcp4');
		var priorArgs = process.argv;
		if(process.platform == "cygwin" && priorArgs){
			priorArgs = ["/usr/bin/bash","--login","-c", "cd " + process.cwd() + " && " + priorArgs.join(" ")];
		}
		var env = {_IS_CHILD_: "true"};
		for(var i in process.env){
			env[i] = process.env[i];
		}
		for(var i = 0; i < options.nodes - 1; i++){
			var childConnection = netBinding.socketpair();
			// spawn the child process
			var child = children[i] = childProcess.spawn(
				priorArgs[0],
				priorArgs.slice(1),
				env,
				[childConnection[1], -1, -1]	
			);
			child.master = new net.Stream(childConnection[0], 'unix');
			
			child.master.write("tcp", "ascii", tcpDescriptor);
			(function(child){
				for(var j = 0; j < i; j++){
						var siblingConnection = netBinding.socketpair();
						child.master.write("sibling", "ascii", siblingConnection[1]);
						children[j].master.write("sibling", "ascii", siblingConnection[0]);
				}
				var masterChildConnection = netBinding.socketpair();
				process.nextTick(function(){
		    		var stream = new net.Stream(masterChildConnection[0], "unix");
		    		emitter.emit("node", stream);
		    		stream.resume();
					child.master.write("sibling", "ascii", masterChildConnection[1]);
				});
			})(child);
			
			// Redirect stdout and stderr
			child.stdout.addListener('data', function(data){
				if(exports.ignoreReloadMessages && data.toString().substring(0, 10) == "Reloading "){ 
					return;
				}
				process.stdout.write("\r" + data + "\r");
			});  
			child.stderr.addListener('data', function(data){
				require("sys").puts("\r" + data + "\r");  
			});
		}
		["SIGINT", "SIGTERM", "SIGKILL", "SIGQUIT", "exit"].forEach(function(signal){
			process.addListener(signal, function(){
				children.forEach(function(child){
					child.kill();
				});
				process.exit();
			});
		});
		
	}
	var emitter = new process.EventEmitter();
	emitter.isMaster = isMaster;
	return emitter;
}
Example #14
0
// Verify that we can send and receive a file descriptor.

var assert = require('assert');
var net = require('net');
var netBinding = process.binding('net');
var path = require('path');
var sys = require('sys');
var Worker = require('../lib/webworker').Worker;

var w = new Worker(path.join(__dirname, 'workers', 'fd.js'));

var fds = netBinding.pipe();

var s = new net.Stream(fds[0]);
s.resume();

var receivedData = false;
s.addListener('data', function(d) {
    var o = JSON.parse(d.toString('utf8'));

    assert.equal(o.grumpy, 'frumpy');

    receivedData = true;
    s.destroy();
    w.terminate();
});

w.postMessage({ 'grumpy' : 'frumpy' }, fds[1]);

process.addListener('exit', function() {
    assert.equal(receivedData, true);
Example #15
0
 , end: function () {
     if (this.done) return;
     this.done = true;
     zlog.info("Closing kvm stream for " + zopts.zone);
     kvmstream.end();
   }
Example #16
0
function Client ( ) {
  net.Stream.call(this);

  var self = this;

  var requests = [];
  var currentRequest;

  var parser = parsers.alloc();
  parser.reinitialize('response');
  parser.socket = this;

  self._reconnect = function () {
    if (self.readyState != "opening") {
      debug("HTTP CLIENT: reconnecting readyState = " + self.readyState);
      self.connect(self.port, self.host);
    }
  };

  self._pushRequest = function (req) {
    req.addListener("flush", function () {
      if (self.readyState == "closed") {
        debug("HTTP CLIENT request flush. reconnect.  readyState = " + self.readyState);
        self._reconnect();
        return;
      }

      debug("self flush  readyState = " + self.readyState);
      if (req == currentRequest) flushMessageQueue(self, [req]);
    });
    requests.push(req);
  };

  self.ondata = function (d, start, end) {
    var bytesParsed = parser.execute(d, start, end - start);
    if (parser.incoming && parser.incoming.upgrade) {
      var upgradeHead = d.slice(start + bytesParsed, end - start);
      parser.incoming.upgradeHead = upgradeHead;
      currentRequest.emit("response", parser.incoming);
      parser.incoming.emit('end');
      self.ondata = null;
      self.onend = null
    }
  };

  self.addListener("connect", function () {
    if (this.https) {
	this.setSecure(this.credentials);
    } else {
      parser.reinitialize('response');
      debug('requests: ' + sys.inspect(requests));
      currentRequest = requests.shift()
      currentRequest.flush();
    }
  });

  self.addListener("secure", function () {
    parser.reinitialize('response');
    debug('requests: ' + sys.inspect(requests));
    currentRequest = requests.shift()
    currentRequest.flush();
  });

  self.onend = function () {
    parser.finish();

    debug("self got end closing. readyState = " + self.readyState);
    self.end();
  };

  self.addListener("close", function (e) {
    if (e) {
      self.emit("error", e);
      return;
    }

    debug("HTTP CLIENT onClose. readyState = " + self.readyState);

    // If there are more requests to handle, reconnect.
    if (requests.length > 0) {
      self._reconnect();
    } else {
      parsers.free(parser);
    }
  });

  parser.onIncoming = function (res) {
    debug("incoming response!");

    res.addListener('end', function ( ) {
      debug("request complete disconnecting. readyState = " + self.readyState);
      self.end();
    });

    currentRequest.emit("response", res);
  };
};
Example #17
0
 client.addListener('end', function (data) {
     assert.equal(bufs.length, elems.join('').length, 'verify length');
     assert.equal(bufs.take(bufs.length), elems.join(''), 'take to the end');
     client.end();
 });
Example #18
0
 S.on('end', function(){
   console.timeEnd('end ' + S.streamID);
   S.end();
 });
Example #19
0
 S.on('data', function(data){
   console.log(data);
   console.timeEnd('data ' + S.streamID);
   S.callback();
   S.end();
 });
Example #20
0
 process.nextTick(function () {
     var stream = new net.Stream(masterChildConnection[0], 'unix');
     emitter.emit('child', stream);
     stream.resume();
     child.master.write('master', 'ascii', masterChildConnection[1]);
 });
Example #21
0
exports.spawnWorkers = function (num, options) {
    var emitter = new process.EventEmitter();
    
    options = options || {};
    
    if (process.env._CHILD_ID_) {
        var stdin = new net.Stream(0, 'unix');
        var descriptorType;
        stdin.addListener('data', function (message) {
            descriptorType = message;
        });
        stdin.addListener('fd', function (fd) {
            if (descriptorType == 'master') {
                var stream = new net.Stream(fd, 'unix');
                emitter.emit('master', stream);
                stream.resume();
            } else {
                throw new Error('Unknown file descriptor ' + descriptorType);
            }
        });
        
        stdin.resume();
        
    } else {
        var children = [],
            numChildren = num || 1,
            priorArgs = process.argv;
            
        if (process.platform === 'cygwin' && priorArgs) {
            priorArgs = ['/usr/bin/bash', '--login', '-c', 'cd ' + process.cwd() + ' && ' + priorArgs.join(' ')];
        }
        
        var env = {};
        for (var i in process.env) {
            env[i] = process.env[i];
        }
        
        var createChild = function (i) {
            
            var childConnection = netBinding.socketpair();
            env._CHILD_ID_ = i;
            
            //Spawn the child process
            var child = children[i] = childProcess.spawn(
                priorArgs[0],
                priorArgs.slice(1),
                env,
                [childConnection[1], 1, 2]
            );
            child.master = new net.Stream(childConnection[0], 'unix');
            
            (function (child) {
                var masterChildConnection = netBinding.socketpair();
                process.nextTick(function () {
                    var stream = new net.Stream(masterChildConnection[0], 'unix');
                    emitter.emit('child', stream);
                    stream.resume();
                    child.master.write('master', 'ascii', masterChildConnection[1]);
                });
            }(child));
            
        };
        for (i = 0; i < numChildren; i++) {
            createChild(i);
        }
        ['SIGINT', 'SIGTERM', 'SIGKILL', 'SIGQUIT', 'SIGHUP', 'exit'].forEach(function (signal) {
            process.addListener(signal, function () {
                children.forEach(function (child) {
                    try {
                        child.kill();
                    } catch (e) {}
                });
                //We use SIGHUP to restart the children
                if (signal !== 'exit' && signal !== 'SIGHUP') {
                    process.exit();
                }
            });
        });
    }
    
    return emitter;
};
Example #22
0
    if (++numSentMessages == 2) {
      s.destroy();
    }
  };

  pipeStream.on('drain', drainFunc);
  pipeStream.resume();

  if (pipeStream.write(JSON.stringify(d) + '\n')) {
    drainFunc();
  }
}

// Create a UNIX socket to the path defined by argv[2] and read a file
// descriptor and misc data from it.
var s = new net.Stream();
s.on('fd', function(fd) {
  receivedFDs.unshift(fd);
  processData(s);
});
s.on('data', function(data) {
  data.toString('utf8').trim().split('\n').forEach(function(d) {
    receivedData.unshift(JSON.parse(d));
  });
  processData(s);
});
s.connect(process.argv[2]);

// vim:ts=2 sw=2 et
Example #23
0
      sys.debug('CHILD: ' + l);
    }
  });
};

// Create a pipe
//
// We establish a listener on the read end of the pipe so that we can
// validate any data sent back by the child. We send the write end of the
// pipe to the child and close it off in our process.
var pipeFDs = netBinding.pipe();
assert.equal(pipeFDs.length, 2);

var seenOrdinals = [];

var pipeReadStream = new net.Stream();
pipeReadStream.addListener('data', function(data) {
  data.toString('utf8').trim().split('\n').forEach(function(d) {
    var rd = JSON.parse(d);

    assert.equal(rd.pid, cpp);
    assert.equal(seenOrdinals.indexOf(rd.ord), -1);

    seenOrdinals.unshift(rd.ord);
  });
});
pipeReadStream.open(pipeFDs[0]);
pipeReadStream.resume();

// Create a UNIX socket at SOCK_PATH and send DATA and the write end
// of the pipe to whoever connects.
Example #24
0
var Connection = exports.Connection = function() {
	var _reqs = {};
	var _self = this;
	var connection = new net.Stream();
	connection.queue = [];
	connection.setNoDelay(true);
	connection.setTimeout(0);
	var _conncb = null;
	var _opaque = 1;
	
	connection.ondata = function (buffer, start, end) {
		_self.parser.execute(buffer, start, end);
	};

	_self.parser = new memc.parser({
		"chunked": true,
		"encoding": memc.constants.encodings.BINARY
	});
	
	connection.addListener("connect", function() {
		writequeue(connection);
		_self.parser.reset();
		
		_self.parser.onMessage = function() {
			console.log(_self.parser.current);
			var message = _self.parser.current;
			_reqs["K"+message.header.opaque](message);
			//TODO: figure out what to do here
			//delete(_reqs["K"+message.header.opaque]);
		};
	
		_self.parser.onHeader = function(header) {
			if(_self.parser.chunked && header.bodylen > 0) {
				_self.parser.current.body = [];
			}
		};
	
		_self.parser.onBody = function(buffer, start, end) {
			if(arguments.length > 1) {
				_self.parser.current.body.push(buffer.slice(start, end));
			}
		};
	
		_self.parser.onError = function(exception) {
			_self.emit("error", {"type": "parser", "exception": exception});
		};
		if(_conncb) _conncb();
	});
	
	connection.addListener("end", function() {
		_self.emit("close");
	});
	
	connection.addListener("timeout", function() {
		connection.end();
	});
	
	connection.addListener("close", function(had_error) {
		connection.end();
	});
	
	connection.addListener("error", function(exception) {
		_self.emit("error", {"type": "connection", "exception": exception});
	});
	
	_self.connect = function(port, host, cb) {
		_conncb = cb;
		if(host) {
			connection.connect(port, host);
		}
		else {
			connection.connect(port);
		}
	}
	
	_self.get = function(key, cb) {
		var encoder = new Buffer(24 + key.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.GET},
	        {"int16": key.length},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": key.length},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"string": key}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.getq = function(key, cb) {
		var encoder = new Buffer(24 + key.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.GETQ},
	        {"int16": key.length},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": key.length},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"string": key}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.getk = function(key, cb) {
		var encoder = new Buffer(24 + key.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.GETK},
	        {"int16": key.length},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": key.length},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"string": key}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.getkq = function(key, cb) {
		var encoder = new Buffer(24 + key.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.GETKQ},
	        {"int16": key.length},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": key.length},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"string": key}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

//TODO: add CAS
	_self.set = function(key, value, flags, expiration, cb) {
		var encoder = new Buffer(32 + key.length + value.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.SET},
	        {"int16": key.length},
	        {"int": 0x08},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": value.length + key.length + 8},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": flags},
	        {"int32": expiration},
	        {"string": key},
	        {"string": value}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.setq = function(key, value, flags, expiration, cb) {
		var encoder = new Buffer(32 + key.length + value.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.SETQ},
	        {"int16": key.length},
	        {"int": 0x08},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": value.length + key.length + 8},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": flags},
	        {"int32": expiration},
	        {"string": key},
	        {"string": value}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.add = function(key, value, flags, expiration, cb) {
		var encoder = new Buffer(32 + key.length + value.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.ADD},
	        {"int16": key.length},
	        {"int": 0x08},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": value.length + key.length + 8},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": flags},
	        {"int32": expiration},
	        {"string": key},
	        {"string": value}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.addq = function(key, value, flags, expiration, cb) {
		var encoder = new Buffer(32 + key.length + value.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.ADDQ},
	        {"int16": key.length},
	        {"int": 0x08},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": value.length + key.length + 8},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": flags},
	        {"int32": expiration},
	        {"string": key},
	        {"string": value}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.replace = function(key, value, flags, expiration, cb) {
		var encoder = new Buffer(32 + key.length + value.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.REPLACE},
	        {"int16": key.length},
	        {"int": 0x08},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": value.length + key.length + 8},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": flags},
	        {"int32": expiration},
	        {"string": key},
	        {"string": value}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.replaceq = function(key, value, flags, expiration, cb) {
		var encoder = new Buffer(32 + key.length + value.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.REPLACEQ},
	        {"int16": key.length},
	        {"int": 0x08},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": value.length + key.length + 8},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": flags},
	        {"int32": expiration},
	        {"string": key},
	        {"string": value}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.inc = function(key, delta, initial, expiration, cb) {
		var encoder = new Buffer(24 + 20 + key.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.INCREMENT},
	        {"int16": key.length},
	        {"int": 20},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": key.length + 20},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": delta},
	        {"int32": 0},
	        {"int32": initial},
	        {"int32": expiration},
	        {"string": key}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.dec = function(key, delta, initial, expiration, cb) {
		var encoder = new Buffer(24 + 20 + key.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.DECREMENT},
	        {"int16": key.length},
	        {"int": 20},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": key.length + 20},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": delta},
	        {"int32": 0},
	        {"int32": initial},
	        {"int32": expiration},
	        {"string": key}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.incq = function(key, delta, initial, expiration, cb) {
		var encoder = new Buffer(24 + 20 + key.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.INCREMENTQ},
	        {"int16": key.length},
	        {"int": 20},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": key.length + 20},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": delta},
	        {"int32": 0},
	        {"int32": initial},
	        {"int32": expiration},
	        {"string": key}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.decq = function(key, delta, initial, expiration, cb) {
		var encoder = new Buffer(24 + 20 + key.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.DECREMENTQ},
	        {"int16": key.length},
	        {"int": 20},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": key.length + 20},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": 0},
	        {"int32": delta},
	        {"int32": 0},
	        {"int32": initial},
	        {"int32": expiration},
	        {"string": key}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.delete = function(key, cb) {
		var encoder = new Buffer(24 + key.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.DELETE},
	        {"int16": key.length},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": key.length},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"string": key}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.deleteq = function(key, cb) {
		var encoder = new Buffer(24 + key.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.DELETEQ},
	        {"int16": key.length},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": key.length},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"string": key}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.append = function(key, value, cb) {
		var encoder = new Buffer(24 + key.length + value.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.APPEND},
	        {"int16": key.length},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": value.length + key.length},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"string": key},
	        {"string": value}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.prepend = function(key, value, cb) {
		var encoder = new Buffer(24 + key.length + value.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.PREPEND},
	        {"int16": key.length},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": value.length + key.length},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"string": key},
	        {"string": value}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.appendq = function(key, value, cb) {
		var encoder = new Buffer(24 + key.length + value.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.APPENDQ},
	        {"int16": key.length},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": value.length + key.length},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"string": key},
	        {"string": value}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.prependq = function(key, value, cb) {
		var encoder = new Buffer(24 + key.length + value.length);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.PREPENDQ},
	        {"int16": key.length},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": value.length + key.length},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0},
	        {"string": key},
	        {"string": value}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.quit = function(cb) {
		var encoder = new Buffer(24);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.QUIT},
	        {"int16": 0},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": 0},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.quitq = function(cb) {
		var encoder = new Buffer(24);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.QUITQ},
	        {"int16": 0},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": 0},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.version = function(cb) {
		var encoder = new Buffer(24);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.VERSION},
	        {"int16": 0},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": 0},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.stat = function(key, cb) {
		if(key) {
			var encoder = new Buffer(24 + key.length);
			var size = bin.pack([
		        {"int": memc.constants.general.MAGIC.request},
		        {"int": memc.constants.opcodes.STAT},
		        {"int16": 0},
		        {"int": 0},
		        {"int": 0},
		        {"int16": 0},
		        {"int32": key.length},
		        {"int32": _opaque},
		        {"int32": 0},
		        {"int32": 0},
	        	{"string": key}
			], encoder, 0);
		}
		else {
			var encoder = new Buffer(24);
			var size = bin.pack([
		        {"int": memc.constants.general.MAGIC.request},
		        {"int": memc.constants.opcodes.STAT},
		        {"int16": 0},
		        {"int": 0},
		        {"int": 0},
		        {"int16": 0},
		        {"int32": 0},
		        {"int32": _opaque},
		        {"int32": 0},
		        {"int32": 0}
			], encoder, 0);
		}
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.noop = function(cb) {
		var encoder = new Buffer(24);
		var size = bin.pack([
	        {"int": memc.constants.general.MAGIC.request},
	        {"int": memc.constants.opcodes.NOOP},
	        {"int16": 0},
	        {"int": 0},
	        {"int": 0},
	        {"int16": 0},
	        {"int32": 0},
	        {"int32": _opaque},
	        {"int32": 0},
	        {"int32": 0}
		], encoder, 0);
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.flush = function(expiration, cb) {
		if(expiration) {
			var encoder = new Buffer(24 + 8);
			var size = bin.pack([
		        {"int": memc.constants.general.MAGIC.request},
		        {"int": memc.constants.opcodes.FLUSH},
		        {"int16": 0},
		        {"int": 0},
		        {"int": 0},
		        {"int16": 0},
		        {"int32": 8},
		        {"int32": _opaque},
		        {"int32": 0},
		        {"int32": 0},
				{"int32": expiration}
			], encoder, 0);
		}
		else {
			var encoder = new Buffer(24);
			var size = bin.pack([
		        {"int": memc.constants.general.MAGIC.request},
		        {"int": memc.constants.opcodes.FLUSH},
		        {"int16": 0},
		        {"int": 0},
		        {"int": 0},
		        {"int16": 0},
		        {"int32": 0},
		        {"int32": _opaque},
		        {"int32": 0},
		        {"int32": 0}
			], encoder, 0);
		}
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}

	_self.flushq = function(expiration, cb) {
		if(expiration) {
			var encoder = new Buffer(24 + 8);
			var size = bin.pack([
		        {"int": memc.constants.general.MAGIC.request},
		        {"int": memc.constants.opcodes.FLUSHQ},
		        {"int16": 0},
		        {"int": 0},
		        {"int": 0},
		        {"int16": 0},
		        {"int32": 8},
		        {"int32": _opaque},
		        {"int32": 0},
		        {"int32": 0},
				{"int32": expiration}
			], encoder, 0);
		}
		else {
			var encoder = new Buffer(24);
			var size = bin.pack([
		        {"int": memc.constants.general.MAGIC.request},
		        {"int": memc.constants.opcodes.FLUSHQ},
		        {"int16": 0},
		        {"int": 0},
		        {"int": 0},
		        {"int16": 0},
		        {"int32": 0},
		        {"int32": _opaque},
		        {"int32": 0},
		        {"int32": 0}
			], encoder, 0);
		}
		_reqs["K"+(_opaque++)] = cb;
		writeSocket(connection, encoder);
	}
};
Example #25
0
/* TCP ROC Client interface, as it's the most usual use-case. */
function Client () {
  if (!(this instanceof Client)) return new Client();
  net.Stream.call(this);
}
Example #26
0
// Verify that msgpack.Stream can pass multiple messages around as expected.

var assert = require('assert');
var msgpack = require('msgpack');
var net = require('net');
var netBindings = process.binding('net');
var sys = require('sys');

var MSGS = [
    [1, 2, 3],
    {'a' : 1, 'b' : 2},
    {'test' : [1, 'a', 3]}
];
var fds = netBindings.socketpair();

var is = new net.Stream(fds[0]);
var ims = new msgpack.Stream(is);
var os = new net.Stream(fds[1]);
var oms = new msgpack.Stream(os);

var msgsReceived = 0;
ims.addListener('msg', function(m) {
    assert.deepEqual(m, MSGS[msgsReceived]);

    if (++msgsReceived == MSGS.length) {
        is.end();
        os.end();
    }
});
is.resume();
Example #27
0
	connection.addListener("timeout", function() {
		connection.end();
	});
Example #28
0
/**
 * Interact with FPM
 *
 * This function is used to interact with the FastCGI protocol
 * using net.Stream and the fastcgi module.
 *
 * We pass the request, the response, some params and some options
 * that we then use to serve the response to our client.
 *
 * @param object Request	The HTTP Request object.
 * @param object Response The HTTP Response object to use.
 * @param array	Params	 A list of parameters to pass to FCGI
 * @param array	options	A list of options like the port of the fpm server.
 *
 * @return void
 */
function server(request, response, params, options) {
		var connection = new net.Stream();
		connection.setNoDelay(true);

		var writer = null;
		var parser = null;

		var header = {
				"version": fastcgi.constants.version,
				"type": FCGI_BEGIN,
				"recordId": 0,
				"contentLength": 0,
				"paddingLength": 0
		};
		var begin = {
				"role": FCGI_RESPONDER,
				"flags": 0
		};

		function sendRequest (connection) {
				header.type = FCGI_BEGIN;
				header.contentLength = 8;
				writer.writeHeader(header);
				writer.writeBegin(begin);
				connection.write(writer.tobuffer());

				header.type = FCGI_PARAMS;
				header.contentLength = fastcgi.getParamLength(params);
				writer.writeHeader(header);
				writer.writeParams(params);
				connection.write(writer.tobuffer());

				header.type = FCGI_STDOUT;
				writer.writeHeader(header);
				connection.write(writer.tobuffer());

				connection.end();
		};

		connection.ondata = function (buffer, start, end) {
				parser.execute(buffer, start, end);
		};

		connection.addListener("connect", function() {
				writer = new fastcgi.writer();
				parser = new fastcgi.parser();

				body="";

				parser.onRecord = function(record) {
						if (record.header.type == FCGI_STDOUT) {
								body = record.body;

								parts = body.split("\r\n\r\n");

								headers = parts[0];
								headerParts = headers.split("\r\n");

								body = parts[1];

								var responseStatus = 200;

								headers = [];
								try {
										for(i in headerParts) {
												header = headerParts[i].split(': ');
												if (header[0].indexOf('Status') >= 0) {
														responseStatus = header[1].substr(0, 3);
														continue;
												}

												headers.push([header[0], header[1]]);
										}
								} catch (err) {
										//console.log(err);
								}

								headers.push(['X-Server' , 'Node.js-' + process.version]);
								response.writeHead(responseStatus, headers);
								response.end(body);

								console.log('	--> Request Response Status Code: "' + responseStatus + '"');
						}
				};

				parser.onHeader = function(header) {
						body = '';
				};

				parser.onError = function(err) {
						//console.log(err);
				};

				sendRequest(connection);
		});

		connection.addListener("close", function() {
				connection.end();
		});

		connection.addListener("error", function(err) {
				sys.puts(sys.inspect(err.stack));
				connection.end();
		});

		connection.connect(options.fcgi.port, options.fcgi.host);
}
Example #29
0
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

require('../common');
const assert = require('assert');
const net = require('net');

const s = new net.Stream();

// test that destroy called on a stream with a server only ever decrements the
// server connection count once

s.server = new net.Server();
s.server.connections = 10;
s._server = s.server;

assert.strictEqual(s.server.connections, 10);
s.destroy();
assert.strictEqual(s.server.connections, 9);
s.destroy();
assert.strictEqual(s.server.connections, 9);

const SIZE = 2E6;
Example #30
0
	connection.addListener("close", function(had_error) {
		connection.end();
	});