From 34934a3aa881871fcf86b9c0a474fa55d3d4613b Mon Sep 17 00:00:00 2001 From: fischer Date: Thu, 19 Dec 2013 06:50:22 +0100 Subject: [PATCH 1/3] Fixed service crash if some client uses a ivalid / unkown function code --- client.js | 16 +- modbus-stack.js | 10 +- modbus-stack.js~ | 278 +++++++++++ node_modules/bufferlist/LICENSE | 4 + node_modules/bufferlist/README.markdown | 71 +++ node_modules/bufferlist/binary.js | 440 ++++++++++++++++++ node_modules/bufferlist/bufferlist.js | 162 +++++++ node_modules/bufferlist/examples/binary.js | 56 +++ node_modules/bufferlist/examples/hackneyed.js | 16 + .../bufferlist/examples/simple_binary.js | 22 + .../bufferlist/examples/simple_bufferlist.js | 13 + node_modules/bufferlist/package.json | 34 ++ node_modules/bufferlist/test/advance.js | 25 + node_modules/bufferlist/test/binary.js | 86 ++++ node_modules/bufferlist/test/binary_assign.js | 73 +++ .../bufferlist/test/binary_endianness.js | 243 ++++++++++ node_modules/bufferlist/test/binary_event.js | 67 +++ node_modules/bufferlist/test/binary_into.js | 49 ++ node_modules/bufferlist/test/binary_jump.js | 55 +++ node_modules/bufferlist/test/binary_loop.js | 115 +++++ node_modules/bufferlist/test/client_server.js | 48 ++ node_modules/bufferlist/test/event.js | 46 ++ node_modules/bufferlist/test/join.js | 26 ++ node_modules/bufferlist/test/take.js | 39 ++ node_modules/put/LICENSE | 21 + node_modules/put/README.md | 57 +++ node_modules/put/examples/buf.js | 12 + node_modules/put/examples/stream.js | 9 + node_modules/put/index.js | 100 ++++ node_modules/put/package.json | 36 ++ node_modules/put/test/buf.js | 70 +++ node_modules/put/test/c/ftoi | Bin 0 -> 4632 bytes node_modules/put/test/c/ftoi.c | 7 + node_modules/put/test/c/itof | Bin 0 -> 4616 bytes node_modules/put/test/c/itof.c | 7 + node_modules/put/test/float.js_ | 9 + node_modules/put/test/stream.js | 28 ++ node_modules/stream-stack/.npmignore | 1 + node_modules/stream-stack/API.md | 63 +++ node_modules/stream-stack/LICENSE | 22 + node_modules/stream-stack/README.md | 65 +++ node_modules/stream-stack/package.json | 35 ++ node_modules/stream-stack/stream-stack.js | 209 +++++++++ .../stream-stack/test/test-custom-edit.js | 28 ++ .../test/test-fakeDuplexStream.js | 78 ++++ .../stream-stack/test/test-parent-emits.js | 66 +++ .../stream-stack/test/test-proxy-events.js | 75 +++ .../stream-stack/test/test-topStream.js | 22 + node_modules/stream-stack/util.js | 61 +++ package.json | 22 +- server.js | 50 +- 51 files changed, 3116 insertions(+), 31 deletions(-) create mode 100644 modbus-stack.js~ create mode 100644 node_modules/bufferlist/LICENSE create mode 100644 node_modules/bufferlist/README.markdown create mode 100644 node_modules/bufferlist/binary.js create mode 100644 node_modules/bufferlist/bufferlist.js create mode 100644 node_modules/bufferlist/examples/binary.js create mode 100644 node_modules/bufferlist/examples/hackneyed.js create mode 100644 node_modules/bufferlist/examples/simple_binary.js create mode 100644 node_modules/bufferlist/examples/simple_bufferlist.js create mode 100644 node_modules/bufferlist/package.json create mode 100644 node_modules/bufferlist/test/advance.js create mode 100644 node_modules/bufferlist/test/binary.js create mode 100644 node_modules/bufferlist/test/binary_assign.js create mode 100644 node_modules/bufferlist/test/binary_endianness.js create mode 100644 node_modules/bufferlist/test/binary_event.js create mode 100644 node_modules/bufferlist/test/binary_into.js create mode 100644 node_modules/bufferlist/test/binary_jump.js create mode 100644 node_modules/bufferlist/test/binary_loop.js create mode 100644 node_modules/bufferlist/test/client_server.js create mode 100644 node_modules/bufferlist/test/event.js create mode 100644 node_modules/bufferlist/test/join.js create mode 100644 node_modules/bufferlist/test/take.js create mode 100644 node_modules/put/LICENSE create mode 100644 node_modules/put/README.md create mode 100644 node_modules/put/examples/buf.js create mode 100644 node_modules/put/examples/stream.js create mode 100644 node_modules/put/index.js create mode 100644 node_modules/put/package.json create mode 100644 node_modules/put/test/buf.js create mode 100644 node_modules/put/test/c/ftoi create mode 100644 node_modules/put/test/c/ftoi.c create mode 100644 node_modules/put/test/c/itof create mode 100644 node_modules/put/test/c/itof.c create mode 100644 node_modules/put/test/float.js_ create mode 100644 node_modules/put/test/stream.js create mode 100644 node_modules/stream-stack/.npmignore create mode 100644 node_modules/stream-stack/API.md create mode 100644 node_modules/stream-stack/LICENSE create mode 100644 node_modules/stream-stack/README.md create mode 100644 node_modules/stream-stack/package.json create mode 100644 node_modules/stream-stack/stream-stack.js create mode 100644 node_modules/stream-stack/test/test-custom-edit.js create mode 100644 node_modules/stream-stack/test/test-fakeDuplexStream.js create mode 100644 node_modules/stream-stack/test/test-parent-emits.js create mode 100644 node_modules/stream-stack/test/test-proxy-events.js create mode 100644 node_modules/stream-stack/test/test-topStream.js create mode 100644 node_modules/stream-stack/util.js diff --git a/client.js b/client.js index be63b56..0ee999a 100644 --- a/client.js +++ b/client.js @@ -50,7 +50,7 @@ Client.REQUESTS = { 3: putTwoWord16be, // READ_INPUT_REGISTERS 4: putTwoWord16be, - // WRITE_SINGLE_COIL + // WRITE_SINGLE_REGISTER: 5: function(address, value) { if (typeof value !== 'boolean') throw new Error('"Write Single Coil" expects a \'boolean\' value'); return putTwoWord16be(address, value ? 0xff00 : 0x0000); @@ -69,17 +69,5 @@ Client.RESPONSES = { rtn.push(binary.end().vars.val); } return rtn; - }, - // WRITE_SINGLE_COIL - 5: function(bufferlist) { - var rtn = []; - var binary = Binary(bufferlist) - .getWord8('byteLength').end(); - rtn.byteLength = binary.vars.byteLength; - for (var i=0, l=binary.vars.byteLength/2; i= 1 && this.bufferlist.length >= (this.requestHeader.length-2)) { // We have the complete request. if (!server.REQUESTS[this.functionCode]) { - return this.emit('error', new Error('"REQUESTS['+this.functionCode+']" in "server.js" is not implemented!')); + //this._gotRequest = true; + //this.writeException(1); + //return this.emit('error', new Error('"REQUESTS['+this.functionCode+']" in "server.js" is not implemented!')); + + console.log(JSON.stringify(this.requestHeader)); + this.request = this.requestHeader; + this._gotRequest = true; + return this.emit('not_implemented', this.request); } try { this.request = server.REQUESTS[this.functionCode].call(this, this.bufferlist); @@ -206,6 +213,7 @@ ModbusResponseStack.prototype._onData = function(chunk) { //console.log('bufferlist.length: ' + this.bufferlist.length); this._gotRequest = true; this.emit('request', this.request); + //console.log("modbus-stack.js" +JSON.stringify(this.request)); } } diff --git a/modbus-stack.js~ b/modbus-stack.js~ new file mode 100644 index 0000000..4b12db5 --- /dev/null +++ b/modbus-stack.js~ @@ -0,0 +1,278 @@ +var StreamStack = require('stream-stack').StreamStack; +var Put = require('put'); +var BufferList = require('bufferlist').BufferList; +var Binary = require('bufferlist/binary').Binary; +var inherits = require('util').inherits; +var client = require('./client'); +var server = require('./server'); +var slice = Array.prototype.slice; + +// The byte length of the "MODBUS Application Protocol" header. +const MBAP_LENGTH = 7; + +// The byte length of the "MODBUS Function Code". +const FUNCTION_CODE_LENGTH = 1; + +// An exception response from a MODBUS slave (server) will have +// the high-bit (0x80) set on it's function code. +const EXCEPTION_BIT = 1 << 7; + +// If it's an exception response, then the next byte will be one +// these exception codes, indicating the reason for the failure. +exports.EXCEPTION_CODES = { + 1 : 'Illegal Function', + 2 : 'Illegal Data Address', + 3 : 'Illegal Data Value', + 4 : 'Slave Device Failure', + 5 : 'Acknowledge', + 6 : 'Slave Device Busy', + 8 : 'Memory Parity Error', + 10: 'Gateway Path Unavailable', + 11: 'Gateway Target Path Failed to Respond' +}; + +// Each of the function codes has a potentially different body payload +// and potentially different parameters to send. Each function code needs +// a 'request' and 'response' parser in the "client.js" and "server.js" files. +exports.FUNCTION_CODES = { + READ_COILS: 1, + READ_DISCRETE_INPUTS: 2, + READ_HOLDING_REGISTERS: 3, + READ_INPUT_REGISTERS: 4, + WRITE_SINGLE_COIL: 5, + WRITE_SINGLE_REGISTER: 6, + READ_EXCEPTION_STATUS: 7, // Serial Line only + DIAGNOSTICS: 8, // Serial Line only + PROGRAM_484: 9, + POLL_484: 10, + GET_COMM_EVENT_COUNTER: 11,// Serial Line only + GET_COMM_EVENT_LOG: 12,// Serial Line only + PROGRAM_CONTROLLER: 13, + POLL_CONTROLLER: 14, + WRITE_MULTIPLE_COILS: 15, + WRITE_MULTIPLE_REGISTERS: 16, + REPORT_SLAVE_ID: 17,// Serial Line only + PROGRAM_884_M84: 18, + RESET_COMM_LINK: 19, + READ_FILE_RECORD: 20, + WRITE_FILE_RECORD: 21, + MASK_WRITE_REGISTER: 22, + READ_WRITE_MULTIPLE_REGISTERS:23, + READ_FIFO_QUEUE: 24, + ENCAPSULATED_INFERFACE_TRANSPORT:43 +}; + +function ModbusRequestStack(stream) { + StreamStack.call(this, stream, { + data: this._onData + }); + this.bufferlist = new BufferList(); + if (this.stream._reqNum) { + this.stream._reqNum++; + } else { + this.stream._reqNum = 1; + } +} +inherits(ModbusRequestStack, StreamStack); +exports.ModbusRequestStack = ModbusRequestStack; + +// The 'version' of the MODBUS protocol. Only version 0 is defined. +ModbusRequestStack.prototype.protocolVersion = 0; + +// The unit identifier to request. This is usually important for +// serial lines, not so much over TCP. +ModbusRequestStack.prototype.unitIdentifier = 1; + +// Make a MODBUS request for a given 'function code'. +ModbusRequestStack.prototype.request = function(functionCode) { + if (!client.REQUESTS[functionCode]) { + throw new Error('"REQUESTS['+functionCode+']" in "client.js" is not implemented!'); + } + this.functionCode = functionCode; + var argsLen = arguments.length; + if (argsLen > 1) { + var callback = arguments[argsLen-1]; + if (typeof(callback) == 'function') { + this.on('error', callback); + this.on('response', function(res) { + callback(null, res); + }); + } else { callback = null; } + } + var args = slice.call(arguments, 1, argsLen-(callback?1:0)); + try { + var pdu = client.REQUESTS[functionCode].apply(this, args); + } catch(e) { + this.emit('error', e); + return false; + } + var buf = Put() + .word16be(this.stream._reqNum) + .word16be(this.protocolVersion) + .word16be(pdu.length+2) + .word8(this.unitIdentifier) + .word8(functionCode) + .put(pdu) + .buffer(); + return this.stream.write(buf); +} + +ModbusRequestStack.prototype._onData = function(chunk) { + if (chunk) { + this.bufferlist.push(chunk); + //console.log(chunk); + } + if (!this.responseHeader && this.bufferlist.length >= MBAP_LENGTH) { + this.responseHeader = readMBAP(this.bufferlist); + // Re-check the bufferlist to see if we have the rest of the response already + this._onData(); + } else if (!this._resFunctionCode && this.responseHeader && this.bufferlist.length >= 1) { + // Get the function code + this._resFunctionCode = readFunctionCode(this.bufferlist); + //console.log(this._resFunctionCode); + this._onData(); + } else if (this.responseHeader && this._resFunctionCode >= 1 && this.bufferlist.length >= (this.responseHeader.length-2)) { + // We have the complete response. + if (this._resFunctionCode & EXCEPTION_BIT) { + // An exception was returned as the response! + var code = this.bufferlist.take(1)[0]; + this.bufferlist.advance(1); + var err = new Error(exports.EXCEPTION_CODES[code]); + err.errno = code; + this.emit('error', err); + } else { + if (!client.RESPONSES[this._resFunctionCode]) { + return this.emit('error', new Error('"RESPONSES['+this._resFunctionCode+']" in "client.js" is not implemented!')); + } + try { + var response = client.RESPONSES[this._resFunctionCode].call(this, this.bufferlist); + } catch(e) { + return this.emit('error', e); + } + this.bufferlist.advance(this.responseHeader.length-2); + // Explicitly set the 'functionCode' property. + response.functionCode = this._resFunctionCode; + delete this._resFunctionCode; + // Modbus request/response complete; invoke callbacks and cleanup! + this.emit('response', response); + } + this.cleanup(); + } +} + + + +function ModbusResponseStack(stream) { + StreamStack.call(this, stream, { + data: this._onData + }); + this.bufferlist = new BufferList(); +} +inherits(ModbusResponseStack, StreamStack); +exports.ModbusResponseStack = ModbusResponseStack; + +ModbusResponseStack.prototype._onData = function(chunk) { + if (chunk) { + this.bufferlist.push(chunk); + //console.log(chunk); + } + if (!this.requestHeader && this.bufferlist.length >= MBAP_LENGTH) { + this.requestHeader = readMBAP(this.bufferlist); + //console.log(this.requestHeader); + // Re-check the bufferlist to see if we have the rest of the request + // already (we probably do, it's usually sent in the same packet). + this._onData(); + } else if (!this.functionCode && this.requestHeader && this.bufferlist.length >= 1) { + // Get the function code + this.functionCode = readFunctionCode(this.bufferlist); + //console.log(this.functionCode); + this._onData(); + } else if (this.requestHeader && this.functionCode >= 1 && this.bufferlist.length >= (this.requestHeader.length-2)) { + // We have the complete request. + if (!server.REQUESTS[this.functionCode]) { + return this.emit('error', new Error('"REQUESTS['+this.functionCode+']" in "server.js" is not implemented!')); + } + try { + this.request = server.REQUESTS[this.functionCode].call(this, this.bufferlist); + } catch(e) { + return this.emit('error', e); + } + this.request.functionCode = this.functionCode; + for (var key in this.requestHeader) { + this.request[key] = this.requestHeader[key]; + } + delete this.request.length; + this.bufferlist.advance(this.requestHeader.length-2); + //console.log('bufferlist.length: ' + this.bufferlist.length); + this._gotRequest = true; + this.emit('request', this.request); + //console.log(JSON.stringify(this.request)); + } +} + +// Sends back the response after receiving a request. +ModbusResponseStack.prototype.writeResponse = function() { + if (!this._gotRequest) { + throw new Error('Can\'t call "writeResponse" until after the "request" event'); + } + if (!server.RESPONSES[this.functionCode]) { + throw new Error('"RESPONSES['+this.functionCode+']" in "server.js" is not implemented!'); + } + try { + var pdu = server.RESPONSES[this.functionCode].apply(this, arguments); + } catch(e) { + this.emit('error', e); + return false; + } + var rtn = this.stream.write(Put() + .word16be(this.request.transactionId) + .word16be(this.request.protocolVersion) + .word16be(pdu.length+2) + .word8(this.request.unitIdentifier) + .word8(this.functionCode) + .put(pdu) + .buffer()); + this.cleanup(); + return rtn; +} + +// Sends back an exception response after receiving a request. +ModbusResponseStack.prototype.writeException = function(exceptionCode) { + if (!this._gotRequest) { + throw new Error('Can\'t call "writeException" until after the "request" event'); + } + var rtn = this.stream.write(Put() + .word16be(this.request.transactionId) + .word16be(this.request.protocolVersion) + .word16be(3) + .word8(this.request.unitIdentifier) + .word8(this.functionCode | EXCEPTION_BIT) + .word8(exceptionCode) + .buffer()); + this.cleanup(); + return rtn; +} + + +// Reads the "MODBUS Application Protocol" header from the given bufferlist, +// and return a object with 'transactionId', 'protocolVersion', 'length', and +// 'unitIdentifier' properties (standard for both client and server). +function readMBAP(bufferlist) { + var mbap = Binary(bufferlist) + .getWord16be('transactionId') + .getWord16be('protocolVersion') + .getWord16be('length') + .getWord8('unitIdentifier') + .end().vars; + bufferlist.advance(MBAP_LENGTH); + return mbap; +} +exports.readMBAP = readMBAP; + +// Reads the "MODBUS Function Code", which comes immediately after the MBAP. +function readFunctionCode(bufferlist) { + var rtn = bufferlist.take(FUNCTION_CODE_LENGTH)[0]; + bufferlist.advance(FUNCTION_CODE_LENGTH); + return rtn; +} +exports.readFunctionCode = readFunctionCode; diff --git a/node_modules/bufferlist/LICENSE b/node_modules/bufferlist/LICENSE new file mode 100644 index 0000000..0471ea3 --- /dev/null +++ b/node_modules/bufferlist/LICENSE @@ -0,0 +1,4 @@ +Copyright 2010 James Halliday (mail@substack.net) + +This project is free software released under the MIT license: +http://www.opensource.org/licenses/mit-license.php diff --git a/node_modules/bufferlist/README.markdown b/node_modules/bufferlist/README.markdown new file mode 100644 index 0000000..7be7152 --- /dev/null +++ b/node_modules/bufferlist/README.markdown @@ -0,0 +1,71 @@ +BufferList +========== +BufferList provides an interface to treat a linked list of buffers as a single +stream. This is useful for events that produce a many small Buffers, such as +network streams. + +Installation +============ +Install using npm: + npm install bufferlist + +Or, check out the repository and have npm link to your development copy. This +is useful for developing the library, and is necessary when running the tests, +since they refer to the installed names of the library files. + git clone http://github.com/substack/node-bufferlist.git + cd node-bufferlist + npm link . + +Simple Bufferlist Example +========================= + + #!/usr/bin/env node + var sys = require('sys'); + var Buffer = require('buffer').Buffer; + var BufferList = require('bufferlist').BufferList; + + var b = new BufferList; + ['abcde','xyz','11358'].forEach(function (s) { + var buf = new Buffer(s.length); + buf.write(s); + b.push(buf); + }); + + sys.puts(b.take(10)); // abcdexyz11 + +Binary +====== +This distribution also contains a Binary module for parsing these bufferlists. + +Simple Binary Example +===================== + + #!/usr/bin/env node + + var sys = require('sys'); + var Buffer = require('buffer').Buffer; + var BufferList = require('bufferlist').BufferList; + var Binary = require('bufferlist/binary').Binary; + + var bufferList = new BufferList; + var binary = Binary(bufferList) + .getWord16be('xLen') + .getBuffer('xs', 'xLen') + .tap(function (vars) { + vars.moo = 'xs:' + vars.xLen + ':' + vars.xs; + }) + .end() + ; + + var buf = new Buffer(6); + buf.write('\x00\x04meow', 'binary'); + bufferList.push(buf); + + sys.puts(binary.vars.moo); // xs:4:meow + +See Also +======== +See the examples/ directory for more involved examples. + +See http://github.com/substack/node-rfb for a practical application of this +distribution. diff --git a/node_modules/bufferlist/binary.js b/node_modules/bufferlist/binary.js new file mode 100644 index 0000000..ab58b33 --- /dev/null +++ b/node_modules/bufferlist/binary.js @@ -0,0 +1,440 @@ +var BufferList = require('bufferlist'); +var EventEmitter = require('events').EventEmitter; +var util = require('util'); + +module.exports = Binary; +module.exports.Binary = Binary; // backwards compatibility + +Binary.prototype = new EventEmitter; +function Binary(buffer) { + if (!(this instanceof Binary)) return new Binary(buffer); + var self = this; + + this.vars = {}; + this.offset = 0; + this.actions = []; + this.parent = null; + + // an explicit end loads all the actions before any evaluation happens + this.end = function () { + if (buffer.listeners('write').indexOf(update) < 0) { + buffer.on('write', update); + } + update(); + return this; + }; + + // Signify to the parent that processing should stop. + this.exit = function () { + this.pushAction({ + ready : true, + action : function () { + this.actions = []; + if (this.parent) this.parent.actions = []; + }, + }); + return this; + }; + + function update () { + var action = self.actions[0]; + if (!action) { + buffer.removeListener('write', update); + self.emit('end', self.vars); + } + else if (action.ready.call(self, self.vars)) { + self.actions.shift(); + + if (action.context == false) { + action.action.call(self, self.vars); + self.end(); + } + else { + buffer.removeListener('write', update); + + var child = new Binary(buffer); + child.vars = self.vars; + child.parent = self; + child.offset = self.offset; + + child.on('end', function () { + self.offset = child.offset; + buffer.on('write', update); + self.end(); + }); + + action.action.call(child, child.vars); + child.end(); + } + } + } + + this.pushAction = function (action) { + if (!action) throw "Action not specified"; + var ready = { + 'function' : action.ready, + 'boolean' : function () { return action.ready }, + }[typeof(action.ready)]; + if (!ready) throw "Unknown action.ready type"; + this.actions.push({ + 'action' : action.action, + 'ready' : ready, + 'context' : action.context || false, + }); + }; + + this.flush = function () { + this.pushAction({ + ready : true, + action : function () { + buffer.advance(this.offset); + this.offset = 0; + }, + }); + return this; + }; + + this.skip = function (bytes) { + this.pushAction({ + ready : true, + action : function () { + this.offset += bytes; + }, + }); + return this; + }; + + this.tap = function (f) { + this.pushAction({ + ready : true, + context : true, + action : function () { + f.call(this, this.vars); + }, + }); + return this; + }; + + this.when = function (v1, v2, f) { + var f1 = typeof(v1) == 'string' + ? function (vars) { return lookup(this,v1) } + : function (vars) { return v1 } + ; + var f2 = typeof(v2) == 'string' + ? function (vars) { return lookup(this,v2) } + : function (vars) { return v2 } + ; + return this.tap(function () { + if (f1.call(this,this.vars) == f2.call(this,this.vars)) { + f.call(this, this.vars); + } + }); + }; + + this.unless = function (v1, v2, f) { + var f1 = typeof(v1) == 'string' + ? function (vars) { return lookup(this,v1) } + : function (vars) { return v1 } + ; + var f2 = typeof(v2) == 'string' + ? function (vars) { return lookup(this,v2) } + : function (vars) { return v2 } + ; + return this.tap(function () { + if (f1.call(this,this.vars) != f2.call(this,this.vars)) { + f.call(this, this.vars); + } + }); + }; + + this.repeat = function (n, f) { + var nf = typeof(n) == 'string' + ? function (vars) { return lookup(this,n) } + : function (vars) { return n } + ; + this.pushAction({ + ready : true, + context : true, + action : function () { + var nn = nf.call(this, this.vars); + for (var i = 0; i < nn; i++) { + f.call(this, this.vars, i); + } + }, + }); + return this; + }; + + this.forever = function (f) { + self.foreverfunc = f; + self.foreveraction = { + ready : true, + context : true, + action : function () { + self.foreverfunc.call(this, this.vars); + self.pushAction(self.foreveraction); + }, + }; + this.pushAction(self.foreveraction); + return this; + }; + + // assign immediately + function assign (self, key, value) { + visit( + self, key instanceof Array ? key : [key], + function (v,k) { v[k] = value } + ); + } + + function lookup (self) { + var args = [].slice.call(arguments, 1); + return visit(self, args, function (v,k) { return v[k] }); + } + + function visit(self, args, f) { + var keys = args.reduce(function (acc,x) { + return acc.concat(x.split('.')) + },[]) + ; + + var obj = self.vars; + keys.slice(0,-1).forEach(function (k) { + if (!obj[k]) obj[k] = {}; + obj = obj[k]; + }); + + return f(obj, keys.slice(-1)[0]); + } + + // Assign into a variable. All but the last argument make up the key, which + // may describe a deeply nested address. If the last argument is a: + // * function - assign the variables from the inner chain + // * string - assign from the key name + // * number - assign from this value + this.into = function () { + var args = [].concat.apply([],arguments); + var keys = args.slice(0,-1); + var fv = args.slice(-1)[0]; + + return this.tap(function (vars) { + if (typeof fv == 'function') { + var topVars = this.vars; + this.vars = {}; + fv.call(this, this.vars); + this.pushAction({ + ready : true, + action : function () { + var localVars = this.vars; + this.vars = topVars; + assign(this, keys, localVars); + } + }); + } + else if (typeof fv == 'string') { + assign(this, keys, lookup(this,fv)); + } + else if (typeof fv == 'number') { + assign(this, keys, fv); + } + else { + throw TypeError( + 'Last argument to .into must be a string, number, ' + + 'or a function, not a "' + typeof fv + '".' + + 'Value supplied: ' + util.inspect(fv) + ); + } + }); + }; + + function get (opts) { + var into = [].reduce.call(opts.into, function (acc,x) { + return acc.concat(x); + }, []); + + this.pushAction({ + ready : function () { + return buffer.length - this.offset >= opts.bytes; + }, + action : function () { + var data = buffer.join(this.offset, this.offset + opts.bytes); + this.offset += opts.bytes; + var decodeLittleEndian = opts.signed ? decodeLEs : decodeLE; + var decodeBigEndian = opts.signed ? decodeBEs : decodeBE; + assign(this, into, + opts.endian && opts.endian == 'little' + ? decodeLittleEndian(data) + : decodeBigEndian(data) + ); + + }, + }); + return this; + }; + + this.getWord8 = function () { + return get.call( + this, { into : arguments, bytes : 1 } + ); + }; + + this.getWord16be = function () { + return get.call( + this, { into : arguments, bytes : 2, endian : 'big' } + ); + }; + + this.getWord16bes = function () { + return get.call( + this, { into : arguments, bytes : 2, endian : 'big', signed : true } + ); + } + + this.getWord16le = function () { + return get.call( + this, { into : arguments, bytes : 2, endian : 'little' } + ); + }; + + this.getWord16les = function () { + return get.call( + this, { into : arguments, bytes : 2, endian : 'little', + signed : true } + ); + } + + this.getWord32be = function () { + return get.call( + this, { into : arguments, bytes : 4, endian : 'big' } + ); + }; + + this.getWord32bes = function () { + return get.call( + this, { into : arguments, bytes : 4, endian : 'big', + signed : true } + ); + }; + + this.getWord32le = function () { + return get.call( + this, { into : arguments, bytes : 4, endian : 'little' } + ); + }; + + this.getWord32les = function () { + return get.call( + this, { into : arguments, bytes : 4, endian : 'little', + signed: true } + ); + }; + + this.getWord64be = function () { + return get.call( + this, { into : arguments, bytes : 8, endian : 'big' } + ); + }; + + this.getWord64bes = function () { + return get.call( + this, { into : arguments, bytes : 8, endian : 'big', + signed : true } + ); + }; + + this.getWord64le = function () { + return get.call( + this, { into : arguments, bytes : 8, endian : 'little' } + ); + }; + + this.getWord64les = function () { + return get.call( + this, { into : arguments, bytes : 8, endian : 'little', + signed : true } + ); + }; + + this.getBuffer = function () { + var args = [].concat.apply([],arguments); + // flatten :into so .getBuffer(['foo','bar','baz'],10) + // and .getBuffer('foo','bar','baz',10) both work + var into = args.slice(0,-1).reduce(function f (acc,x) { + return acc.concat( + x instanceof Array ? x.reduce(f) : x.split('.') + ); + }, []); + var length = args.slice(-1)[0]; + var lengthF; + + if (typeof(length) == 'string') { + var s = length; + lengthF = function (vars) { return lookup(this,s) }; + } + else if (typeof(length) == 'number') { + var s = length; + lengthF = function (vars) { return s }; + } + else if (length instanceof Function) { + lengthF = length; + } + else { + throw TypeError( + 'Last argument to getBuffer (length) must be a string, number, ' + + 'or a function, not a "' + typeof(length) + '".' + + 'Value supplied: ' + util.inspect(length) + ); + } + + this.pushAction({ + ready : function () { + var s = lengthF.call(this,this.vars); + return s && buffer.length - this.offset >= s; + }, + action : function () { + var s = lengthF.call(this,this.vars); + var data = buffer.join(this.offset, this.offset + s); + this.offset += s; + assign(this, into, data); + }, + }); + return this; + }; +} + +// convert byte strings to little endian numbers +function decodeLE (bytes) { + var acc = 0; + for (var i = 0; i < bytes.length; i++) { + acc += Math.pow(256,i) * bytes[i]; + } + return acc; +} + +// convert byte strings to big endian numbers +function decodeBE (bytes) { + var acc = 0; + for (var i = 0; i < bytes.length; i++) { + acc += Math.pow(256, bytes.length - i - 1) * bytes[i]; + } + return acc; +} + +// convert byte strings to signed big endian numbers +function decodeBEs (bytes) { + var val = decodeBE(bytes); + if ((bytes[0]&0x80) == 0x80) { + val -= Math.pow(256, bytes.length); + } + return val; +} + +// convert byte strings to signed little endian numbers +function decodeLEs (bytes) { + var val = decodeLE(bytes); + if ((bytes[bytes.length-1]&0x80) == 0x80) { + val -= Math.pow(256, bytes.length); + } + return val; +} + diff --git a/node_modules/bufferlist/bufferlist.js b/node_modules/bufferlist/bufferlist.js new file mode 100644 index 0000000..fafc6a6 --- /dev/null +++ b/node_modules/bufferlist/bufferlist.js @@ -0,0 +1,162 @@ +// bufferlist.js +// Treat a linked list of buffers as a single variable-size buffer. +var Buffer = require('buffer').Buffer; +var EventEmitter = require('events').EventEmitter; + +module.exports = BufferList; +module.exports.BufferList = BufferList; // backwards compatibility + +function BufferList(opts) { + if (!(this instanceof BufferList)) return new BufferList(opts); + EventEmitter.call(this); + var self = this; + + if (typeof(opts) == 'undefined') opts = {}; + + // default encoding to use for take(). Leaving as 'undefined' + // makes take() return a Buffer instead. + self.encoding = opts.encoding; + + // constructor to use for Buffer-esque operations + self.construct = opts.construct || Buffer; + + var head = { next : null, buffer : null }; + var last = { next : null, buffer : null }; + + // length can get negative when advanced past the end + // and this is the desired behavior + var length = 0; + self.__defineGetter__('length', function () { + return length; + }); + + // keep an offset of the head to decide when to head = head.next + var offset = 0; + + // Write to the bufferlist. Emits 'write'. Always returns true. + self.write = function (buf) { + if (!head.buffer) { + head.buffer = buf; + last = head; + } + else { + last.next = { next : null, buffer : buf }; + last = last.next; + } + length += buf.length; + self.emit('write', buf); + return true; + }; + + self.end = function (buf) { + if (buf instanceof Buffer) self.write(buf); + }; + + // Push buffers to the end of the linked list. (deprecated) + // Return this (self). + self.push = function () { + var args = [].concat.apply([], arguments); + args.forEach(self.write); + return self; + }; + + // For each buffer, perform some action. + // If fn's result is a true value, cut out early. + // Returns this (self). + self.forEach = function (fn) { + if (!head.buffer) return new self.construct(0); + + if (head.buffer.length - offset <= 0) return self; + var firstBuf = new self.construct(head.buffer.length - offset); + head.buffer.copy(firstBuf, 0, offset, head.buffer.length); + + var b = { buffer : firstBuf, next : head.next }; + + while (b && b.buffer) { + var r = fn(b.buffer); + if (r) break; + b = b.next; + } + + return self; + }; + + // Create a single Buffer out of all the chunks or some subset specified by + // start and one-past the end (like slice) in bytes. + self.join = function (start, end) { + if (!head.buffer) return new self.construct(0); + if (start == undefined) start = 0; + if (end == undefined) end = self.length; + + var big = new self.construct(end - start); + var ix = 0; + self.forEach(function (buffer) { + if (start < (ix + buffer.length) && ix < end) { + // at least partially contained in the range + buffer.copy( + big, + Math.max(0, ix - start), + Math.max(0, start - ix), + Math.min(buffer.length, end - ix) + ); + } + ix += buffer.length; + if (ix > end) return true; // stop processing past end + }); + + return big; + }; + + // Advance the buffer stream by n bytes. + // If n the aggregate advance offset passes the end of the buffer list, + // operations such as .take() will return empty strings until enough data is + // pushed. + // Returns this (self). + self.advance = function (n) { + offset += n; + length -= n; + while (head.buffer && offset >= head.buffer.length) { + offset -= head.buffer.length; + head = head.next + ? head.next + : { buffer : null, next : null } + ; + } + self.emit('advance', n); + return self; + }; + + // Take n bytes from the start of the buffers. + // Returns a string. + // If there are less than n bytes in all the buffers or n is undefined, + // returns the entire concatenated buffer string. + self.take = function (n, encoding) { + if (n == undefined) n = self.length; + else if (typeof n !== 'number') { + encoding = n; + n = self.length; + } + var b = head; + if (!encoding) encoding = self.encoding; + if (encoding) { + var acc = ''; + self.forEach(function (buffer) { + if (n <= 0) return true; + acc += buffer.toString( + encoding, 0, Math.min(n,buffer.length) + ); + n -= buffer.length; + }); + return acc; + } else { + // If no 'encoding' is specified, then return a Buffer. + return self.join(0, n); + } + }; + + // The entire concatenated buffer as a string. + self.toString = function () { + return self.take('binary'); + }; +} +require('util').inherits(BufferList, EventEmitter); diff --git a/node_modules/bufferlist/examples/binary.js b/node_modules/bufferlist/examples/binary.js new file mode 100644 index 0000000..3c52973 --- /dev/null +++ b/node_modules/bufferlist/examples/binary.js @@ -0,0 +1,56 @@ +#!/usr/bin/env node + +var sys = require('sys'); +var net = require('net'); + +var BufferList = require('bufferlist'); +var Binary = require('bufferlist/binary'); + +function parser (sock) { + var bufferList = new BufferList; + sock.addListener('data', function (data) { + bufferList.push(data); + }); + + return Binary(bufferList) + .getWord16be('xLen') + .when('xLen', 0, function (vars) { + this + .getWord32le('msgLen') + .getBuffer('msg', 'msgLen') + .tap(function (vars) { + vars.moo = 'msg:' + vars.msgLen + ':' + vars.msg; + }) + .exit() + ; + }) + .getBuffer('xs', 'xLen') + .tap(function (vars) { + vars.moo = 'xs:' + vars.xLen + ':' + vars.xs; + }) + .end() + ; +} + +function serverSession (port, strings) { + // fire up a server to write the strings when a client connects + var server = net.createServer(function (stream) { + strings.forEach(function (s) { + stream.write(s); + }); + stream.end(); + server.close(); + }); + server.listen(port); + + // connect to the server and parse its output + var client = new net.Stream; + parser(client).addListener('end', function (vars) { + sys.puts(vars.moo); + client.end(); + }); + client.connect(port); +} + +serverSession(20801, ['\x00','\x04m','eow']); +serverSession(20802, ['\x00\x00','\x12\x00\x00\x00happy pur','ring c','ats']); diff --git a/node_modules/bufferlist/examples/hackneyed.js b/node_modules/bufferlist/examples/hackneyed.js new file mode 100644 index 0000000..c53eebb --- /dev/null +++ b/node_modules/bufferlist/examples/hackneyed.js @@ -0,0 +1,16 @@ +#!/usr/bin/env node + +var sys = require('sys'); +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); + +var buf1 = new Buffer(5); buf1.write('abcde'); +var buf2 = new Buffer(3); buf2.write('xyz'); +var buf3 = new Buffer(5); buf3.write('11358'); + +var b = new BufferList; +b.push(buf1,buf2,buf3); + +sys.puts(b.take(10)); // abcdexyz11 +sys.puts(b.take(3)); // abc +sys.puts(b.take(100)); // abcdexyz11358 diff --git a/node_modules/bufferlist/examples/simple_binary.js b/node_modules/bufferlist/examples/simple_binary.js new file mode 100644 index 0000000..ae8a824 --- /dev/null +++ b/node_modules/bufferlist/examples/simple_binary.js @@ -0,0 +1,22 @@ +#!/usr/bin/env node + +var sys = require('sys'); +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); +var Binary = require('bufferlist/binary'); + +var bufferList = new BufferList; +var binary = Binary(bufferList) + .getWord16be('xLen') + .getBuffer('xs', 'xLen') + .tap(function (vars) { + vars.moo = 'xs:' + vars.xLen + ':' + vars.xs; + }) + .end() +; + +var buf = new Buffer(6); +buf.write('\x00\x04meow', 'binary'); +bufferList.push(buf); + +sys.puts(binary.vars.moo); // xs:4:meow diff --git a/node_modules/bufferlist/examples/simple_bufferlist.js b/node_modules/bufferlist/examples/simple_bufferlist.js new file mode 100644 index 0000000..c48ca27 --- /dev/null +++ b/node_modules/bufferlist/examples/simple_bufferlist.js @@ -0,0 +1,13 @@ +#!/usr/bin/env node +var sys = require('sys'); +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); + +var b = new BufferList; +['abcde','xyz','11358'].forEach(function (s) { + var buf = new Buffer(s.length); + buf.write(s); + b.push(buf); +}); + +sys.puts(b.take(10)); // abcdexyz11 diff --git a/node_modules/bufferlist/package.json b/node_modules/bufferlist/package.json new file mode 100644 index 0000000..eda3042 --- /dev/null +++ b/node_modules/bufferlist/package.json @@ -0,0 +1,34 @@ +{ + "name": "bufferlist", + "version": "0.1.0", + "description": "Create linked lists of Buffer objects", + "directories": { + "lib": "." + }, + "main": "./bufferlist", + "repository": { + "type": "git", + "url": "http://github.com/substack/node-bufferlist.git" + }, + "devDependencies": { + "expresso": ">= 0.7.2" + }, + "scripts": { + "test": "expresso" + }, + "engine": [ + "node >=0.1.97" + ], + "readme": "BufferList\n==========\nBufferList provides an interface to treat a linked list of buffers as a single\nstream. This is useful for events that produce a many small Buffers, such as\nnetwork streams.\n\nInstallation\n============\nInstall using npm:\n npm install bufferlist\n\nOr, check out the repository and have npm link to your development copy. This\nis useful for developing the library, and is necessary when running the tests,\nsince they refer to the installed names of the library files.\n git clone http://github.com/substack/node-bufferlist.git \n cd node-bufferlist\n npm link .\n\nSimple Bufferlist Example\n=========================\n \n #!/usr/bin/env node\n var sys = require('sys');\n var Buffer = require('buffer').Buffer;\n var BufferList = require('bufferlist').BufferList;\n\n var b = new BufferList;\n ['abcde','xyz','11358'].forEach(function (s) {\n var buf = new Buffer(s.length);\n buf.write(s);\n b.push(buf);\n });\n\n sys.puts(b.take(10)); // abcdexyz11\n\nBinary\n======\nThis distribution also contains a Binary module for parsing these bufferlists.\n\nSimple Binary Example\n=====================\n\n #!/usr/bin/env node\n\n var sys = require('sys');\n var Buffer = require('buffer').Buffer;\n var BufferList = require('bufferlist').BufferList;\n var Binary = require('bufferlist/binary').Binary;\n\n var bufferList = new BufferList;\n var binary = Binary(bufferList)\n .getWord16be('xLen')\n .getBuffer('xs', 'xLen')\n .tap(function (vars) {\n vars.moo = 'xs:' + vars.xLen + ':' + vars.xs;\n })\n .end()\n ;\n\n var buf = new Buffer(6);\n buf.write('\\x00\\x04meow', 'binary');\n bufferList.push(buf);\n\n sys.puts(binary.vars.moo); // xs:4:meow\n\nSee Also\n========\nSee the examples/ directory for more involved examples.\n\nSee http://github.com/substack/node-rfb for a practical application of this\ndistribution.\n", + "readmeFilename": "README.markdown", + "bugs": { + "url": "https://github.com/substack/node-bufferlist/issues" + }, + "homepage": "https://github.com/substack/node-bufferlist", + "_id": "bufferlist@0.1.0", + "dist": { + "shasum": "c4ab48435f9f9df13939ed9172499ccff73b0864" + }, + "_from": "bufferlist@>= 0.0.6", + "_resolved": "https://registry.npmjs.org/bufferlist/-/bufferlist-0.1.0.tgz" +} diff --git a/node_modules/bufferlist/test/advance.js b/node_modules/bufferlist/test/advance.js new file mode 100644 index 0000000..d66a891 --- /dev/null +++ b/node_modules/bufferlist/test/advance.js @@ -0,0 +1,25 @@ +// Test advancing the buffer + +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); +var assert = require('assert'); + +exports.advance = function () { + var b = new BufferList({ encoding: 'binary' }); + var buf1 = new Buffer(5); buf1.write('abcde'); + var buf2 = new Buffer(3); buf2.write('xyz'); + var buf3 = new Buffer(5); buf3.write('11358'); + + b.write(buf1); + assert.eql(b.take(b.length), 'abcde', 'wrote correctly'); + b.advance(3); + assert.eql(b.take(b.length), 'de', 'advanced with one buffer'); + b.advance(3); + assert.eql(b.take(b.length), '', 'advanced one buffer past the end'); + b.write(buf2); + assert.eql(b.take(b.length), 'yz', 'offset preserved past the end'); + b.write(buf3); + assert.eql(b.take(b.length), 'yz11358', 'second write after advance'); + b.advance(4); + assert.eql(b.take(b.length), '358', 'advance after two writes'); +}; diff --git a/node_modules/bufferlist/test/binary.js b/node_modules/bufferlist/test/binary.js new file mode 100644 index 0000000..548a3ff --- /dev/null +++ b/node_modules/bufferlist/test/binary.js @@ -0,0 +1,86 @@ +// Test the binary interface to bufferlists +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist').BufferList; // old style +var Binary = require('bufferlist/binary').Binary; // old style +var sys = require('sys'); +var assert = require('assert'); + +exports.binary = function () { + function runTest(bufs, check) { + var bList = new BufferList; + + var binary = Binary(bList) + .getWord16be('xLen') + .when('xLen', 0, function (vars) { + assert.eql(vars.xLen, 0, 'when check for 0 failed'); + this + .getWord32le('msgLen') + .getBuffer('msg', function (vars) { + return vars.msgLen + }) + .tap(function (vars) { + vars.moo = 42; + }) + .exit() + ; + }) + .getBuffer('xs', 'xLen') + .tap(function (vars) { + vars.moo = 100; + }) + .end() + ; + + var iv = setInterval(function () { + var buf = bufs.shift(); + if (!buf) { + clearInterval(iv); + check(binary.vars); + } + else { + bList.push(buf); + } + }, 50); + } + + runTest( + ['\x00','\x04m','eow'].map(function (s) { + var b = new Buffer(Buffer.byteLength(s,'binary')); + b.write(s,'binary'); + return b; + }), + function (vars) { + assert.eql( + vars.xLen, + 4, + 'xLen == 4 failed (xLen == ' + sys.inspect(vars.xLen) + ')' + ); + + var xs = vars.xs.toString(); + assert.eql( + xs, 'meow', 'xs != "meow", xs = ' + sys.inspect(xs) + ); + assert.eql( + vars.moo, 100, 'moo != 100, moo == ' + sys.inspect(vars.moo) + ); + } + ); + + runTest( + ['\x00\x00','\x12\x00\x00\x00hap','py pur','ring c','ats'] + .map(function (s) { + var b = new Buffer(Buffer.byteLength(s,'binary')); + b.write(s,'binary'); + return b; + }), + function (vars) { + assert.eql(vars.xLen, 0, 'xLen == 0 in "\\x00\\x12happy purring cats"'); + assert.eql( + vars.msgLen, 18, + 'msgLen != 18, msgLen = ' + sys.inspect(vars.msgLen) + ); + assert.eql(vars.moo, 42, 'moo != 42'); + } + ); +}; + diff --git a/node_modules/bufferlist/test/binary_assign.js b/node_modules/bufferlist/test/binary_assign.js new file mode 100644 index 0000000..b280b1a --- /dev/null +++ b/node_modules/bufferlist/test/binary_assign.js @@ -0,0 +1,73 @@ +// Test .into and hierarchical addressing assignment +var sys = require('sys'); +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); +var Binary = require('bufferlist/binary'); +var assert = require('assert'); + +exports['binary assign'] = function () { + var tapped = 0; + var bList = new BufferList; + + Binary(bList) + .getWord16be('foo','bar','baz') + .tap(function (vars) { + assert.eql( + vars.foo.bar.baz, 24930, + 'vars.foo.bar.baz != 24930, ' + + 'vars.foo.bar.baz == ' + sys.inspect(vars.foo.bar.baz) + ); + tapped ++; + }) + .getWord32le(['one','two','three']) + .tap(function (vars) { + assert.eql( + vars.one.two.three, 1717920867, + 'vars.one.two.three != 1717920867, ' + + 'vars.one.two.three == ' + sys.inspect(vars.one.two.three) + ); + tapped ++; + }) + .into(['what.the','fuck'],function () { + this + .getWord8('w') + .getWord8('t') + .getWord8('f') + .getWord32le('?!') + .tap(function (vars) { + vars.meow = 9000; + }) + ; + }) + .tap(function (vars) { + assert.eql( + vars.what.the.fuck.w, 119, + '.w != 119, .w == ' + vars.what.the.fuck.w + ); + assert.eql( + vars.what.the.fuck.t, 116, + '.t != 119, .t == ' + vars.what.the.fuck.t + ); + assert.eql( + vars.what.the.fuck.f, 102, + '.f != 119, .f == ' + vars.what.the.fuck.f + ); + assert.eql( + vars.what.the.fuck['?!'], 825303359, + '.?! != 825303359, .?! == ' + vars.what.the.fuck['?!'] + ); + assert.eql( + vars.what.the.fuck['meow'], 9000, + '.meow != 9000, .meow == ' + vars.what.the.fuck.meow + ); + tapped ++; + }) + .end() + ; + + var buf = new Buffer(13); + buf.write('abcdefwtf?!11'); + bList.push(buf); + assert.eql(tapped, 3, 'tapped != 3, tapped == ' + tapped); +}; + diff --git a/node_modules/bufferlist/test/binary_endianness.js b/node_modules/bufferlist/test/binary_endianness.js new file mode 100644 index 0000000..fc5067b --- /dev/null +++ b/node_modules/bufferlist/test/binary_endianness.js @@ -0,0 +1,243 @@ +#!/usr/bin/env node +// Test binary byte and endianness functions +var sys = require('sys'); +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); +var Binary = require('bufferlist/binary'); +var assert = require('assert'); + +exports.endianness = function () { + var bList = new BufferList; + + Binary(bList) + .getWord8('w8') + .tap(function (vars) { + assert.eql(vars.w8, 239, 'w8 is not 239') + }) + // 16 bit functions + .getWord16le('w16le') + .tap(function (vars) { + assert.eql(vars.w16le, 23569, 'w16le is not 23569'); + }) + .getWord16be('w16be') + .tap(function (vars) { + assert.eql(vars.w16be, 23569, 'w16be is not 23569'); + }) + .getWord16les('w16les') + .tap(function (vars) { + assert.eql(vars.w16les, -239, 'w16les is not -239'); + }) + .getWord16bes('w16bes') + .tap(function (vars) { + assert.eql(vars.w16bes, -239, 'w16bes is not -239'); + }) + .getWord16les('w16lesu') + .tap(function (vars) { + assert.eql(vars.w16lesu, 23569, 'w16lesu is not -239'); + }) + .getWord16bes('w16besu') + .tap(function (vars) { + assert.eql(vars.w16besu, 23569, 'w16besu is not -239'); + }) + // 32 bit functions + .getWord32le('w32le') + .tap(function (vars) { + assert.eql(vars.w32le, 287454020, 'w32le is not 287454020'); + }) + .getWord32be('w32be') + .tap(function (vars) { + assert.eql(vars.w32be, 287454020, 'w32be is not 287454020'); + }) + .getWord32les('w32les') + .tap(function (vars) { + assert.eql(vars.w32les, -16742383, 'w32les is not -16742383'); + }) + .getWord32bes('w32bes') + .tap(function (vars) { + assert.eql(vars.w32bes, -16742383, 'w32bes is not -16742383'); + }) + .getWord32les('w32lesu') + .tap(function (vars) { + assert.eql(vars.w32lesu, 2076074948, 'w32lesu is not 2076074948'); + }) + .getWord32bes('w32besu') + .tap(function (vars) { + assert.eql(vars.w32besu, 2076074948, 'w32besu is not 2076074948'); + }) + // 64 bit functions + .getWord64le('w64le') + .tap(function (vars) { + assert.eql(vars.w64le, 9833440827789222417, 'w64le is not 9833440826932474692'); + }) + .getWord64be('w64be') + .tap(function (vars) { + assert.eql(vars.w64be, 9833440827789222417, 'w64be is not 9833440826932474692'); + }) + .getWord64les('w64les') + .tap(function (vars) { + assert.eql(vars.w64les, -8613303245920330000, 'w64les is not -8613303245920330000'); + }) + .getWord64bes('w64bes') + .tap(function (vars) { + assert.eql(vars.w64bes, -8613303245920330000, 'w64bes is not -8613303245920330000'); + }) + .getWord64les('w64lesu') + .tap(function (vars) { + assert.eql(vars.w64lesu, 5337084636995872375, 'w64lesu is not 5337084636995872375'); + }) + .getWord64bes('w64besu') + .tap(function (vars) { + assert.eql(vars.w64besu, 5337084636995872375, 'w64besu is not 5337084636995872375'); + }) + .end() + ; + + var b8 = new Buffer(1); + b8[0] = 239; + bList.push(b8); + + // 16 bit functions + + var b16le = new Buffer(2); + b16le[0] = 0x11; + b16le[1] = 0x5C; + bList.push(b16le); + + var b16be = new Buffer(2); + b16be[0] = 0x5C; + b16be[1] = 0x11; + bList.push(b16be); + + var b16les = new Buffer(2); + b16les[0] = 0x11; + b16les[1] = 0xFF; + bList.push(b16les); + + var b16bes = new Buffer(2); + b16bes[0] = 0xFF; + b16bes[1] = 0x11; + bList.push(b16bes); + + var b16lesu = new Buffer(2); + b16lesu[0] = 0x11; + b16lesu[1] = 0x5C; + bList.push(b16lesu); + + var b16besu = new Buffer(2); + b16besu[0] = 0x5C; + b16besu[1] = 0x11; + bList.push(b16besu); + + // 32 bit functions + + var b32le = new Buffer(4); + b32le[0] = 0x44; + b32le[1] = 0x33; + b32le[2] = 0x22; + b32le[3] = 0x11; + bList.push(b32le); + + var b32be = new Buffer(4); + b32be[0] = 0x11; + b32be[1] = 0x22; + b32be[2] = 0x33; + b32be[3] = 0x44; + bList.push(b32be); + + var b32les = new Buffer(4); + b32les[0] = 0x11; + b32les[1] = 0x88; + b32les[2] = 0x00; + b32les[3] = 0xFF; + bList.push(b32les); + + var b32bes = new Buffer(4); + b32bes[0] = 0xFF; + b32bes[1] = 0x00; + b32bes[2] = 0x88; + b32bes[3] = 0x11; + bList.push(b32bes); + + var b32lesu = new Buffer(4); + b32lesu[0] = 0xC4; + b32lesu[1] = 0x63; + b32lesu[2] = 0xBE; + b32lesu[3] = 0x7B; + bList.push(b32lesu); + + var b32besu = new Buffer(4); + b32besu[0] = 0x7B; + b32besu[1] = 0xBE; + b32besu[2] = 0x63; + b32besu[3] = 0xC4; + bList.push(b32besu); + + // 64 bit functions + + var b64le = new Buffer(8); + b64le[0] = 0x11; + b64le[1] = 0x22; + b64le[2] = 0x33; + b64le[3] = 0x44; + b64le[4] = 0x55; + b64le[5] = 0x66; + b64le[6] = 0x77; + b64le[7] = 0x88; + bList.push(b64le); + + var b64be = new Buffer(8); + b64be[0] = 0x88; + b64be[1] = 0x77; + b64be[2] = 0x66; + b64be[3] = 0x55; + b64be[4] = 0x44; + b64be[5] = 0x33; + b64be[6] = 0x22; + b64be[7] = 0x11; + bList.push(b64be); + + var b64les = new Buffer(8); + b64les[0] = 0x11; + b64les[1] = 0x22; + b64les[2] = 0x33; + b64les[3] = 0x44; + b64les[4] = 0x55; + b64les[5] = 0x66; + b64les[6] = 0x77; + b64les[7] = 0x88; + bList.push(b64les); + + var b64bes = new Buffer(8); + b64bes[0] = 0x88; + b64bes[1] = 0x77; + b64bes[2] = 0x66; + b64bes[3] = 0x55; + b64bes[4] = 0x44; + b64bes[5] = 0x33; + b64bes[6] = 0x22; + b64bes[7] = 0x11; + bList.push(b64bes); + + var b64lesu = new Buffer(8); + b64lesu[0] = 0x77; + b64lesu[1] = 0x66; + b64lesu[2] = 0x55; + b64lesu[3] = 0x44; + b64lesu[4] = 0x33; + b64lesu[5] = 0x22; + b64lesu[6] = 0x11; + b64lesu[7] = 0x4A; + bList.push(b64lesu); + + var b64besu = new Buffer(8); + b64besu[0] = 0x4A; + b64besu[1] = 0x11; + b64besu[2] = 0x22; + b64besu[3] = 0x33; + b64besu[4] = 0x44; + b64besu[5] = 0x55; + b64besu[6] = 0x66; + b64besu[7] = 0x77; + bList.push(b64besu); +}; + diff --git a/node_modules/bufferlist/test/binary_event.js b/node_modules/bufferlist/test/binary_event.js new file mode 100644 index 0000000..f8b124d --- /dev/null +++ b/node_modules/bufferlist/test/binary_event.js @@ -0,0 +1,67 @@ +var sys = require('sys'); +var net = require('net'); +var BufferList = require('bufferlist'); +var Binary = require('bufferlist/binary'); +var assert = require('assert'); + +function parser (sock) { + var bufferList = new BufferList; + sys.pump(sock, bufferList); + + return Binary(bufferList) + .getWord16be('xLen') + .when('xLen', 0, function (vars) { + this + .getWord32le('msgLen') + .getBuffer('msg', 'msgLen') + .tap(function (vars) { + vars.moo = 'msg:' + vars.msgLen + ':' + vars.msg; + }) + .exit() + ; + }) + .getBuffer('xs', 'xLen') + .tap(function (vars) { + vars.moo = 'xs:' + vars.xLen + ':' + vars.xs; + }) + .end() + ; +} + +exports['binary event'] = function () { + function serverSession (port, strings, moo) { + // fire up a server to write the strings when a client connects + var server = net.createServer(function (stream) { + strings.forEach(function (s) { + stream.write(s); + }); + stream.end(); + server.close(); + }); + server.listen(port); + + // connect to the server and parse its output + var client = new net.Stream; + parser(client).on('end', function (vars) { + assert.eql( + moo, vars.moo, + 'moo != ' + sys.inspect(moo) + ', moo == ' + sys.inspect(vars.moo) + ); + client.end(); + }); + setTimeout(function () { + client.connect(port); + }, 50); + } + + serverSession(20801, + ['\x00','\x04m','eow'], + 'xs:4:meow' + ); + + serverSession(20802, + ['\x00\x00','\x12\x00\x00\x00happy pur','ring c','ats'], + 'msg:18:happy purring cats' + ); +}; + diff --git a/node_modules/bufferlist/test/binary_into.js b/node_modules/bufferlist/test/binary_into.js new file mode 100644 index 0000000..7ae9776 --- /dev/null +++ b/node_modules/bufferlist/test/binary_into.js @@ -0,0 +1,49 @@ +// Check .into(), especially for object pollution +var sys = require('sys'); +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); +var Binary = require('bufferlist/binary'); +var assert = require('assert'); + +exports.into = function () { + var bList = new BufferList; + var tapped = false; + + Binary(bList) + .getWord8('ones') + .into('frac', function () { + this + .getWord64be('64') + .getWord32be('32') + .getWord16be('16') + .getWord8('8') + }) + .tap(function (vars) { + tapped = true; + + assert.eql(vars.ones, 3); + assert.eql(vars.frac['64'], 73184615082362370); + assert.eql(vars.frac['32'], 50661385); + assert.eql(vars.frac['16'], 1801); + assert.eql(vars.frac['8'], 3); + + assert.eql( + Object.keys(vars).sort().join(' '), 'frac ones', + 'object pollution with .into()' + ) + }) + .end() + ; + + var buf = new Buffer(16); + var i = 0; + String(4 * Math.atan2(1,1)).split('').forEach(function (digit) { + if (digit != '.') { + buf[i++] = parseInt(digit,10); + } + }); + bList.push(buf); + + assert.ok(tapped, 'not tapped'); +}; + diff --git a/node_modules/bufferlist/test/binary_jump.js b/node_modules/bufferlist/test/binary_jump.js new file mode 100644 index 0000000..4f66a57 --- /dev/null +++ b/node_modules/bufferlist/test/binary_jump.js @@ -0,0 +1,55 @@ +// Jumping around in a binary parser +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); +var Binary = require('bufferlist/binary'); +var assert = require('assert'); + +Number.prototype.upTo = function (n) { + var acc = []; + for (var i = Number(this); i <= n; i++) { + acc.push(i); + } + return acc; +}; + +Number.prototype.downTo = function (n) { + var acc = []; + for (var i = Number(this); i >= n; i--) { + acc.push(i); + } + return acc; +}; + +Array.prototype.zip = function (xs) { + var arr = this; + return (0).upTo(this.length - 1).map(function (i) { + return [ arr[i], xs[i] ]; + }); +}; + +exports.jump = function () { + var tapped = 0; + + var bList = new BufferList; + + Binary(bList) + .skip(3) + .getWord16be('de') + .tap(function (vars) { + var de = 256 * 'd'.charCodeAt(0) + 'e'.charCodeAt(0); + assert.eql( + vars.de, de, + 'getWord16be at 3 should be ' + de + ', not ' + vars.de + ); + tapped ++; + }) + .end() + ; + + var buf1 = new Buffer(5); buf1.write('abcde'); + var buf2 = new Buffer(3); buf2.write('xyz'); + var buf3 = new Buffer(5); buf3.write('11358'); + bList.push(buf1,buf2,buf3); + assert.eql(tapped, 1, 'not tapped'); +}; + diff --git a/node_modules/bufferlist/test/binary_loop.js b/node_modules/bufferlist/test/binary_loop.js new file mode 100644 index 0000000..45e1d62 --- /dev/null +++ b/node_modules/bufferlist/test/binary_loop.js @@ -0,0 +1,115 @@ +// Test binary looping functions +var sys = require('sys'); + +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); +var Binary = require('bufferlist/binary'); +var assert = require('assert'); + +exports['binary loop'] = function () { + // test repeat + var reps = 0; + var trickyList = []; + + Binary(new BufferList) + .repeat(5000, function(vars, n) { + reps++; + }) + .tap(function (vars) { + assert.eql( + reps, 5000, 'reps != 5000, reps == ' + reps + ' in repeat test' + ); + }) + .repeat(3, function (vars, i) { + this + .repeat(4, function (vars, j) { + trickyList.push([ i + 1, j + 1 ]); + }) + ; + }) + .tap(function (vars) { + expectedTrickyList = [ + [1,1],[1,2],[1,3],[1,4], + [2,1],[2,2],[2,3],[2,4], + [3,1],[3,2],[3,3],[3,4] + ]; + for (var i = 0; i < trickyList.length; i++) { + assert.eql( + trickyList[i][0], + expectedTrickyList[i][0], + 'trickly list is not what it should be. it should be: ' + + sys.inspect(expectedTrickyList) + '. it is: ' + + sys.inspect(trickyList) + ); + assert.eql( + trickyList[i][1], + expectedTrickyList[i][1], + 'trickly list is not what it should be. it should be: ' + + sys.inspect(expectedTrickyList) + '. it is: ' + + sys.inspect(trickyList) + ); + } + }) + .end() + ; + + assert.eql(reps, 5000, 'reps != 5000, reps == ' + reps + ' in outer repeat check'); + + var bufferList = new BufferList; + var loops = 0; + Binary(bufferList) + .forever(function () { + this + .getWord16be('moo','count') + .tap(function (vars) { + assert.eql( + vars.moo.count, 100, + 'count != 100, count == ' + vars.moo.count + ); + vars.reps = 0; + }) + .repeat('moo.count', function (vars, i) { + this + .getWord16be('size') + .tap(function (vars) { + assert.eql( + vars.size, 1000, + 'size != 1000, size == ' + vars.size + ); + }) + .getBuffer('block', 'size') + ; + vars.reps ++; + }) + .tap(function (vars) { + assert.eql( + vars.reps, 100, 'reps != 100, reps == ' + vars.reps + ); + }) + ; + loops ++; + if (loops == 20) this.exit(); + }) + .end() + ; + + for (var n = 0; n < 20; n++) { + var countBuf = new Buffer(2); + countBuf[0] = 100 >> 8; + countBuf[1] = 100 % 256; + bufferList.push(countBuf); + + for (var i = 0; i < 100; i++) { + var buf = new Buffer(1000 + 2); + buf[0] = 1000 >> 8; + buf[1] = 1000 % 256; + for (var j = 0; j < 1000; j++) { + buf[j + 2] = j; + } + bufferList.push(buf); + } + } + + assert.eql(loops, 20, 'loops != 20, loops == ' + loops); +}; + diff --git a/node_modules/bufferlist/test/client_server.js b/node_modules/bufferlist/test/client_server.js new file mode 100644 index 0000000..e1e85e9 --- /dev/null +++ b/node_modules/bufferlist/test/client_server.js @@ -0,0 +1,48 @@ +// Test a client/server interaction +// If nothing gets printed, everything is fine. + +var sys = require('util'); +var net = require('net'); +var client = new net.Stream; +var assert = require('assert'); + +exports['client/server'] = function () { + var BufferList = require('bufferlist'); + var bufs = new BufferList({ encoding: 'binary' }); + var elems = []; + + client.addListener('data', function (data) { + bufs.push(data); + elems.push(data); + + assert.eql(bufs.take(3).toString(), elems[0].toString(), 'take first 3 bytes ('+sys.inspect(elems[0])+') vs ('+sys.inspect(bufs.take(3).toString())+')'); + assert.eql(bufs.take(100), elems.join(''), 'take past length of buffer'); + }); + + client.addListener('end', function (data) { + assert.eql(bufs.length, elems.join('').length, 'verify length'); + assert.eql(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); + + setTimeout(function () { + client.connect(port); + }, 50); +}; + diff --git a/node_modules/bufferlist/test/event.js b/node_modules/bufferlist/test/event.js new file mode 100644 index 0000000..335cb64 --- /dev/null +++ b/node_modules/bufferlist/test/event.js @@ -0,0 +1,46 @@ +#!/usr/bin/env node +// Test joining lots of chunks into one buffer + +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); +var assert = require('assert'); + +exports.events = function () { + var b = new BufferList({ encoding: 'binary' }); + var times = 0; + + var wrote = null; + b.addListener('write', function (buf) { + assert.eql( + wrote.toString(), + buf.toString(), + 'write callback gives its arguments' + ); + times ++; + }); + + var buf1 = new Buffer(5); buf1.write('abcde'); + var buf2 = new Buffer(3); buf2.write('xyz'); + var buf3 = new Buffer(5); buf3.write('11358'); + + var wrote = buf1; b.write(buf1); + var wrote = buf2; b.write(buf2); + + assert.eql(times, 2, 'wrote twice'); + + var wrote = buf3; b.write(buf3); + + assert.eql(times, 3, 'wrote thrice'); + + assert.eql(b.take(), 'abcdexyz11358', 'entire buffer check'); + + var advanced = 0; + b.on('advance', function (n) { + assert.eql(n, 3, 'n = 3 in advance callback') + advanced ++; + }); + b.advance(3); + assert.eql(b.take(3), 'dex', 'advanced 3'); + assert.eql(advanced, 1, 'advance callback triggered once'); +}; + diff --git a/node_modules/bufferlist/test/join.js b/node_modules/bufferlist/test/join.js new file mode 100644 index 0000000..9678539 --- /dev/null +++ b/node_modules/bufferlist/test/join.js @@ -0,0 +1,26 @@ +// Test joining lots of chunks into one buffer +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); +var assert = require('assert'); + +exports.join = function () { + var buf1 = new Buffer(5); buf1.write('abcde'); + var buf2 = new Buffer(3); buf2.write('xyz'); + var buf3 = new Buffer(5); buf3.write('11358'); + + var b = new BufferList; + b.push(buf1,buf2,buf3); + + assert.eql( + b.join().toString('ascii',0,b.length), + 'abcdexyz11358', + 'join multiple chunks into one Buffer' + ); + + assert.eql( + b.join(3,6).toString(), + 'dex', + 'slice of a buffer join' + ); +}; + diff --git a/node_modules/bufferlist/test/take.js b/node_modules/bufferlist/test/take.js new file mode 100644 index 0000000..a637f64 --- /dev/null +++ b/node_modules/bufferlist/test/take.js @@ -0,0 +1,39 @@ +// Test BufferList#take(). +var Buffer = require('buffer').Buffer; +var BufferList = require('bufferlist'); +var assert = require('assert'); + +exports.join = function () { + var buf1 = new Buffer(5); buf1.write('abcde'); + var buf2 = new Buffer(3); buf2.write('xyz'); + var buf3 = new Buffer(5); buf3.write('11358'); + + var b = new BufferList; + b.push(buf1,buf2,buf3); + + assert.eql( + b.take('binary'), + 'abcdexyz11358', + 'take entire BufferList at once' + ); + + assert.eql( + b.take(1, 'ascii'), + 'a', + 'take 1 byte with "ascii" encoding' + ); + + assert.ok( + Buffer.isBuffer(b.take(1)), + 'take without encoding returns Buffer' + ); + + + // Now set the encoding + b.encoding = 'ascii'; + assert.ok( + !Buffer.isBuffer(b.take(1)), + 'take with encoding returns String' + ); +}; + diff --git a/node_modules/put/LICENSE b/node_modules/put/LICENSE new file mode 100644 index 0000000..432d1ae --- /dev/null +++ b/node_modules/put/LICENSE @@ -0,0 +1,21 @@ +Copyright 2010 James Halliday (mail@substack.net) + +This project is free software released under the MIT/X11 license: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +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. diff --git a/node_modules/put/README.md b/node_modules/put/README.md new file mode 100644 index 0000000..c91e9bd --- /dev/null +++ b/node_modules/put/README.md @@ -0,0 +1,57 @@ +Put +=== + +Pack multibyte binary values into buffers with specific endiannesses. + +Installation +============ + +To install with [npm](http://github.com/isaacs/npm): + + npm install put + +To run the tests with [expresso](http://github.com/visionmedia/expresso): + + expresso + +Examples +======== + +buf.js +------ + +Build a buffer + + #!/usr/bin/env node + + var Put = require('put'); + var buf = Put() + .word16be(1337) + .word8(1) + .pad(5) + .put(new Buffer('pow', 'ascii')) + .word32le(9000) + .buffer() + ; + console.log(buf); + +Output: + + +stream.js +--------- + +Send a buffer to a writeable stream + + #!/usr/bin/env node + + var Put = require('put'); + Put() + .word16be(24930) + .word32le(1717920867) + .word8(103) + .write(process.stdout) + ; + +Output: + abcdefg diff --git a/node_modules/put/examples/buf.js b/node_modules/put/examples/buf.js new file mode 100644 index 0000000..a5446d0 --- /dev/null +++ b/node_modules/put/examples/buf.js @@ -0,0 +1,12 @@ +#!/usr/bin/env node + +var Put = require('put'); +var buf = Put() + .word16be(1337) + .word8(1) + .pad(5) + .put(new Buffer('pow', 'ascii')) + .word32le(9000) + .buffer() +; +console.log(buf); diff --git a/node_modules/put/examples/stream.js b/node_modules/put/examples/stream.js new file mode 100644 index 0000000..ac65119 --- /dev/null +++ b/node_modules/put/examples/stream.js @@ -0,0 +1,9 @@ +#!/usr/bin/env node + +var Put = require('put'); +Put() + .word16be(24930) + .word32le(1717920867) + .word8(103) + .write(process.stdout) +; diff --git a/node_modules/put/index.js b/node_modules/put/index.js new file mode 100644 index 0000000..47cb0a7 --- /dev/null +++ b/node_modules/put/index.js @@ -0,0 +1,100 @@ +module.exports = Put; +function Put () { + if (!(this instanceof Put)) return new Put; + + var words = []; + var len = 0; + + this.put = function (buf) { + words.push({ buffer : buf }); + len += buf.length; + return this; + }; + + this.word8 = function (x) { + words.push({ bytes : 1, value : x }); + len += 1; + return this; + }; + + this.floatle = function (x) { + words.push({ bytes : 'float', endian : 'little', value : x }); + len += 4; + return this; + }; + + [ 8, 16, 24, 32, 64 ].forEach((function (bits) { + this['word' + bits + 'be'] = function (x) { + words.push({ endian : 'big', bytes : bits / 8, value : x }); + len += bits / 8; + return this; + }; + + this['word' + bits + 'le'] = function (x) { + words.push({ endian : 'little', bytes : bits / 8, value : x }); + len += bits / 8; + return this; + }; + }).bind(this)); + + this.pad = function (bytes) { + words.push({ endian : 'big', bytes : bytes, value : 0 }); + len += bytes; + return this; + }; + + this.length = function () { + return len; + }; + + this.buffer = function () { + var buf = new Buffer(len); + var offset = 0; + words.forEach(function (word) { + if (word.buffer) { + word.buffer.copy(buf, offset, 0); + offset += word.buffer.length; + } + else if (word.bytes == 'float') { + // s * f * 2^e + var v = Math.abs(word.value); + var s = (word.value >= 0) * 1; + var e = Math.ceil(Math.log(v) / Math.LN2); + var f = v / (1 << e); + console.dir([s,e,f]); + + console.log(word.value); + + // s:1, e:7, f:23 + // [seeeeeee][efffffff][ffffffff][ffffffff] + buf[offset++] = (s << 7) & ~~(e / 2); + buf[offset++] = ((e & 1) << 7) & ~~(f / (1 << 16)); + buf[offset++] = 0; + buf[offset++] = 0; + offset += 4; + } + else { + var big = word.endian === 'big'; + var ix = big ? [ (word.bytes - 1) * 8, -8 ] : [ 0, 8 ]; + + for ( + var i = ix[0]; + big ? i >= 0 : i < word.bytes * 8; + i += ix[1] + ) { + if (i >= 32) { + buf[offset++] = Math.floor(word.value / Math.pow(2, i)) & 0xff; + } + else { + buf[offset++] = (word.value >> i) & 0xff; + } + } + } + }); + return buf; + }; + + this.write = function (stream) { + stream.write(this.buffer()); + }; +} diff --git a/node_modules/put/package.json b/node_modules/put/package.json new file mode 100644 index 0000000..f349faf --- /dev/null +++ b/node_modules/put/package.json @@ -0,0 +1,36 @@ +{ + "name": "put", + "version": "0.0.6", + "description": "Pack multibyte binary values into buffers", + "main": "./index.js", + "keywords": [ + "put", + "pack", + "binary" + ], + "repository": { + "type": "git", + "url": "http://github.com/substack/node-put.git" + }, + "scripts": { + "test": "expresso" + }, + "engines": { + "node": ">=0.3.0" + }, + "license": { + "type": "MIT/X11" + }, + "readme": "Put\n===\n\nPack multibyte binary values into buffers with specific endiannesses.\n\nInstallation\n============\n\nTo install with [npm](http://github.com/isaacs/npm):\n \n npm install put\n\nTo run the tests with [expresso](http://github.com/visionmedia/expresso):\n\n expresso\n\nExamples\n========\n\nbuf.js\n------\n\nBuild a buffer\n\n #!/usr/bin/env node\n\n var Put = require('put');\n var buf = Put()\n .word16be(1337)\n .word8(1)\n .pad(5)\n .put(new Buffer('pow', 'ascii'))\n .word32le(9000)\n .buffer()\n ;\n console.log(buf);\n\nOutput:\n \n\nstream.js\n---------\n\nSend a buffer to a writeable stream\n\n #!/usr/bin/env node\n\n var Put = require('put');\n Put()\n .word16be(24930)\n .word32le(1717920867)\n .word8(103)\n .write(process.stdout)\n ;\n\nOutput:\n abcdefg\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/substack/node-put/issues" + }, + "homepage": "https://github.com/substack/node-put", + "_id": "put@0.0.6", + "dist": { + "shasum": "f56db18c769a9f4c68c2c7020b41c601e1a5cad6" + }, + "_from": "put@*", + "_resolved": "https://registry.npmjs.org/put/-/put-0.0.6.tgz" +} diff --git a/node_modules/put/test/buf.js b/node_modules/put/test/buf.js new file mode 100644 index 0000000..299dc13 --- /dev/null +++ b/node_modules/put/test/buf.js @@ -0,0 +1,70 @@ +var assert = require('assert'); +var Put = require('put'); +var Binary = require('binary'); + +exports.chain = function () { + var buf = Put() + .word16be(1337) + .word8(1) + .pad(5) + .put(new Buffer('pow', 'ascii')) + .word32le(9000) + .word64le(3) + .word64be(4) + .buffer() + ; + assert.equal(buf.length, 2 + 1 + 5 + 3 + 4 + 8 + 8); + var bs = [].slice.call(buf); + + // word16be(1337) + assert.eql(bs.slice(0,2), [ 0x05, 0x39 ]); + + // word8(1) + assert.eql(bs.slice(2,3), [ 0x01 ]); + + // pad(5) + assert.eql(bs.slice(3,8), [ 0x00, 0x00, 0x00, 0x00, 0x00 ]); + + // put(new Buffer('pow', 'ascii')) + assert.eql(bs.slice(8,11), [ 0x70, 0x6f, 0x77 ]); + + // word32le(9000) + assert.eql(bs.slice(11,15), [ 0x28, 0x23, 0x00, 0x00 ]); + + // word64le(3) + assert.eql( + bs.slice(15,23), + [ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] + ); + + // word64be(4) + assert.eql( + bs.slice(23,31), + [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04 ] + ); +}; + +exports.parity = function () { + [ 'le', 'be' ].forEach(function (end) { + [ 8, 16, 32 ].forEach(function (n) { + var max = Math.pow(2,n); + var step = Math.max(1, Math.floor(max / 1000)); + + for (var i = 0; i < max; i += step) { + var buf = Put()[ 'word' + n + end ](i).buffer(); + var j = Binary.parse(buf)[ 'word' + n + end ]('j').vars.j; + assert.eql(i, j); + } + }); + }); +}; + +exports.b64 = function () { + var buf = Put().word64be(1).buffer(); + assert.eql([].slice.call(buf), [ 0, 0, 0, 0, 0, 0, 0, 1 ]); +}; + +exports.l64 = function () { + var buf = Put().word64le(1).buffer(); + assert.eql([].slice.call(buf), [ 1, 0, 0, 0, 0, 0, 0, 0 ]); +}; diff --git a/node_modules/put/test/c/ftoi b/node_modules/put/test/c/ftoi new file mode 100644 index 0000000000000000000000000000000000000000..4eb358b39094b40113c5f4da899768be2aab9e71 GIT binary patch literal 4632 zcmb7HYiL}@6`oyP+naXl$g*N@62)xEDwV;$v5h3`(uZX2T2>-keke{|C!VhMp?l`j2ik#iXTCY#oHH}`%>@PnhHvO@gSWY6Uuxe`$l(bc(RpAUec0@t|0b zD(X6)0|#;iWy(5;1!;n`!bt0s6`*Vercg)Q6qV3cKmuq;VSCZ6^{Vbg=paGbg3vGZ zeq?PRw?Ri)0;W(;ACwO8JK&oV1*RC?(W_1p@Q!5KKbp&qJeo`H%w-Fe3ADt_J)7@U8Dz0ghu6Ct1qTe6b+Q zPQ2tuDKI4oPDQtn14F1yW(%@XP9?>7DO+&TBJLE^XhT}PO+KD2i2lKW{e5zeU3cfl zzw@gx`tap^Qka^v+0XIM_G>7X@n6?tP`8k8;NX6W9Ft-($HWDgqq9%UTs>Z0wrXs4 zYHBfpIGcUpmg~CHZ#(O1+fZA(#?K|#_}Zzr7TvBJu;{km#FuT{c6!LLcQQLf}p>I4u`ghr&H?S`pT{OK&ZnA?JgY>hiAH zSg^Wa&59W-QhOMEedno2+dEOnQ;{8W(a4V3<_lul3d{^gEK*i(yDplqNwC%E|H%`_ zYeR55wfN#D3}Csf_9Pn4T@1m)T$SJLZ@%vOr(Gwq`=i-d^Gq}nKu?fav#|gixj%W8 ztm+%SeYZ>RRWG%jIxU}GoNbH1cYXfOabKw3be+u?SxTR&Uboz(*(Ov~Zsp<<6zve{LdkOYwY4*a@dt zD#L-!#u6|DBk_DT0S84i#K%_Fbjy)4*ok63pDH+Jvi^tsL2&rr_}|r;2*7`95_L=u zLwMYhr_L@Y!YG@>y_sn@#PALx-VTBnQ5yX*yn}#@P1<9;=D^#5GUJqqJW3Su5n_rw z#`ApLZzJz8^o(ip80Qzj`v%JF3yR7XMF<712b0KUIt^h=lgD@-LxF3} z_+>ri83@+^%UlN&D1=e=`UMo zmGxZz3*hZS*(CCqegHAN74TNTJEAoDLmuVF5X0mBst1$wb5_(7=Zb3}urH@3*Kh zJRVBTu(!H-KxcTr_wac5gg(XZB6yr*`sMz_yWJAX{J%`JNBe(-7{9z9EZ@Z*xqtES zxZkdT*EoOV{nf(@;xrAS6L%ZO74TTk{_)gp{S@9+=-Izr5GL~W>Z1BmN8vtCTP6*H z_b&sGlf%TE|IDOiEWR*0{tzm5LO2G-3}e}AFNn&Zr=hV2+8v4e5i9krU++5_YXjV0 zG}a!tk7!KqdcV*ZlZ?cDL1PRGiR)iu{Ws0I)l{Epu4k?1DD=A3Sf9&WpBi)L(d$rS z9qC+e8gu0e^={F4qrzN28sDoh*NMiQIm{u}gU0+T_|J$Jjd==Vepj*Hu^Go&&(mAS ztH%12XIyH$g_%0Nb(Z+I%MqLY`EZNpo!#`$ zhZCg(*!0hb+XdeM+!#_!!LB8bSd*g=wdFBP{s6 zU^9O{MD>q=z5ag&e7-*4^#2O5NwmkyDc2|KeEzNCPsq*qgug}ntpWcB*xX-y{`vx+ zdH9pSra#T-&-a0w>;HR`KO|lN=1m_>#U}q|aTb`*1^x&2?>w+cwEu?&{5IRy?KNZm z-UDv);P)H!{{a3a?9*n8eT^jM!ql`P89TyZ3xljh>j* zm3)5E_=z2kDmMp?^&W~zgXqSTKk=e&ZOTj9DQ4N%{=uRBy@PV-z=7kjVL9Bpe=x>A z^9m^ArBZxSrV7cm73y6pWc1|W-a`X@g7-W9ZUs#}ViVNW3S`Pj4aSZXv| z# +#include + +int main (int argc, char **argv) { + float f = atof(argv[1]); + printf("%i\n", *(int *) &f); +} diff --git a/node_modules/put/test/c/itof b/node_modules/put/test/c/itof new file mode 100644 index 0000000000000000000000000000000000000000..4ac24efdb64a6c3ce8cdf47357a2eb0c54c1f94b GIT binary patch literal 4616 zcmb7HZEPIH8J;^|l7qU5^T$)g@lo?s1ii2rAV|H<<1S-(kx8t znrLf&9vtXA>eO}62($`Xhe7H_BT?!WU@C1Ko2mqT1@tBiRQ4A&+OFDOf(=^Dv7q!z zdl*GE$ki{y2Au<@(oP@LCh(i!o7w?PHMV2d+$7*_V){RncKRPmCwHZtY;o8s!5sh+M8Z$nEvq97ykLm58ilqZ2G7FojUyFCfbY-_9YGq z-`~WBc7s)1Vj@N^>#sld@eJ!hG5y#UgYIL+7tU{o0Vs)gSKxbr7hZ@&`5v1YWGM$T zxvVU>@w_XgKu8h{MT?N#y=YB3Sy?RDNimdnvhIM0yEzAaNb~z-;!aj{^>iO>mwPSW zT^Qdktllw%C*w(_)Hu%9`DME_6j$(F*W;xYP;NlE$Pz(WVu`@rWQoZ>arWAY(n6%n zZl^|P>yT&TFD`qYH}<}}uDlJc9%DRt>fKpy-&OSVwwLi_A8$K7q*%Q^k8a*} zdP>oDeNJI|OmUjmXB4LAR6X%U;60z7KKqZ-)y2pAj;D4beyLVGj-5;`Vf~bU1H#hz zRpQV0`EN#kfe949bs>s!I)X7rZwNf!{32Ys5jyZeVcWzX;6s#VLcb=(s~e+P(GPr( zFTcHx1B6O%MNU04JK;VkCjRsd@-cpCq5eV?+_4$A_7dArx#OKkBip>WcW2L&b9J$_ z5F78TF3m*7#o0(>`2o!JY)50m1oW@s(js2t!>1b~G~K-AdFZADeJlNa`{apoFWijI zzPuR|UT7!}qQk^=Jw}`;@wwxjH@)zf=Qi&7e7v&;UZU`fA~N0?g#+)U-;q^%J9OYy z{-e@c4W~}aXJ*G68sXEA*9GnarJJ6+Wtz2t^Q9XRZ*IH_O~oZ0gcYvIg(zlIK8LA1 zh40R_7D9e)AGnht5%A{)OV*JhDj%y+&ip76MM8?p{+dW*ANkKMFE@#jYp@=6uH{R> z9Pt?RYfvW2T~G>r&Likt%P}bT2h2&_4V^-N)+bSNJu>0AN3z6}bHixI6my)@BFZzs zsQ%x={n2z|2~i}7^n=C$QH zJ6~{e*;PQombcU7>&j5t6_%5A@O15AJO=<^$|d7&Tv&EW4&>t*TUZG}kVox+evX_XkNG_5`>o_1 zg`GJ~9`pPXc;7{xb3s*&#e6>rWv-LQby1HB*MkvqDW{>#Y4VuQXHelTbjM1@Ih#^bvZm!O8nbvNaYM;_O>;hjUBb7ec%{|tD$ zQ8z*!wccYMJhpRwJY^%8>{`5QuycO9p%n7=>#BOvM&&-wv5Y(d-oFe$Ne+c2znPIM zSbQ-|{C+g-g7O`hGtA}Sc*~m*$3RCj9%#1-_aipyTfW|RG}Z%ff6-Wb;69=;z3cr# zV+0SveL-V>QN8{()?d?{TUCApxt_J1Z=u(%#`;|5`qY>^k6wow>rCf*)0it)sQ(m= zH!95aqcMU4;X2Wnk<;rzV}2E#_ZssQh9ECkRQWqL^H^h^-a213)~7u4Qsb>G)OoKl zPkAAjXBzX$sPjqVdlWX0Dsk^h9w~PzL?~3V6!5 z)BkTt^o8T`GRpPIrcn59@fVcl{Y1D{{JjEy25jyxq3~Ve3t$t^n5Y;0Kj594nOF;d zTY8-YvMrfdMOlU$^$Y-s7^T`$Ql9_N44sg&u7Wn36d; zn9lXb(^6feWV|>ma7h|U+pe9o_8r*2SI{7xXri$5Tt^Q%5e$iFf#Qy-LH7$Su literal 0 HcmV?d00001 diff --git a/node_modules/put/test/c/itof.c b/node_modules/put/test/c/itof.c new file mode 100644 index 0000000..2a988da --- /dev/null +++ b/node_modules/put/test/c/itof.c @@ -0,0 +1,7 @@ +#include +#include + +int main (int argc, char **argv) { + int i = atoi(argv[1]); + printf("%f\n", *(float *) &i); +} diff --git a/node_modules/put/test/float.js_ b/node_modules/put/test/float.js_ new file mode 100644 index 0000000..5250be2 --- /dev/null +++ b/node_modules/put/test/float.js_ @@ -0,0 +1,9 @@ +var assert = require('assert'); +var Put = require('put'); + +exports.buf = function () { + var ibuf = Put().word32le(1096149893).buffer(); + var fbuf = Put().floatle(13.37).buffer(); + + assert.eql(ibuf, fbuf); +}; diff --git a/node_modules/put/test/stream.js b/node_modules/put/test/stream.js new file mode 100644 index 0000000..d338413 --- /dev/null +++ b/node_modules/put/test/stream.js @@ -0,0 +1,28 @@ +var assert = require('assert'); +var Put = require('put'); + +exports.stream = function () { + var written = 0; + var stream = { + write : function (buf) { + assert.equal(buf.toString(), 'abcdefg'); + written ++; + } + }; + + Put() + .word16be( + 256 * 'a'.charCodeAt(0) + + 'b'.charCodeAt(0) + ) + .word32le( + Math.pow(256, 0) * 'c'.charCodeAt(0) + + Math.pow(256, 1) * 'd'.charCodeAt(0) + + Math.pow(256, 2) * 'e'.charCodeAt(0) + + Math.pow(256, 3) * 'f'.charCodeAt(0) + ) + .word8('g'.charCodeAt(0)) + .write(stream) + ; + assert.equal(written, 1); +}; diff --git a/node_modules/stream-stack/.npmignore b/node_modules/stream-stack/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/stream-stack/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/stream-stack/API.md b/node_modules/stream-stack/API.md new file mode 100644 index 0000000..e5f3768 --- /dev/null +++ b/node_modules/stream-stack/API.md @@ -0,0 +1,63 @@ +# API + +## var ss = require('stream-stack') + +The main module (`stream-stack`) contains the primary constructor function for StreamStacks. + +### var streamStack = new ss.StreamStack(stream, [events]) + +Creates a new `StreamStack` instance. "stream" must be an instance of `Stream` (i.e. `net.Socket`, +`fs.ReadStream`, `fs.WriteStream`, `http.{Clinet,Server}{Request,Response}`, etc..), which will be +the "parent" stream of the new instance. + +The optional "events" arg should be an Object with keys being the names of events that _WILL NOT_ +be re-emitted on the new instance, and values being Functions that will be called instead when the +event is emitted. This gives the opportunity for subclasses to intercept event in order to perform +some filter or transformation first. + +Usually, the `StreamStack` class is subclassed, rather than directly instantiated. A bare instance +of "StreamStack" will re-emit all events from it's parent Stream, and any `write()` calls on the +instance will be proxied up to the parent Stream. + + var parent = require('fs').createReadStream(__filename); + var streamStack = new ss.StreamStack(parent, { + data: function(chunk) { + // Re-emit every other byte from the parent to `this` + for (var i=0, l=chunk.length; i= 0.3.0" + }, + "directories": {}, + "dependencies": {}, + "readme": "node-stream-stack\n=================\n### Filter low-level `Stream` instances into stackable, protocol-based streams.\n\nThis module exposes the `StreamStack` interface, which starts off as a node\n`Stream` subclass that accepts a \"parent\" Stream to work with. `StreamStack` is\nmeant to be subclassed in order to implement the layers of a protocol, or run the\nparent Stream's data through some kind of filter (i.e. compression).\n\nBy default, a `StreamStack` instance proxies all events downstream (from the\nparent stream to the child stream), and proxies all functions calls upstream\n(from the child stream to the parent stream).\n\nKeeping the `StreamStack` subclass' implementation independent of the parent\n`Stream` instance allows for the backend transport to be easily swapped out\nfor flexibility and code re-use. For example, storing `netcat` results to a file,\nand using `fs.ReadStream` as your parent stream, rather than `net.Stream`, in your\ntest cases.\n\nSince `StreamStack` inherits from the regular node `Stream`, all it's prototypal\ngoodies can be used along with your subclass instances. This makes it extremely\neasy for you to call `Stream#pipe(writable)`, in order to utilize node's data\ntransfer philosophies.\n\n\nA Simple Example\n----------------\n\nHere's a simple, kinda silly example:\n\n``` js\nvar util = require('util');\nvar StreamStack = require('stream-stack').StreamStack;\n\n// The first argument is the parent stream\nfunction DoubleWrite(stream) {\n StreamStack.call(this, stream);\n}\nutil.inherits(DoubleWrite, StreamStack);\n\n// Overwrite the default `write()` function to call\n// write() on the parent stream twice!\nDoubleWrite.prototype.write = function(data) {\n this.stream.write(data);\n this.stream.write(data);\n}\n\n\n// How to Use:\nvar doubleStdout = new DoubleWrite(process.stdout);\ndoubleStdout.write(\"this will be printed twice!\\n\");\n```\n\nWe've defined a `DoubleWrite` class. It accepts a writable stream, and\nwhenever `write()` is called on the DoubleWrite instance, then in return\n`write()` get called _twice_ on the parent stream. In this example, our\nwritable stream, `process.stdout`, will get the string printed to it twice.\n\n\nKnown Subclasses\n----------------\n\nCheck out the [Wiki][] page to see the list of [Known Subclasses][Wiki].\n\n[Wiki]: https://github.com/TooTallNate/node-stream-stack/wiki\n", + "readmeFilename": "README.md", + "_id": "stream-stack@1.1.4", + "dist": { + "shasum": "8b9bfd0218acf670f82ba5b83cffeb633216b8a5" + }, + "_from": "stream-stack@>= 1.0.1", + "_resolved": "https://registry.npmjs.org/stream-stack/-/stream-stack-1.1.4.tgz" +} diff --git a/node_modules/stream-stack/stream-stack.js b/node_modules/stream-stack/stream-stack.js new file mode 100644 index 0000000..a0a1fb9 --- /dev/null +++ b/node_modules/stream-stack/stream-stack.js @@ -0,0 +1,209 @@ +var Stream = require('stream').Stream; + +/** + * StreamStack + * ----------- + * Turns low-level `Stream` objects into stackable stream, meant + * to fill out your desired protocol stack. But also allow for + * the protocol to be implemented independent of the underlying + * transport. + * An example overall stack could look like: + * - net.Stream <- TCP Layer + * - HttpRequestStack <- HTTP Layer + * - `write()`s an HTTP request upstream + * - Response comes back with 'gzip' transfer-encoding + * - GzipDecoderStack <- Decoding Layer + * - `.pipe()` into a 'fs.WriteStream' <- Save to a File + */ +function StreamStack(stream, events) { + if (!(stream instanceof Stream)) { + throw new Error("StreamStack expects an instance of 'Stream' as an argument!"); + } + if (!(this instanceof StreamStack)) { + return new StreamStack(stream, events); + } + + Stream.call(this); + + // If this is the first time the parent stream has been used in a + // StreamStack, then a StackEmitter will need to be injected into the stream. + if (!stream._stackEmitter) { + StackEmitter.call(stream); + } + stream._stacks.push(this); + + // A reference to the parent stream for event handlers, etc. + this.stream = stream; + + // TODO: Remove, if I can find a good reason to. + events = events || {}; + if (!('data' in events)) + events.data = proxyEvent('data'); + if (!('end' in events)) + events.end = proxyEvent('end'); + if (!('error' in events)) + events.error = proxyEvent('error'); + if (!('close' in events)) + events.close = proxyEvent('close'); + if (!('fd' in events)) + events.fd = proxyEvent('fd'); + if (!('drain' in events)) + events.drain = proxyEvent('drain'); + + // If the StreamStack instance intends on intercepting events emitted from + // the parent stream, then the handlers need to be passed as a second 'events' + // object in the constructor. It takes care of attaching them to the parent + // stream. Handlers are invoked in 'this' StreamStack instance. + if (events) { + this._stackEvents = {}; + for (var ev in events) { + this._stackEvents[ev] = events[ev].bind(this); + stream.on(ev, this._stackEvents[ev]); + } + } + +} +require('util').inherits(StreamStack, Stream); +exports.StreamStack = StreamStack; + +// By default, just proxy all the standard ReadStream and WriteStream +// functions upstream. If the StreamStack implementation needs to overwrite +// or augment any of the behavior, then simply overwrite that function. +// The most common is to augment the 'write()' function, such that the +// passed data goes through some kind of filter before being passed to +// the parent stream. +StreamStack.prototype.write = function(buf, type) { + return this.stream.write(buf, type); +} +StreamStack.prototype.end = function(buf, type) { + if (buf) { + this.write(buf, type); + } + return this.stream.end(); +} +StreamStack.prototype.pause = function() { + if (this.stream.pause) { + return this.stream.pause(); + } else { + return this.stream.emit('pause'); + } +} +StreamStack.prototype.resume = function() { + if (this.stream.resume) { + return this.stream.resume(); + } else { + return this.stream.emit('resume'); + } +} +StreamStack.prototype.destroy = function(error) { + return this.stream.destroy(error); +} + +// The 'cleanup()' function should be called after a StreamStack instance is +// finished doing it's "thing", to cleanly allow another new StreamStack +// instance to be attached to the parent Stream. +StreamStack.prototype.cleanup = function() { + // Remove 'this' from the parent Stream's '_stacks' Array + var index = this.stream._stacks.indexOf(this); + this.stream._stacks.splice(index, 1); + // Set 'this.stream' to null. + // If any events were binded through the constructor, they get unbinded here + if (this._stackEvents) { + for (var ev in this._stackEvents) { + this.stream.removeListener(ev, this._stackEvents[ev]); + } + this._stackEvents = null; + } + // TODO: Maybe 'delete' instead? Is there any benefit? + this.stream = null; +} + +// By default, the 'readable' and 'writable' property lookups get proxied +// to the parent stream. You can set the variables if needed, and to relinquish +// control of the variable back upstream, set it to `undefined`. +Object.defineProperty(StreamStack.prototype, "readable", { + get: function() { + if (this._readable != undefined) { + return this._readable; + } + return this.stream.readable; + }, + set: function(value) { + this._readable = value; + }, + enumerable: true +}); +Object.defineProperty(StreamStack.prototype, "writable", { + get: function() { + if (this._writable != undefined) { + return this._writable; + } + return this.stream.writable; + }, + set: function(value) { + this._writable = value; + }, + enumerable: true +}); + +// Walks up the 'stream' properties until it finds and returns the top-most +// stream. i.e. it gets the low-level stream this stack is based on. +Object.defineProperty(StreamStack.prototype, "topStream", { + get: function() { + var rtn = this.stream; + while (rtn.stream) { + rtn = rtn.stream; + } + return rtn; + }, + enumerable: true +}); + +// Stupid workaround. Attach a listener for the given 'eventName'. +// The callback simply re-emits the events and all arguments on 'this'. +function proxyEvent(eventName) { + return function() { + var args = [eventName]; + args = args.concat(args.slice.call(arguments)); + this.emit.apply(this, args); + } +} + + +// Parent streams need to have StackEmitter called on them the first time a +// StreamStack instance is attempting to use it. The __proto__ of the parent +// stream will be injected with StackEmitter's prototype, to benefit from +// the overwritten 'emit()' function. +function StackEmitter() { + // The Array that holds the active StreamStack instances on a parent Stream. + this._stacks = []; + // Get a reference to the original 'emit' function, since we're about to + // monkey-patch with our own 'emit' function. + this._origEmit = this.emit; + // Mix-in the rest of the StackEmitter properties. + for (var prop in StackEmitter.prototype) { + this[prop] = StackEmitter.prototype[prop]; + } +} + +// A flag to indicate that the parent stream has already been injected. +StackEmitter.prototype._stackEmitter = true; + +// The custom 'emit()' function is responsible for iterating through the list +// of active StreamStack instances, and IFF the StreamStack instance didn't +// pass a handler to the current event, it should re-emit on the child as well. +StackEmitter.prototype.emit = function(eventName) { + var stack; + // Emit on the parent Stream first + var rtn = this._origEmit.apply(this, arguments); + // Next re-emit on all the active StreamStack instances (if any) + for (var i=0, l=this._stacks.length; i", + "author": { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net" + }, "keywords": [ "MODBUS", "protocol", @@ -19,13 +22,20 @@ }, "main": "./modbus-stack", "scripts": { - "test": "expresso test/test*.js" + "test": "expresso test/test*.js", + "start": "node server.js" }, "engines": { "node": ">= 0.3.0" }, "directories": {}, - "files": [ - "" - ] -} \ No newline at end of file + "files": [], + "readme": "node-modbus-stack\n=================\n### A [StreamStack][] implementation of the [MODBUS][Modbus] protocol for [Node][].\n\nThis module exposes two concrete `StreamStack` implementations:\n`ModbusRequestStack` can be used as a MODBUS client (i.e. Master), and can write\nMODBUS compliant requests and listen for the response.\n`ModbusResponseStack` can be used to create a MODBUS server (i.e. Slave), by\nlistening for requests and providing a convenient API to respond with.\n\n[MODBUS][ModbusWiki] is an open building automation protocol that is widely used\nin various monitoring and controlling equipment. It's used with a variety of\ndifferent transports, including TCP.\n\nCurrently only communication through the TCP protocol is supported, however\nRS-485 serial support should be possible with [node-serialport]. I haven't\nhad a chance to look into it yet.\n\n\nA MODBUS Master (Client)\n------------------------\n\nYou will need to know which _Function Code_ (defined in the MODBUS specification)\nyou are invoking on the remote MODBUS slave. In this example, we'll request to\nread from the current values of the first 50 __Input Registers__ on the slave:\n\n // 'RIR' contains the \"Function Code\" that we are going to invoke on the remote device\n var RIR = require('modbus-stack').FUNCTION_CODES.READ_INPUT_REGISTERS;\n \n // IP and port of the MODBUS slave, default port is 502\n var client = require('modbus-stack/client').createClient(502, '10.0.1.50');\n \n // 'req' is an instance of the low-level `ModbusRequestStack` class\n var req = client.request(RIR, // Function Code: 4\n 0, // Start at address 0\n 50); // Read 50 contiguous registers from 0\n \n // 'response' is emitted after the entire contents of the response has been received.\n req.on('response', function(registers) {\n // An Array of length 50 filled with Numbers of the current registers.\n console.log(registers);\n client.end();\n });\n\n\nA MODBUS Slave (Server)\n-----------------------\n\n`node-modbus-stack` makes it dead simple to create a compliant MODBUS Slave (or Server)\nwritten in pure JavaScript. Here's an example of a server that would respond to the\nrequest above:\n\n var FC = require('modbus-stack').FUNCTION_CODES;\n \n // 'handlers' is an Object with keys containing the \"Function Codes\" that your MODBUS\n // server will handle. Anything function code requested without a handler defined here\n // will have the Server transparently respond with Exception Code 1 (\"Illegal Function\")\n var handlers = {};\n \n // Define a handler for \"Read Input Registers\". We'll just respond with the register\n // number requested. In a real-world situation, you'd probably look up these values from\n // a database, etc.\n handlers[FC.READ_INPUT_REGISTERS] = function(request, response) {\n var start = request.startAddress;\n var length = request.quantity;\n \n var resp = new Array(length);\n for (var i=0; i Date: Thu, 19 Dec 2013 07:08:19 +0100 Subject: [PATCH 2/3] cleanup --- modbus-stack.js~ | 278 ----------- node_modules/bufferlist/LICENSE | 4 - node_modules/bufferlist/README.markdown | 71 --- node_modules/bufferlist/binary.js | 440 ------------------ node_modules/bufferlist/bufferlist.js | 162 ------- node_modules/bufferlist/examples/binary.js | 56 --- node_modules/bufferlist/examples/hackneyed.js | 16 - .../bufferlist/examples/simple_binary.js | 22 - .../bufferlist/examples/simple_bufferlist.js | 13 - node_modules/bufferlist/package.json | 34 -- node_modules/bufferlist/test/advance.js | 25 - node_modules/bufferlist/test/binary.js | 86 ---- node_modules/bufferlist/test/binary_assign.js | 73 --- .../bufferlist/test/binary_endianness.js | 243 ---------- node_modules/bufferlist/test/binary_event.js | 67 --- node_modules/bufferlist/test/binary_into.js | 49 -- node_modules/bufferlist/test/binary_jump.js | 55 --- node_modules/bufferlist/test/binary_loop.js | 115 ----- node_modules/bufferlist/test/client_server.js | 48 -- node_modules/bufferlist/test/event.js | 46 -- node_modules/bufferlist/test/join.js | 26 -- node_modules/bufferlist/test/take.js | 39 -- node_modules/put/LICENSE | 21 - node_modules/put/README.md | 57 --- node_modules/put/examples/buf.js | 12 - node_modules/put/examples/stream.js | 9 - node_modules/put/index.js | 100 ---- node_modules/put/package.json | 36 -- node_modules/put/test/buf.js | 70 --- node_modules/put/test/c/ftoi | Bin 4632 -> 0 bytes node_modules/put/test/c/ftoi.c | 7 - node_modules/put/test/c/itof | Bin 4616 -> 0 bytes node_modules/put/test/c/itof.c | 7 - node_modules/put/test/float.js_ | 9 - node_modules/put/test/stream.js | 28 -- node_modules/stream-stack/.npmignore | 1 - node_modules/stream-stack/API.md | 63 --- node_modules/stream-stack/LICENSE | 22 - node_modules/stream-stack/README.md | 65 --- node_modules/stream-stack/package.json | 35 -- node_modules/stream-stack/stream-stack.js | 209 --------- .../stream-stack/test/test-custom-edit.js | 28 -- .../test/test-fakeDuplexStream.js | 78 ---- .../stream-stack/test/test-parent-emits.js | 66 --- .../stream-stack/test/test-proxy-events.js | 75 --- .../stream-stack/test/test-topStream.js | 22 - node_modules/stream-stack/util.js | 61 --- 47 files changed, 3049 deletions(-) delete mode 100644 modbus-stack.js~ delete mode 100644 node_modules/bufferlist/LICENSE delete mode 100644 node_modules/bufferlist/README.markdown delete mode 100644 node_modules/bufferlist/binary.js delete mode 100644 node_modules/bufferlist/bufferlist.js delete mode 100644 node_modules/bufferlist/examples/binary.js delete mode 100644 node_modules/bufferlist/examples/hackneyed.js delete mode 100644 node_modules/bufferlist/examples/simple_binary.js delete mode 100644 node_modules/bufferlist/examples/simple_bufferlist.js delete mode 100644 node_modules/bufferlist/package.json delete mode 100644 node_modules/bufferlist/test/advance.js delete mode 100644 node_modules/bufferlist/test/binary.js delete mode 100644 node_modules/bufferlist/test/binary_assign.js delete mode 100644 node_modules/bufferlist/test/binary_endianness.js delete mode 100644 node_modules/bufferlist/test/binary_event.js delete mode 100644 node_modules/bufferlist/test/binary_into.js delete mode 100644 node_modules/bufferlist/test/binary_jump.js delete mode 100644 node_modules/bufferlist/test/binary_loop.js delete mode 100644 node_modules/bufferlist/test/client_server.js delete mode 100644 node_modules/bufferlist/test/event.js delete mode 100644 node_modules/bufferlist/test/join.js delete mode 100644 node_modules/bufferlist/test/take.js delete mode 100644 node_modules/put/LICENSE delete mode 100644 node_modules/put/README.md delete mode 100644 node_modules/put/examples/buf.js delete mode 100644 node_modules/put/examples/stream.js delete mode 100644 node_modules/put/index.js delete mode 100644 node_modules/put/package.json delete mode 100644 node_modules/put/test/buf.js delete mode 100644 node_modules/put/test/c/ftoi delete mode 100644 node_modules/put/test/c/ftoi.c delete mode 100644 node_modules/put/test/c/itof delete mode 100644 node_modules/put/test/c/itof.c delete mode 100644 node_modules/put/test/float.js_ delete mode 100644 node_modules/put/test/stream.js delete mode 100644 node_modules/stream-stack/.npmignore delete mode 100644 node_modules/stream-stack/API.md delete mode 100644 node_modules/stream-stack/LICENSE delete mode 100644 node_modules/stream-stack/README.md delete mode 100644 node_modules/stream-stack/package.json delete mode 100644 node_modules/stream-stack/stream-stack.js delete mode 100644 node_modules/stream-stack/test/test-custom-edit.js delete mode 100644 node_modules/stream-stack/test/test-fakeDuplexStream.js delete mode 100644 node_modules/stream-stack/test/test-parent-emits.js delete mode 100644 node_modules/stream-stack/test/test-proxy-events.js delete mode 100644 node_modules/stream-stack/test/test-topStream.js delete mode 100644 node_modules/stream-stack/util.js diff --git a/modbus-stack.js~ b/modbus-stack.js~ deleted file mode 100644 index 4b12db5..0000000 --- a/modbus-stack.js~ +++ /dev/null @@ -1,278 +0,0 @@ -var StreamStack = require('stream-stack').StreamStack; -var Put = require('put'); -var BufferList = require('bufferlist').BufferList; -var Binary = require('bufferlist/binary').Binary; -var inherits = require('util').inherits; -var client = require('./client'); -var server = require('./server'); -var slice = Array.prototype.slice; - -// The byte length of the "MODBUS Application Protocol" header. -const MBAP_LENGTH = 7; - -// The byte length of the "MODBUS Function Code". -const FUNCTION_CODE_LENGTH = 1; - -// An exception response from a MODBUS slave (server) will have -// the high-bit (0x80) set on it's function code. -const EXCEPTION_BIT = 1 << 7; - -// If it's an exception response, then the next byte will be one -// these exception codes, indicating the reason for the failure. -exports.EXCEPTION_CODES = { - 1 : 'Illegal Function', - 2 : 'Illegal Data Address', - 3 : 'Illegal Data Value', - 4 : 'Slave Device Failure', - 5 : 'Acknowledge', - 6 : 'Slave Device Busy', - 8 : 'Memory Parity Error', - 10: 'Gateway Path Unavailable', - 11: 'Gateway Target Path Failed to Respond' -}; - -// Each of the function codes has a potentially different body payload -// and potentially different parameters to send. Each function code needs -// a 'request' and 'response' parser in the "client.js" and "server.js" files. -exports.FUNCTION_CODES = { - READ_COILS: 1, - READ_DISCRETE_INPUTS: 2, - READ_HOLDING_REGISTERS: 3, - READ_INPUT_REGISTERS: 4, - WRITE_SINGLE_COIL: 5, - WRITE_SINGLE_REGISTER: 6, - READ_EXCEPTION_STATUS: 7, // Serial Line only - DIAGNOSTICS: 8, // Serial Line only - PROGRAM_484: 9, - POLL_484: 10, - GET_COMM_EVENT_COUNTER: 11,// Serial Line only - GET_COMM_EVENT_LOG: 12,// Serial Line only - PROGRAM_CONTROLLER: 13, - POLL_CONTROLLER: 14, - WRITE_MULTIPLE_COILS: 15, - WRITE_MULTIPLE_REGISTERS: 16, - REPORT_SLAVE_ID: 17,// Serial Line only - PROGRAM_884_M84: 18, - RESET_COMM_LINK: 19, - READ_FILE_RECORD: 20, - WRITE_FILE_RECORD: 21, - MASK_WRITE_REGISTER: 22, - READ_WRITE_MULTIPLE_REGISTERS:23, - READ_FIFO_QUEUE: 24, - ENCAPSULATED_INFERFACE_TRANSPORT:43 -}; - -function ModbusRequestStack(stream) { - StreamStack.call(this, stream, { - data: this._onData - }); - this.bufferlist = new BufferList(); - if (this.stream._reqNum) { - this.stream._reqNum++; - } else { - this.stream._reqNum = 1; - } -} -inherits(ModbusRequestStack, StreamStack); -exports.ModbusRequestStack = ModbusRequestStack; - -// The 'version' of the MODBUS protocol. Only version 0 is defined. -ModbusRequestStack.prototype.protocolVersion = 0; - -// The unit identifier to request. This is usually important for -// serial lines, not so much over TCP. -ModbusRequestStack.prototype.unitIdentifier = 1; - -// Make a MODBUS request for a given 'function code'. -ModbusRequestStack.prototype.request = function(functionCode) { - if (!client.REQUESTS[functionCode]) { - throw new Error('"REQUESTS['+functionCode+']" in "client.js" is not implemented!'); - } - this.functionCode = functionCode; - var argsLen = arguments.length; - if (argsLen > 1) { - var callback = arguments[argsLen-1]; - if (typeof(callback) == 'function') { - this.on('error', callback); - this.on('response', function(res) { - callback(null, res); - }); - } else { callback = null; } - } - var args = slice.call(arguments, 1, argsLen-(callback?1:0)); - try { - var pdu = client.REQUESTS[functionCode].apply(this, args); - } catch(e) { - this.emit('error', e); - return false; - } - var buf = Put() - .word16be(this.stream._reqNum) - .word16be(this.protocolVersion) - .word16be(pdu.length+2) - .word8(this.unitIdentifier) - .word8(functionCode) - .put(pdu) - .buffer(); - return this.stream.write(buf); -} - -ModbusRequestStack.prototype._onData = function(chunk) { - if (chunk) { - this.bufferlist.push(chunk); - //console.log(chunk); - } - if (!this.responseHeader && this.bufferlist.length >= MBAP_LENGTH) { - this.responseHeader = readMBAP(this.bufferlist); - // Re-check the bufferlist to see if we have the rest of the response already - this._onData(); - } else if (!this._resFunctionCode && this.responseHeader && this.bufferlist.length >= 1) { - // Get the function code - this._resFunctionCode = readFunctionCode(this.bufferlist); - //console.log(this._resFunctionCode); - this._onData(); - } else if (this.responseHeader && this._resFunctionCode >= 1 && this.bufferlist.length >= (this.responseHeader.length-2)) { - // We have the complete response. - if (this._resFunctionCode & EXCEPTION_BIT) { - // An exception was returned as the response! - var code = this.bufferlist.take(1)[0]; - this.bufferlist.advance(1); - var err = new Error(exports.EXCEPTION_CODES[code]); - err.errno = code; - this.emit('error', err); - } else { - if (!client.RESPONSES[this._resFunctionCode]) { - return this.emit('error', new Error('"RESPONSES['+this._resFunctionCode+']" in "client.js" is not implemented!')); - } - try { - var response = client.RESPONSES[this._resFunctionCode].call(this, this.bufferlist); - } catch(e) { - return this.emit('error', e); - } - this.bufferlist.advance(this.responseHeader.length-2); - // Explicitly set the 'functionCode' property. - response.functionCode = this._resFunctionCode; - delete this._resFunctionCode; - // Modbus request/response complete; invoke callbacks and cleanup! - this.emit('response', response); - } - this.cleanup(); - } -} - - - -function ModbusResponseStack(stream) { - StreamStack.call(this, stream, { - data: this._onData - }); - this.bufferlist = new BufferList(); -} -inherits(ModbusResponseStack, StreamStack); -exports.ModbusResponseStack = ModbusResponseStack; - -ModbusResponseStack.prototype._onData = function(chunk) { - if (chunk) { - this.bufferlist.push(chunk); - //console.log(chunk); - } - if (!this.requestHeader && this.bufferlist.length >= MBAP_LENGTH) { - this.requestHeader = readMBAP(this.bufferlist); - //console.log(this.requestHeader); - // Re-check the bufferlist to see if we have the rest of the request - // already (we probably do, it's usually sent in the same packet). - this._onData(); - } else if (!this.functionCode && this.requestHeader && this.bufferlist.length >= 1) { - // Get the function code - this.functionCode = readFunctionCode(this.bufferlist); - //console.log(this.functionCode); - this._onData(); - } else if (this.requestHeader && this.functionCode >= 1 && this.bufferlist.length >= (this.requestHeader.length-2)) { - // We have the complete request. - if (!server.REQUESTS[this.functionCode]) { - return this.emit('error', new Error('"REQUESTS['+this.functionCode+']" in "server.js" is not implemented!')); - } - try { - this.request = server.REQUESTS[this.functionCode].call(this, this.bufferlist); - } catch(e) { - return this.emit('error', e); - } - this.request.functionCode = this.functionCode; - for (var key in this.requestHeader) { - this.request[key] = this.requestHeader[key]; - } - delete this.request.length; - this.bufferlist.advance(this.requestHeader.length-2); - //console.log('bufferlist.length: ' + this.bufferlist.length); - this._gotRequest = true; - this.emit('request', this.request); - //console.log(JSON.stringify(this.request)); - } -} - -// Sends back the response after receiving a request. -ModbusResponseStack.prototype.writeResponse = function() { - if (!this._gotRequest) { - throw new Error('Can\'t call "writeResponse" until after the "request" event'); - } - if (!server.RESPONSES[this.functionCode]) { - throw new Error('"RESPONSES['+this.functionCode+']" in "server.js" is not implemented!'); - } - try { - var pdu = server.RESPONSES[this.functionCode].apply(this, arguments); - } catch(e) { - this.emit('error', e); - return false; - } - var rtn = this.stream.write(Put() - .word16be(this.request.transactionId) - .word16be(this.request.protocolVersion) - .word16be(pdu.length+2) - .word8(this.request.unitIdentifier) - .word8(this.functionCode) - .put(pdu) - .buffer()); - this.cleanup(); - return rtn; -} - -// Sends back an exception response after receiving a request. -ModbusResponseStack.prototype.writeException = function(exceptionCode) { - if (!this._gotRequest) { - throw new Error('Can\'t call "writeException" until after the "request" event'); - } - var rtn = this.stream.write(Put() - .word16be(this.request.transactionId) - .word16be(this.request.protocolVersion) - .word16be(3) - .word8(this.request.unitIdentifier) - .word8(this.functionCode | EXCEPTION_BIT) - .word8(exceptionCode) - .buffer()); - this.cleanup(); - return rtn; -} - - -// Reads the "MODBUS Application Protocol" header from the given bufferlist, -// and return a object with 'transactionId', 'protocolVersion', 'length', and -// 'unitIdentifier' properties (standard for both client and server). -function readMBAP(bufferlist) { - var mbap = Binary(bufferlist) - .getWord16be('transactionId') - .getWord16be('protocolVersion') - .getWord16be('length') - .getWord8('unitIdentifier') - .end().vars; - bufferlist.advance(MBAP_LENGTH); - return mbap; -} -exports.readMBAP = readMBAP; - -// Reads the "MODBUS Function Code", which comes immediately after the MBAP. -function readFunctionCode(bufferlist) { - var rtn = bufferlist.take(FUNCTION_CODE_LENGTH)[0]; - bufferlist.advance(FUNCTION_CODE_LENGTH); - return rtn; -} -exports.readFunctionCode = readFunctionCode; diff --git a/node_modules/bufferlist/LICENSE b/node_modules/bufferlist/LICENSE deleted file mode 100644 index 0471ea3..0000000 --- a/node_modules/bufferlist/LICENSE +++ /dev/null @@ -1,4 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT license: -http://www.opensource.org/licenses/mit-license.php diff --git a/node_modules/bufferlist/README.markdown b/node_modules/bufferlist/README.markdown deleted file mode 100644 index 7be7152..0000000 --- a/node_modules/bufferlist/README.markdown +++ /dev/null @@ -1,71 +0,0 @@ -BufferList -========== -BufferList provides an interface to treat a linked list of buffers as a single -stream. This is useful for events that produce a many small Buffers, such as -network streams. - -Installation -============ -Install using npm: - npm install bufferlist - -Or, check out the repository and have npm link to your development copy. This -is useful for developing the library, and is necessary when running the tests, -since they refer to the installed names of the library files. - git clone http://github.com/substack/node-bufferlist.git - cd node-bufferlist - npm link . - -Simple Bufferlist Example -========================= - - #!/usr/bin/env node - var sys = require('sys'); - var Buffer = require('buffer').Buffer; - var BufferList = require('bufferlist').BufferList; - - var b = new BufferList; - ['abcde','xyz','11358'].forEach(function (s) { - var buf = new Buffer(s.length); - buf.write(s); - b.push(buf); - }); - - sys.puts(b.take(10)); // abcdexyz11 - -Binary -====== -This distribution also contains a Binary module for parsing these bufferlists. - -Simple Binary Example -===================== - - #!/usr/bin/env node - - var sys = require('sys'); - var Buffer = require('buffer').Buffer; - var BufferList = require('bufferlist').BufferList; - var Binary = require('bufferlist/binary').Binary; - - var bufferList = new BufferList; - var binary = Binary(bufferList) - .getWord16be('xLen') - .getBuffer('xs', 'xLen') - .tap(function (vars) { - vars.moo = 'xs:' + vars.xLen + ':' + vars.xs; - }) - .end() - ; - - var buf = new Buffer(6); - buf.write('\x00\x04meow', 'binary'); - bufferList.push(buf); - - sys.puts(binary.vars.moo); // xs:4:meow - -See Also -======== -See the examples/ directory for more involved examples. - -See http://github.com/substack/node-rfb for a practical application of this -distribution. diff --git a/node_modules/bufferlist/binary.js b/node_modules/bufferlist/binary.js deleted file mode 100644 index ab58b33..0000000 --- a/node_modules/bufferlist/binary.js +++ /dev/null @@ -1,440 +0,0 @@ -var BufferList = require('bufferlist'); -var EventEmitter = require('events').EventEmitter; -var util = require('util'); - -module.exports = Binary; -module.exports.Binary = Binary; // backwards compatibility - -Binary.prototype = new EventEmitter; -function Binary(buffer) { - if (!(this instanceof Binary)) return new Binary(buffer); - var self = this; - - this.vars = {}; - this.offset = 0; - this.actions = []; - this.parent = null; - - // an explicit end loads all the actions before any evaluation happens - this.end = function () { - if (buffer.listeners('write').indexOf(update) < 0) { - buffer.on('write', update); - } - update(); - return this; - }; - - // Signify to the parent that processing should stop. - this.exit = function () { - this.pushAction({ - ready : true, - action : function () { - this.actions = []; - if (this.parent) this.parent.actions = []; - }, - }); - return this; - }; - - function update () { - var action = self.actions[0]; - if (!action) { - buffer.removeListener('write', update); - self.emit('end', self.vars); - } - else if (action.ready.call(self, self.vars)) { - self.actions.shift(); - - if (action.context == false) { - action.action.call(self, self.vars); - self.end(); - } - else { - buffer.removeListener('write', update); - - var child = new Binary(buffer); - child.vars = self.vars; - child.parent = self; - child.offset = self.offset; - - child.on('end', function () { - self.offset = child.offset; - buffer.on('write', update); - self.end(); - }); - - action.action.call(child, child.vars); - child.end(); - } - } - } - - this.pushAction = function (action) { - if (!action) throw "Action not specified"; - var ready = { - 'function' : action.ready, - 'boolean' : function () { return action.ready }, - }[typeof(action.ready)]; - if (!ready) throw "Unknown action.ready type"; - this.actions.push({ - 'action' : action.action, - 'ready' : ready, - 'context' : action.context || false, - }); - }; - - this.flush = function () { - this.pushAction({ - ready : true, - action : function () { - buffer.advance(this.offset); - this.offset = 0; - }, - }); - return this; - }; - - this.skip = function (bytes) { - this.pushAction({ - ready : true, - action : function () { - this.offset += bytes; - }, - }); - return this; - }; - - this.tap = function (f) { - this.pushAction({ - ready : true, - context : true, - action : function () { - f.call(this, this.vars); - }, - }); - return this; - }; - - this.when = function (v1, v2, f) { - var f1 = typeof(v1) == 'string' - ? function (vars) { return lookup(this,v1) } - : function (vars) { return v1 } - ; - var f2 = typeof(v2) == 'string' - ? function (vars) { return lookup(this,v2) } - : function (vars) { return v2 } - ; - return this.tap(function () { - if (f1.call(this,this.vars) == f2.call(this,this.vars)) { - f.call(this, this.vars); - } - }); - }; - - this.unless = function (v1, v2, f) { - var f1 = typeof(v1) == 'string' - ? function (vars) { return lookup(this,v1) } - : function (vars) { return v1 } - ; - var f2 = typeof(v2) == 'string' - ? function (vars) { return lookup(this,v2) } - : function (vars) { return v2 } - ; - return this.tap(function () { - if (f1.call(this,this.vars) != f2.call(this,this.vars)) { - f.call(this, this.vars); - } - }); - }; - - this.repeat = function (n, f) { - var nf = typeof(n) == 'string' - ? function (vars) { return lookup(this,n) } - : function (vars) { return n } - ; - this.pushAction({ - ready : true, - context : true, - action : function () { - var nn = nf.call(this, this.vars); - for (var i = 0; i < nn; i++) { - f.call(this, this.vars, i); - } - }, - }); - return this; - }; - - this.forever = function (f) { - self.foreverfunc = f; - self.foreveraction = { - ready : true, - context : true, - action : function () { - self.foreverfunc.call(this, this.vars); - self.pushAction(self.foreveraction); - }, - }; - this.pushAction(self.foreveraction); - return this; - }; - - // assign immediately - function assign (self, key, value) { - visit( - self, key instanceof Array ? key : [key], - function (v,k) { v[k] = value } - ); - } - - function lookup (self) { - var args = [].slice.call(arguments, 1); - return visit(self, args, function (v,k) { return v[k] }); - } - - function visit(self, args, f) { - var keys = args.reduce(function (acc,x) { - return acc.concat(x.split('.')) - },[]) - ; - - var obj = self.vars; - keys.slice(0,-1).forEach(function (k) { - if (!obj[k]) obj[k] = {}; - obj = obj[k]; - }); - - return f(obj, keys.slice(-1)[0]); - } - - // Assign into a variable. All but the last argument make up the key, which - // may describe a deeply nested address. If the last argument is a: - // * function - assign the variables from the inner chain - // * string - assign from the key name - // * number - assign from this value - this.into = function () { - var args = [].concat.apply([],arguments); - var keys = args.slice(0,-1); - var fv = args.slice(-1)[0]; - - return this.tap(function (vars) { - if (typeof fv == 'function') { - var topVars = this.vars; - this.vars = {}; - fv.call(this, this.vars); - this.pushAction({ - ready : true, - action : function () { - var localVars = this.vars; - this.vars = topVars; - assign(this, keys, localVars); - } - }); - } - else if (typeof fv == 'string') { - assign(this, keys, lookup(this,fv)); - } - else if (typeof fv == 'number') { - assign(this, keys, fv); - } - else { - throw TypeError( - 'Last argument to .into must be a string, number, ' - + 'or a function, not a "' + typeof fv + '".' - + 'Value supplied: ' + util.inspect(fv) - ); - } - }); - }; - - function get (opts) { - var into = [].reduce.call(opts.into, function (acc,x) { - return acc.concat(x); - }, []); - - this.pushAction({ - ready : function () { - return buffer.length - this.offset >= opts.bytes; - }, - action : function () { - var data = buffer.join(this.offset, this.offset + opts.bytes); - this.offset += opts.bytes; - var decodeLittleEndian = opts.signed ? decodeLEs : decodeLE; - var decodeBigEndian = opts.signed ? decodeBEs : decodeBE; - assign(this, into, - opts.endian && opts.endian == 'little' - ? decodeLittleEndian(data) - : decodeBigEndian(data) - ); - - }, - }); - return this; - }; - - this.getWord8 = function () { - return get.call( - this, { into : arguments, bytes : 1 } - ); - }; - - this.getWord16be = function () { - return get.call( - this, { into : arguments, bytes : 2, endian : 'big' } - ); - }; - - this.getWord16bes = function () { - return get.call( - this, { into : arguments, bytes : 2, endian : 'big', signed : true } - ); - } - - this.getWord16le = function () { - return get.call( - this, { into : arguments, bytes : 2, endian : 'little' } - ); - }; - - this.getWord16les = function () { - return get.call( - this, { into : arguments, bytes : 2, endian : 'little', - signed : true } - ); - } - - this.getWord32be = function () { - return get.call( - this, { into : arguments, bytes : 4, endian : 'big' } - ); - }; - - this.getWord32bes = function () { - return get.call( - this, { into : arguments, bytes : 4, endian : 'big', - signed : true } - ); - }; - - this.getWord32le = function () { - return get.call( - this, { into : arguments, bytes : 4, endian : 'little' } - ); - }; - - this.getWord32les = function () { - return get.call( - this, { into : arguments, bytes : 4, endian : 'little', - signed: true } - ); - }; - - this.getWord64be = function () { - return get.call( - this, { into : arguments, bytes : 8, endian : 'big' } - ); - }; - - this.getWord64bes = function () { - return get.call( - this, { into : arguments, bytes : 8, endian : 'big', - signed : true } - ); - }; - - this.getWord64le = function () { - return get.call( - this, { into : arguments, bytes : 8, endian : 'little' } - ); - }; - - this.getWord64les = function () { - return get.call( - this, { into : arguments, bytes : 8, endian : 'little', - signed : true } - ); - }; - - this.getBuffer = function () { - var args = [].concat.apply([],arguments); - // flatten :into so .getBuffer(['foo','bar','baz'],10) - // and .getBuffer('foo','bar','baz',10) both work - var into = args.slice(0,-1).reduce(function f (acc,x) { - return acc.concat( - x instanceof Array ? x.reduce(f) : x.split('.') - ); - }, []); - var length = args.slice(-1)[0]; - var lengthF; - - if (typeof(length) == 'string') { - var s = length; - lengthF = function (vars) { return lookup(this,s) }; - } - else if (typeof(length) == 'number') { - var s = length; - lengthF = function (vars) { return s }; - } - else if (length instanceof Function) { - lengthF = length; - } - else { - throw TypeError( - 'Last argument to getBuffer (length) must be a string, number, ' - + 'or a function, not a "' + typeof(length) + '".' - + 'Value supplied: ' + util.inspect(length) - ); - } - - this.pushAction({ - ready : function () { - var s = lengthF.call(this,this.vars); - return s && buffer.length - this.offset >= s; - }, - action : function () { - var s = lengthF.call(this,this.vars); - var data = buffer.join(this.offset, this.offset + s); - this.offset += s; - assign(this, into, data); - }, - }); - return this; - }; -} - -// convert byte strings to little endian numbers -function decodeLE (bytes) { - var acc = 0; - for (var i = 0; i < bytes.length; i++) { - acc += Math.pow(256,i) * bytes[i]; - } - return acc; -} - -// convert byte strings to big endian numbers -function decodeBE (bytes) { - var acc = 0; - for (var i = 0; i < bytes.length; i++) { - acc += Math.pow(256, bytes.length - i - 1) * bytes[i]; - } - return acc; -} - -// convert byte strings to signed big endian numbers -function decodeBEs (bytes) { - var val = decodeBE(bytes); - if ((bytes[0]&0x80) == 0x80) { - val -= Math.pow(256, bytes.length); - } - return val; -} - -// convert byte strings to signed little endian numbers -function decodeLEs (bytes) { - var val = decodeLE(bytes); - if ((bytes[bytes.length-1]&0x80) == 0x80) { - val -= Math.pow(256, bytes.length); - } - return val; -} - diff --git a/node_modules/bufferlist/bufferlist.js b/node_modules/bufferlist/bufferlist.js deleted file mode 100644 index fafc6a6..0000000 --- a/node_modules/bufferlist/bufferlist.js +++ /dev/null @@ -1,162 +0,0 @@ -// bufferlist.js -// Treat a linked list of buffers as a single variable-size buffer. -var Buffer = require('buffer').Buffer; -var EventEmitter = require('events').EventEmitter; - -module.exports = BufferList; -module.exports.BufferList = BufferList; // backwards compatibility - -function BufferList(opts) { - if (!(this instanceof BufferList)) return new BufferList(opts); - EventEmitter.call(this); - var self = this; - - if (typeof(opts) == 'undefined') opts = {}; - - // default encoding to use for take(). Leaving as 'undefined' - // makes take() return a Buffer instead. - self.encoding = opts.encoding; - - // constructor to use for Buffer-esque operations - self.construct = opts.construct || Buffer; - - var head = { next : null, buffer : null }; - var last = { next : null, buffer : null }; - - // length can get negative when advanced past the end - // and this is the desired behavior - var length = 0; - self.__defineGetter__('length', function () { - return length; - }); - - // keep an offset of the head to decide when to head = head.next - var offset = 0; - - // Write to the bufferlist. Emits 'write'. Always returns true. - self.write = function (buf) { - if (!head.buffer) { - head.buffer = buf; - last = head; - } - else { - last.next = { next : null, buffer : buf }; - last = last.next; - } - length += buf.length; - self.emit('write', buf); - return true; - }; - - self.end = function (buf) { - if (buf instanceof Buffer) self.write(buf); - }; - - // Push buffers to the end of the linked list. (deprecated) - // Return this (self). - self.push = function () { - var args = [].concat.apply([], arguments); - args.forEach(self.write); - return self; - }; - - // For each buffer, perform some action. - // If fn's result is a true value, cut out early. - // Returns this (self). - self.forEach = function (fn) { - if (!head.buffer) return new self.construct(0); - - if (head.buffer.length - offset <= 0) return self; - var firstBuf = new self.construct(head.buffer.length - offset); - head.buffer.copy(firstBuf, 0, offset, head.buffer.length); - - var b = { buffer : firstBuf, next : head.next }; - - while (b && b.buffer) { - var r = fn(b.buffer); - if (r) break; - b = b.next; - } - - return self; - }; - - // Create a single Buffer out of all the chunks or some subset specified by - // start and one-past the end (like slice) in bytes. - self.join = function (start, end) { - if (!head.buffer) return new self.construct(0); - if (start == undefined) start = 0; - if (end == undefined) end = self.length; - - var big = new self.construct(end - start); - var ix = 0; - self.forEach(function (buffer) { - if (start < (ix + buffer.length) && ix < end) { - // at least partially contained in the range - buffer.copy( - big, - Math.max(0, ix - start), - Math.max(0, start - ix), - Math.min(buffer.length, end - ix) - ); - } - ix += buffer.length; - if (ix > end) return true; // stop processing past end - }); - - return big; - }; - - // Advance the buffer stream by n bytes. - // If n the aggregate advance offset passes the end of the buffer list, - // operations such as .take() will return empty strings until enough data is - // pushed. - // Returns this (self). - self.advance = function (n) { - offset += n; - length -= n; - while (head.buffer && offset >= head.buffer.length) { - offset -= head.buffer.length; - head = head.next - ? head.next - : { buffer : null, next : null } - ; - } - self.emit('advance', n); - return self; - }; - - // Take n bytes from the start of the buffers. - // Returns a string. - // If there are less than n bytes in all the buffers or n is undefined, - // returns the entire concatenated buffer string. - self.take = function (n, encoding) { - if (n == undefined) n = self.length; - else if (typeof n !== 'number') { - encoding = n; - n = self.length; - } - var b = head; - if (!encoding) encoding = self.encoding; - if (encoding) { - var acc = ''; - self.forEach(function (buffer) { - if (n <= 0) return true; - acc += buffer.toString( - encoding, 0, Math.min(n,buffer.length) - ); - n -= buffer.length; - }); - return acc; - } else { - // If no 'encoding' is specified, then return a Buffer. - return self.join(0, n); - } - }; - - // The entire concatenated buffer as a string. - self.toString = function () { - return self.take('binary'); - }; -} -require('util').inherits(BufferList, EventEmitter); diff --git a/node_modules/bufferlist/examples/binary.js b/node_modules/bufferlist/examples/binary.js deleted file mode 100644 index 3c52973..0000000 --- a/node_modules/bufferlist/examples/binary.js +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env node - -var sys = require('sys'); -var net = require('net'); - -var BufferList = require('bufferlist'); -var Binary = require('bufferlist/binary'); - -function parser (sock) { - var bufferList = new BufferList; - sock.addListener('data', function (data) { - bufferList.push(data); - }); - - return Binary(bufferList) - .getWord16be('xLen') - .when('xLen', 0, function (vars) { - this - .getWord32le('msgLen') - .getBuffer('msg', 'msgLen') - .tap(function (vars) { - vars.moo = 'msg:' + vars.msgLen + ':' + vars.msg; - }) - .exit() - ; - }) - .getBuffer('xs', 'xLen') - .tap(function (vars) { - vars.moo = 'xs:' + vars.xLen + ':' + vars.xs; - }) - .end() - ; -} - -function serverSession (port, strings) { - // fire up a server to write the strings when a client connects - var server = net.createServer(function (stream) { - strings.forEach(function (s) { - stream.write(s); - }); - stream.end(); - server.close(); - }); - server.listen(port); - - // connect to the server and parse its output - var client = new net.Stream; - parser(client).addListener('end', function (vars) { - sys.puts(vars.moo); - client.end(); - }); - client.connect(port); -} - -serverSession(20801, ['\x00','\x04m','eow']); -serverSession(20802, ['\x00\x00','\x12\x00\x00\x00happy pur','ring c','ats']); diff --git a/node_modules/bufferlist/examples/hackneyed.js b/node_modules/bufferlist/examples/hackneyed.js deleted file mode 100644 index c53eebb..0000000 --- a/node_modules/bufferlist/examples/hackneyed.js +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node - -var sys = require('sys'); -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); - -var buf1 = new Buffer(5); buf1.write('abcde'); -var buf2 = new Buffer(3); buf2.write('xyz'); -var buf3 = new Buffer(5); buf3.write('11358'); - -var b = new BufferList; -b.push(buf1,buf2,buf3); - -sys.puts(b.take(10)); // abcdexyz11 -sys.puts(b.take(3)); // abc -sys.puts(b.take(100)); // abcdexyz11358 diff --git a/node_modules/bufferlist/examples/simple_binary.js b/node_modules/bufferlist/examples/simple_binary.js deleted file mode 100644 index ae8a824..0000000 --- a/node_modules/bufferlist/examples/simple_binary.js +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env node - -var sys = require('sys'); -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); -var Binary = require('bufferlist/binary'); - -var bufferList = new BufferList; -var binary = Binary(bufferList) - .getWord16be('xLen') - .getBuffer('xs', 'xLen') - .tap(function (vars) { - vars.moo = 'xs:' + vars.xLen + ':' + vars.xs; - }) - .end() -; - -var buf = new Buffer(6); -buf.write('\x00\x04meow', 'binary'); -bufferList.push(buf); - -sys.puts(binary.vars.moo); // xs:4:meow diff --git a/node_modules/bufferlist/examples/simple_bufferlist.js b/node_modules/bufferlist/examples/simple_bufferlist.js deleted file mode 100644 index c48ca27..0000000 --- a/node_modules/bufferlist/examples/simple_bufferlist.js +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env node -var sys = require('sys'); -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); - -var b = new BufferList; -['abcde','xyz','11358'].forEach(function (s) { - var buf = new Buffer(s.length); - buf.write(s); - b.push(buf); -}); - -sys.puts(b.take(10)); // abcdexyz11 diff --git a/node_modules/bufferlist/package.json b/node_modules/bufferlist/package.json deleted file mode 100644 index eda3042..0000000 --- a/node_modules/bufferlist/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "bufferlist", - "version": "0.1.0", - "description": "Create linked lists of Buffer objects", - "directories": { - "lib": "." - }, - "main": "./bufferlist", - "repository": { - "type": "git", - "url": "http://github.com/substack/node-bufferlist.git" - }, - "devDependencies": { - "expresso": ">= 0.7.2" - }, - "scripts": { - "test": "expresso" - }, - "engine": [ - "node >=0.1.97" - ], - "readme": "BufferList\n==========\nBufferList provides an interface to treat a linked list of buffers as a single\nstream. This is useful for events that produce a many small Buffers, such as\nnetwork streams.\n\nInstallation\n============\nInstall using npm:\n npm install bufferlist\n\nOr, check out the repository and have npm link to your development copy. This\nis useful for developing the library, and is necessary when running the tests,\nsince they refer to the installed names of the library files.\n git clone http://github.com/substack/node-bufferlist.git \n cd node-bufferlist\n npm link .\n\nSimple Bufferlist Example\n=========================\n \n #!/usr/bin/env node\n var sys = require('sys');\n var Buffer = require('buffer').Buffer;\n var BufferList = require('bufferlist').BufferList;\n\n var b = new BufferList;\n ['abcde','xyz','11358'].forEach(function (s) {\n var buf = new Buffer(s.length);\n buf.write(s);\n b.push(buf);\n });\n\n sys.puts(b.take(10)); // abcdexyz11\n\nBinary\n======\nThis distribution also contains a Binary module for parsing these bufferlists.\n\nSimple Binary Example\n=====================\n\n #!/usr/bin/env node\n\n var sys = require('sys');\n var Buffer = require('buffer').Buffer;\n var BufferList = require('bufferlist').BufferList;\n var Binary = require('bufferlist/binary').Binary;\n\n var bufferList = new BufferList;\n var binary = Binary(bufferList)\n .getWord16be('xLen')\n .getBuffer('xs', 'xLen')\n .tap(function (vars) {\n vars.moo = 'xs:' + vars.xLen + ':' + vars.xs;\n })\n .end()\n ;\n\n var buf = new Buffer(6);\n buf.write('\\x00\\x04meow', 'binary');\n bufferList.push(buf);\n\n sys.puts(binary.vars.moo); // xs:4:meow\n\nSee Also\n========\nSee the examples/ directory for more involved examples.\n\nSee http://github.com/substack/node-rfb for a practical application of this\ndistribution.\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/node-bufferlist/issues" - }, - "homepage": "https://github.com/substack/node-bufferlist", - "_id": "bufferlist@0.1.0", - "dist": { - "shasum": "c4ab48435f9f9df13939ed9172499ccff73b0864" - }, - "_from": "bufferlist@>= 0.0.6", - "_resolved": "https://registry.npmjs.org/bufferlist/-/bufferlist-0.1.0.tgz" -} diff --git a/node_modules/bufferlist/test/advance.js b/node_modules/bufferlist/test/advance.js deleted file mode 100644 index d66a891..0000000 --- a/node_modules/bufferlist/test/advance.js +++ /dev/null @@ -1,25 +0,0 @@ -// Test advancing the buffer - -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); -var assert = require('assert'); - -exports.advance = function () { - var b = new BufferList({ encoding: 'binary' }); - var buf1 = new Buffer(5); buf1.write('abcde'); - var buf2 = new Buffer(3); buf2.write('xyz'); - var buf3 = new Buffer(5); buf3.write('11358'); - - b.write(buf1); - assert.eql(b.take(b.length), 'abcde', 'wrote correctly'); - b.advance(3); - assert.eql(b.take(b.length), 'de', 'advanced with one buffer'); - b.advance(3); - assert.eql(b.take(b.length), '', 'advanced one buffer past the end'); - b.write(buf2); - assert.eql(b.take(b.length), 'yz', 'offset preserved past the end'); - b.write(buf3); - assert.eql(b.take(b.length), 'yz11358', 'second write after advance'); - b.advance(4); - assert.eql(b.take(b.length), '358', 'advance after two writes'); -}; diff --git a/node_modules/bufferlist/test/binary.js b/node_modules/bufferlist/test/binary.js deleted file mode 100644 index 548a3ff..0000000 --- a/node_modules/bufferlist/test/binary.js +++ /dev/null @@ -1,86 +0,0 @@ -// Test the binary interface to bufferlists -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist').BufferList; // old style -var Binary = require('bufferlist/binary').Binary; // old style -var sys = require('sys'); -var assert = require('assert'); - -exports.binary = function () { - function runTest(bufs, check) { - var bList = new BufferList; - - var binary = Binary(bList) - .getWord16be('xLen') - .when('xLen', 0, function (vars) { - assert.eql(vars.xLen, 0, 'when check for 0 failed'); - this - .getWord32le('msgLen') - .getBuffer('msg', function (vars) { - return vars.msgLen - }) - .tap(function (vars) { - vars.moo = 42; - }) - .exit() - ; - }) - .getBuffer('xs', 'xLen') - .tap(function (vars) { - vars.moo = 100; - }) - .end() - ; - - var iv = setInterval(function () { - var buf = bufs.shift(); - if (!buf) { - clearInterval(iv); - check(binary.vars); - } - else { - bList.push(buf); - } - }, 50); - } - - runTest( - ['\x00','\x04m','eow'].map(function (s) { - var b = new Buffer(Buffer.byteLength(s,'binary')); - b.write(s,'binary'); - return b; - }), - function (vars) { - assert.eql( - vars.xLen, - 4, - 'xLen == 4 failed (xLen == ' + sys.inspect(vars.xLen) + ')' - ); - - var xs = vars.xs.toString(); - assert.eql( - xs, 'meow', 'xs != "meow", xs = ' + sys.inspect(xs) - ); - assert.eql( - vars.moo, 100, 'moo != 100, moo == ' + sys.inspect(vars.moo) - ); - } - ); - - runTest( - ['\x00\x00','\x12\x00\x00\x00hap','py pur','ring c','ats'] - .map(function (s) { - var b = new Buffer(Buffer.byteLength(s,'binary')); - b.write(s,'binary'); - return b; - }), - function (vars) { - assert.eql(vars.xLen, 0, 'xLen == 0 in "\\x00\\x12happy purring cats"'); - assert.eql( - vars.msgLen, 18, - 'msgLen != 18, msgLen = ' + sys.inspect(vars.msgLen) - ); - assert.eql(vars.moo, 42, 'moo != 42'); - } - ); -}; - diff --git a/node_modules/bufferlist/test/binary_assign.js b/node_modules/bufferlist/test/binary_assign.js deleted file mode 100644 index b280b1a..0000000 --- a/node_modules/bufferlist/test/binary_assign.js +++ /dev/null @@ -1,73 +0,0 @@ -// Test .into and hierarchical addressing assignment -var sys = require('sys'); -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); -var Binary = require('bufferlist/binary'); -var assert = require('assert'); - -exports['binary assign'] = function () { - var tapped = 0; - var bList = new BufferList; - - Binary(bList) - .getWord16be('foo','bar','baz') - .tap(function (vars) { - assert.eql( - vars.foo.bar.baz, 24930, - 'vars.foo.bar.baz != 24930, ' - + 'vars.foo.bar.baz == ' + sys.inspect(vars.foo.bar.baz) - ); - tapped ++; - }) - .getWord32le(['one','two','three']) - .tap(function (vars) { - assert.eql( - vars.one.two.three, 1717920867, - 'vars.one.two.three != 1717920867, ' - + 'vars.one.two.three == ' + sys.inspect(vars.one.two.three) - ); - tapped ++; - }) - .into(['what.the','fuck'],function () { - this - .getWord8('w') - .getWord8('t') - .getWord8('f') - .getWord32le('?!') - .tap(function (vars) { - vars.meow = 9000; - }) - ; - }) - .tap(function (vars) { - assert.eql( - vars.what.the.fuck.w, 119, - '.w != 119, .w == ' + vars.what.the.fuck.w - ); - assert.eql( - vars.what.the.fuck.t, 116, - '.t != 119, .t == ' + vars.what.the.fuck.t - ); - assert.eql( - vars.what.the.fuck.f, 102, - '.f != 119, .f == ' + vars.what.the.fuck.f - ); - assert.eql( - vars.what.the.fuck['?!'], 825303359, - '.?! != 825303359, .?! == ' + vars.what.the.fuck['?!'] - ); - assert.eql( - vars.what.the.fuck['meow'], 9000, - '.meow != 9000, .meow == ' + vars.what.the.fuck.meow - ); - tapped ++; - }) - .end() - ; - - var buf = new Buffer(13); - buf.write('abcdefwtf?!11'); - bList.push(buf); - assert.eql(tapped, 3, 'tapped != 3, tapped == ' + tapped); -}; - diff --git a/node_modules/bufferlist/test/binary_endianness.js b/node_modules/bufferlist/test/binary_endianness.js deleted file mode 100644 index fc5067b..0000000 --- a/node_modules/bufferlist/test/binary_endianness.js +++ /dev/null @@ -1,243 +0,0 @@ -#!/usr/bin/env node -// Test binary byte and endianness functions -var sys = require('sys'); -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); -var Binary = require('bufferlist/binary'); -var assert = require('assert'); - -exports.endianness = function () { - var bList = new BufferList; - - Binary(bList) - .getWord8('w8') - .tap(function (vars) { - assert.eql(vars.w8, 239, 'w8 is not 239') - }) - // 16 bit functions - .getWord16le('w16le') - .tap(function (vars) { - assert.eql(vars.w16le, 23569, 'w16le is not 23569'); - }) - .getWord16be('w16be') - .tap(function (vars) { - assert.eql(vars.w16be, 23569, 'w16be is not 23569'); - }) - .getWord16les('w16les') - .tap(function (vars) { - assert.eql(vars.w16les, -239, 'w16les is not -239'); - }) - .getWord16bes('w16bes') - .tap(function (vars) { - assert.eql(vars.w16bes, -239, 'w16bes is not -239'); - }) - .getWord16les('w16lesu') - .tap(function (vars) { - assert.eql(vars.w16lesu, 23569, 'w16lesu is not -239'); - }) - .getWord16bes('w16besu') - .tap(function (vars) { - assert.eql(vars.w16besu, 23569, 'w16besu is not -239'); - }) - // 32 bit functions - .getWord32le('w32le') - .tap(function (vars) { - assert.eql(vars.w32le, 287454020, 'w32le is not 287454020'); - }) - .getWord32be('w32be') - .tap(function (vars) { - assert.eql(vars.w32be, 287454020, 'w32be is not 287454020'); - }) - .getWord32les('w32les') - .tap(function (vars) { - assert.eql(vars.w32les, -16742383, 'w32les is not -16742383'); - }) - .getWord32bes('w32bes') - .tap(function (vars) { - assert.eql(vars.w32bes, -16742383, 'w32bes is not -16742383'); - }) - .getWord32les('w32lesu') - .tap(function (vars) { - assert.eql(vars.w32lesu, 2076074948, 'w32lesu is not 2076074948'); - }) - .getWord32bes('w32besu') - .tap(function (vars) { - assert.eql(vars.w32besu, 2076074948, 'w32besu is not 2076074948'); - }) - // 64 bit functions - .getWord64le('w64le') - .tap(function (vars) { - assert.eql(vars.w64le, 9833440827789222417, 'w64le is not 9833440826932474692'); - }) - .getWord64be('w64be') - .tap(function (vars) { - assert.eql(vars.w64be, 9833440827789222417, 'w64be is not 9833440826932474692'); - }) - .getWord64les('w64les') - .tap(function (vars) { - assert.eql(vars.w64les, -8613303245920330000, 'w64les is not -8613303245920330000'); - }) - .getWord64bes('w64bes') - .tap(function (vars) { - assert.eql(vars.w64bes, -8613303245920330000, 'w64bes is not -8613303245920330000'); - }) - .getWord64les('w64lesu') - .tap(function (vars) { - assert.eql(vars.w64lesu, 5337084636995872375, 'w64lesu is not 5337084636995872375'); - }) - .getWord64bes('w64besu') - .tap(function (vars) { - assert.eql(vars.w64besu, 5337084636995872375, 'w64besu is not 5337084636995872375'); - }) - .end() - ; - - var b8 = new Buffer(1); - b8[0] = 239; - bList.push(b8); - - // 16 bit functions - - var b16le = new Buffer(2); - b16le[0] = 0x11; - b16le[1] = 0x5C; - bList.push(b16le); - - var b16be = new Buffer(2); - b16be[0] = 0x5C; - b16be[1] = 0x11; - bList.push(b16be); - - var b16les = new Buffer(2); - b16les[0] = 0x11; - b16les[1] = 0xFF; - bList.push(b16les); - - var b16bes = new Buffer(2); - b16bes[0] = 0xFF; - b16bes[1] = 0x11; - bList.push(b16bes); - - var b16lesu = new Buffer(2); - b16lesu[0] = 0x11; - b16lesu[1] = 0x5C; - bList.push(b16lesu); - - var b16besu = new Buffer(2); - b16besu[0] = 0x5C; - b16besu[1] = 0x11; - bList.push(b16besu); - - // 32 bit functions - - var b32le = new Buffer(4); - b32le[0] = 0x44; - b32le[1] = 0x33; - b32le[2] = 0x22; - b32le[3] = 0x11; - bList.push(b32le); - - var b32be = new Buffer(4); - b32be[0] = 0x11; - b32be[1] = 0x22; - b32be[2] = 0x33; - b32be[3] = 0x44; - bList.push(b32be); - - var b32les = new Buffer(4); - b32les[0] = 0x11; - b32les[1] = 0x88; - b32les[2] = 0x00; - b32les[3] = 0xFF; - bList.push(b32les); - - var b32bes = new Buffer(4); - b32bes[0] = 0xFF; - b32bes[1] = 0x00; - b32bes[2] = 0x88; - b32bes[3] = 0x11; - bList.push(b32bes); - - var b32lesu = new Buffer(4); - b32lesu[0] = 0xC4; - b32lesu[1] = 0x63; - b32lesu[2] = 0xBE; - b32lesu[3] = 0x7B; - bList.push(b32lesu); - - var b32besu = new Buffer(4); - b32besu[0] = 0x7B; - b32besu[1] = 0xBE; - b32besu[2] = 0x63; - b32besu[3] = 0xC4; - bList.push(b32besu); - - // 64 bit functions - - var b64le = new Buffer(8); - b64le[0] = 0x11; - b64le[1] = 0x22; - b64le[2] = 0x33; - b64le[3] = 0x44; - b64le[4] = 0x55; - b64le[5] = 0x66; - b64le[6] = 0x77; - b64le[7] = 0x88; - bList.push(b64le); - - var b64be = new Buffer(8); - b64be[0] = 0x88; - b64be[1] = 0x77; - b64be[2] = 0x66; - b64be[3] = 0x55; - b64be[4] = 0x44; - b64be[5] = 0x33; - b64be[6] = 0x22; - b64be[7] = 0x11; - bList.push(b64be); - - var b64les = new Buffer(8); - b64les[0] = 0x11; - b64les[1] = 0x22; - b64les[2] = 0x33; - b64les[3] = 0x44; - b64les[4] = 0x55; - b64les[5] = 0x66; - b64les[6] = 0x77; - b64les[7] = 0x88; - bList.push(b64les); - - var b64bes = new Buffer(8); - b64bes[0] = 0x88; - b64bes[1] = 0x77; - b64bes[2] = 0x66; - b64bes[3] = 0x55; - b64bes[4] = 0x44; - b64bes[5] = 0x33; - b64bes[6] = 0x22; - b64bes[7] = 0x11; - bList.push(b64bes); - - var b64lesu = new Buffer(8); - b64lesu[0] = 0x77; - b64lesu[1] = 0x66; - b64lesu[2] = 0x55; - b64lesu[3] = 0x44; - b64lesu[4] = 0x33; - b64lesu[5] = 0x22; - b64lesu[6] = 0x11; - b64lesu[7] = 0x4A; - bList.push(b64lesu); - - var b64besu = new Buffer(8); - b64besu[0] = 0x4A; - b64besu[1] = 0x11; - b64besu[2] = 0x22; - b64besu[3] = 0x33; - b64besu[4] = 0x44; - b64besu[5] = 0x55; - b64besu[6] = 0x66; - b64besu[7] = 0x77; - bList.push(b64besu); -}; - diff --git a/node_modules/bufferlist/test/binary_event.js b/node_modules/bufferlist/test/binary_event.js deleted file mode 100644 index f8b124d..0000000 --- a/node_modules/bufferlist/test/binary_event.js +++ /dev/null @@ -1,67 +0,0 @@ -var sys = require('sys'); -var net = require('net'); -var BufferList = require('bufferlist'); -var Binary = require('bufferlist/binary'); -var assert = require('assert'); - -function parser (sock) { - var bufferList = new BufferList; - sys.pump(sock, bufferList); - - return Binary(bufferList) - .getWord16be('xLen') - .when('xLen', 0, function (vars) { - this - .getWord32le('msgLen') - .getBuffer('msg', 'msgLen') - .tap(function (vars) { - vars.moo = 'msg:' + vars.msgLen + ':' + vars.msg; - }) - .exit() - ; - }) - .getBuffer('xs', 'xLen') - .tap(function (vars) { - vars.moo = 'xs:' + vars.xLen + ':' + vars.xs; - }) - .end() - ; -} - -exports['binary event'] = function () { - function serverSession (port, strings, moo) { - // fire up a server to write the strings when a client connects - var server = net.createServer(function (stream) { - strings.forEach(function (s) { - stream.write(s); - }); - stream.end(); - server.close(); - }); - server.listen(port); - - // connect to the server and parse its output - var client = new net.Stream; - parser(client).on('end', function (vars) { - assert.eql( - moo, vars.moo, - 'moo != ' + sys.inspect(moo) + ', moo == ' + sys.inspect(vars.moo) - ); - client.end(); - }); - setTimeout(function () { - client.connect(port); - }, 50); - } - - serverSession(20801, - ['\x00','\x04m','eow'], - 'xs:4:meow' - ); - - serverSession(20802, - ['\x00\x00','\x12\x00\x00\x00happy pur','ring c','ats'], - 'msg:18:happy purring cats' - ); -}; - diff --git a/node_modules/bufferlist/test/binary_into.js b/node_modules/bufferlist/test/binary_into.js deleted file mode 100644 index 7ae9776..0000000 --- a/node_modules/bufferlist/test/binary_into.js +++ /dev/null @@ -1,49 +0,0 @@ -// Check .into(), especially for object pollution -var sys = require('sys'); -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); -var Binary = require('bufferlist/binary'); -var assert = require('assert'); - -exports.into = function () { - var bList = new BufferList; - var tapped = false; - - Binary(bList) - .getWord8('ones') - .into('frac', function () { - this - .getWord64be('64') - .getWord32be('32') - .getWord16be('16') - .getWord8('8') - }) - .tap(function (vars) { - tapped = true; - - assert.eql(vars.ones, 3); - assert.eql(vars.frac['64'], 73184615082362370); - assert.eql(vars.frac['32'], 50661385); - assert.eql(vars.frac['16'], 1801); - assert.eql(vars.frac['8'], 3); - - assert.eql( - Object.keys(vars).sort().join(' '), 'frac ones', - 'object pollution with .into()' - ) - }) - .end() - ; - - var buf = new Buffer(16); - var i = 0; - String(4 * Math.atan2(1,1)).split('').forEach(function (digit) { - if (digit != '.') { - buf[i++] = parseInt(digit,10); - } - }); - bList.push(buf); - - assert.ok(tapped, 'not tapped'); -}; - diff --git a/node_modules/bufferlist/test/binary_jump.js b/node_modules/bufferlist/test/binary_jump.js deleted file mode 100644 index 4f66a57..0000000 --- a/node_modules/bufferlist/test/binary_jump.js +++ /dev/null @@ -1,55 +0,0 @@ -// Jumping around in a binary parser -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); -var Binary = require('bufferlist/binary'); -var assert = require('assert'); - -Number.prototype.upTo = function (n) { - var acc = []; - for (var i = Number(this); i <= n; i++) { - acc.push(i); - } - return acc; -}; - -Number.prototype.downTo = function (n) { - var acc = []; - for (var i = Number(this); i >= n; i--) { - acc.push(i); - } - return acc; -}; - -Array.prototype.zip = function (xs) { - var arr = this; - return (0).upTo(this.length - 1).map(function (i) { - return [ arr[i], xs[i] ]; - }); -}; - -exports.jump = function () { - var tapped = 0; - - var bList = new BufferList; - - Binary(bList) - .skip(3) - .getWord16be('de') - .tap(function (vars) { - var de = 256 * 'd'.charCodeAt(0) + 'e'.charCodeAt(0); - assert.eql( - vars.de, de, - 'getWord16be at 3 should be ' + de + ', not ' + vars.de - ); - tapped ++; - }) - .end() - ; - - var buf1 = new Buffer(5); buf1.write('abcde'); - var buf2 = new Buffer(3); buf2.write('xyz'); - var buf3 = new Buffer(5); buf3.write('11358'); - bList.push(buf1,buf2,buf3); - assert.eql(tapped, 1, 'not tapped'); -}; - diff --git a/node_modules/bufferlist/test/binary_loop.js b/node_modules/bufferlist/test/binary_loop.js deleted file mode 100644 index 45e1d62..0000000 --- a/node_modules/bufferlist/test/binary_loop.js +++ /dev/null @@ -1,115 +0,0 @@ -// Test binary looping functions -var sys = require('sys'); - -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); -var Binary = require('bufferlist/binary'); -var assert = require('assert'); - -exports['binary loop'] = function () { - // test repeat - var reps = 0; - var trickyList = []; - - Binary(new BufferList) - .repeat(5000, function(vars, n) { - reps++; - }) - .tap(function (vars) { - assert.eql( - reps, 5000, 'reps != 5000, reps == ' + reps + ' in repeat test' - ); - }) - .repeat(3, function (vars, i) { - this - .repeat(4, function (vars, j) { - trickyList.push([ i + 1, j + 1 ]); - }) - ; - }) - .tap(function (vars) { - expectedTrickyList = [ - [1,1],[1,2],[1,3],[1,4], - [2,1],[2,2],[2,3],[2,4], - [3,1],[3,2],[3,3],[3,4] - ]; - for (var i = 0; i < trickyList.length; i++) { - assert.eql( - trickyList[i][0], - expectedTrickyList[i][0], - 'trickly list is not what it should be. it should be: ' + - sys.inspect(expectedTrickyList) + '. it is: ' + - sys.inspect(trickyList) - ); - assert.eql( - trickyList[i][1], - expectedTrickyList[i][1], - 'trickly list is not what it should be. it should be: ' + - sys.inspect(expectedTrickyList) + '. it is: ' + - sys.inspect(trickyList) - ); - } - }) - .end() - ; - - assert.eql(reps, 5000, 'reps != 5000, reps == ' + reps + ' in outer repeat check'); - - var bufferList = new BufferList; - var loops = 0; - Binary(bufferList) - .forever(function () { - this - .getWord16be('moo','count') - .tap(function (vars) { - assert.eql( - vars.moo.count, 100, - 'count != 100, count == ' + vars.moo.count - ); - vars.reps = 0; - }) - .repeat('moo.count', function (vars, i) { - this - .getWord16be('size') - .tap(function (vars) { - assert.eql( - vars.size, 1000, - 'size != 1000, size == ' + vars.size - ); - }) - .getBuffer('block', 'size') - ; - vars.reps ++; - }) - .tap(function (vars) { - assert.eql( - vars.reps, 100, 'reps != 100, reps == ' + vars.reps - ); - }) - ; - loops ++; - if (loops == 20) this.exit(); - }) - .end() - ; - - for (var n = 0; n < 20; n++) { - var countBuf = new Buffer(2); - countBuf[0] = 100 >> 8; - countBuf[1] = 100 % 256; - bufferList.push(countBuf); - - for (var i = 0; i < 100; i++) { - var buf = new Buffer(1000 + 2); - buf[0] = 1000 >> 8; - buf[1] = 1000 % 256; - for (var j = 0; j < 1000; j++) { - buf[j + 2] = j; - } - bufferList.push(buf); - } - } - - assert.eql(loops, 20, 'loops != 20, loops == ' + loops); -}; - diff --git a/node_modules/bufferlist/test/client_server.js b/node_modules/bufferlist/test/client_server.js deleted file mode 100644 index e1e85e9..0000000 --- a/node_modules/bufferlist/test/client_server.js +++ /dev/null @@ -1,48 +0,0 @@ -// Test a client/server interaction -// If nothing gets printed, everything is fine. - -var sys = require('util'); -var net = require('net'); -var client = new net.Stream; -var assert = require('assert'); - -exports['client/server'] = function () { - var BufferList = require('bufferlist'); - var bufs = new BufferList({ encoding: 'binary' }); - var elems = []; - - client.addListener('data', function (data) { - bufs.push(data); - elems.push(data); - - assert.eql(bufs.take(3).toString(), elems[0].toString(), 'take first 3 bytes ('+sys.inspect(elems[0])+') vs ('+sys.inspect(bufs.take(3).toString())+')'); - assert.eql(bufs.take(100), elems.join(''), 'take past length of buffer'); - }); - - client.addListener('end', function (data) { - assert.eql(bufs.length, elems.join('').length, 'verify length'); - assert.eql(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); - - setTimeout(function () { - client.connect(port); - }, 50); -}; - diff --git a/node_modules/bufferlist/test/event.js b/node_modules/bufferlist/test/event.js deleted file mode 100644 index 335cb64..0000000 --- a/node_modules/bufferlist/test/event.js +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env node -// Test joining lots of chunks into one buffer - -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); -var assert = require('assert'); - -exports.events = function () { - var b = new BufferList({ encoding: 'binary' }); - var times = 0; - - var wrote = null; - b.addListener('write', function (buf) { - assert.eql( - wrote.toString(), - buf.toString(), - 'write callback gives its arguments' - ); - times ++; - }); - - var buf1 = new Buffer(5); buf1.write('abcde'); - var buf2 = new Buffer(3); buf2.write('xyz'); - var buf3 = new Buffer(5); buf3.write('11358'); - - var wrote = buf1; b.write(buf1); - var wrote = buf2; b.write(buf2); - - assert.eql(times, 2, 'wrote twice'); - - var wrote = buf3; b.write(buf3); - - assert.eql(times, 3, 'wrote thrice'); - - assert.eql(b.take(), 'abcdexyz11358', 'entire buffer check'); - - var advanced = 0; - b.on('advance', function (n) { - assert.eql(n, 3, 'n = 3 in advance callback') - advanced ++; - }); - b.advance(3); - assert.eql(b.take(3), 'dex', 'advanced 3'); - assert.eql(advanced, 1, 'advance callback triggered once'); -}; - diff --git a/node_modules/bufferlist/test/join.js b/node_modules/bufferlist/test/join.js deleted file mode 100644 index 9678539..0000000 --- a/node_modules/bufferlist/test/join.js +++ /dev/null @@ -1,26 +0,0 @@ -// Test joining lots of chunks into one buffer -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); -var assert = require('assert'); - -exports.join = function () { - var buf1 = new Buffer(5); buf1.write('abcde'); - var buf2 = new Buffer(3); buf2.write('xyz'); - var buf3 = new Buffer(5); buf3.write('11358'); - - var b = new BufferList; - b.push(buf1,buf2,buf3); - - assert.eql( - b.join().toString('ascii',0,b.length), - 'abcdexyz11358', - 'join multiple chunks into one Buffer' - ); - - assert.eql( - b.join(3,6).toString(), - 'dex', - 'slice of a buffer join' - ); -}; - diff --git a/node_modules/bufferlist/test/take.js b/node_modules/bufferlist/test/take.js deleted file mode 100644 index a637f64..0000000 --- a/node_modules/bufferlist/test/take.js +++ /dev/null @@ -1,39 +0,0 @@ -// Test BufferList#take(). -var Buffer = require('buffer').Buffer; -var BufferList = require('bufferlist'); -var assert = require('assert'); - -exports.join = function () { - var buf1 = new Buffer(5); buf1.write('abcde'); - var buf2 = new Buffer(3); buf2.write('xyz'); - var buf3 = new Buffer(5); buf3.write('11358'); - - var b = new BufferList; - b.push(buf1,buf2,buf3); - - assert.eql( - b.take('binary'), - 'abcdexyz11358', - 'take entire BufferList at once' - ); - - assert.eql( - b.take(1, 'ascii'), - 'a', - 'take 1 byte with "ascii" encoding' - ); - - assert.ok( - Buffer.isBuffer(b.take(1)), - 'take without encoding returns Buffer' - ); - - - // Now set the encoding - b.encoding = 'ascii'; - assert.ok( - !Buffer.isBuffer(b.take(1)), - 'take with encoding returns String' - ); -}; - diff --git a/node_modules/put/LICENSE b/node_modules/put/LICENSE deleted file mode 100644 index 432d1ae..0000000 --- a/node_modules/put/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -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. diff --git a/node_modules/put/README.md b/node_modules/put/README.md deleted file mode 100644 index c91e9bd..0000000 --- a/node_modules/put/README.md +++ /dev/null @@ -1,57 +0,0 @@ -Put -=== - -Pack multibyte binary values into buffers with specific endiannesses. - -Installation -============ - -To install with [npm](http://github.com/isaacs/npm): - - npm install put - -To run the tests with [expresso](http://github.com/visionmedia/expresso): - - expresso - -Examples -======== - -buf.js ------- - -Build a buffer - - #!/usr/bin/env node - - var Put = require('put'); - var buf = Put() - .word16be(1337) - .word8(1) - .pad(5) - .put(new Buffer('pow', 'ascii')) - .word32le(9000) - .buffer() - ; - console.log(buf); - -Output: - - -stream.js ---------- - -Send a buffer to a writeable stream - - #!/usr/bin/env node - - var Put = require('put'); - Put() - .word16be(24930) - .word32le(1717920867) - .word8(103) - .write(process.stdout) - ; - -Output: - abcdefg diff --git a/node_modules/put/examples/buf.js b/node_modules/put/examples/buf.js deleted file mode 100644 index a5446d0..0000000 --- a/node_modules/put/examples/buf.js +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env node - -var Put = require('put'); -var buf = Put() - .word16be(1337) - .word8(1) - .pad(5) - .put(new Buffer('pow', 'ascii')) - .word32le(9000) - .buffer() -; -console.log(buf); diff --git a/node_modules/put/examples/stream.js b/node_modules/put/examples/stream.js deleted file mode 100644 index ac65119..0000000 --- a/node_modules/put/examples/stream.js +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env node - -var Put = require('put'); -Put() - .word16be(24930) - .word32le(1717920867) - .word8(103) - .write(process.stdout) -; diff --git a/node_modules/put/index.js b/node_modules/put/index.js deleted file mode 100644 index 47cb0a7..0000000 --- a/node_modules/put/index.js +++ /dev/null @@ -1,100 +0,0 @@ -module.exports = Put; -function Put () { - if (!(this instanceof Put)) return new Put; - - var words = []; - var len = 0; - - this.put = function (buf) { - words.push({ buffer : buf }); - len += buf.length; - return this; - }; - - this.word8 = function (x) { - words.push({ bytes : 1, value : x }); - len += 1; - return this; - }; - - this.floatle = function (x) { - words.push({ bytes : 'float', endian : 'little', value : x }); - len += 4; - return this; - }; - - [ 8, 16, 24, 32, 64 ].forEach((function (bits) { - this['word' + bits + 'be'] = function (x) { - words.push({ endian : 'big', bytes : bits / 8, value : x }); - len += bits / 8; - return this; - }; - - this['word' + bits + 'le'] = function (x) { - words.push({ endian : 'little', bytes : bits / 8, value : x }); - len += bits / 8; - return this; - }; - }).bind(this)); - - this.pad = function (bytes) { - words.push({ endian : 'big', bytes : bytes, value : 0 }); - len += bytes; - return this; - }; - - this.length = function () { - return len; - }; - - this.buffer = function () { - var buf = new Buffer(len); - var offset = 0; - words.forEach(function (word) { - if (word.buffer) { - word.buffer.copy(buf, offset, 0); - offset += word.buffer.length; - } - else if (word.bytes == 'float') { - // s * f * 2^e - var v = Math.abs(word.value); - var s = (word.value >= 0) * 1; - var e = Math.ceil(Math.log(v) / Math.LN2); - var f = v / (1 << e); - console.dir([s,e,f]); - - console.log(word.value); - - // s:1, e:7, f:23 - // [seeeeeee][efffffff][ffffffff][ffffffff] - buf[offset++] = (s << 7) & ~~(e / 2); - buf[offset++] = ((e & 1) << 7) & ~~(f / (1 << 16)); - buf[offset++] = 0; - buf[offset++] = 0; - offset += 4; - } - else { - var big = word.endian === 'big'; - var ix = big ? [ (word.bytes - 1) * 8, -8 ] : [ 0, 8 ]; - - for ( - var i = ix[0]; - big ? i >= 0 : i < word.bytes * 8; - i += ix[1] - ) { - if (i >= 32) { - buf[offset++] = Math.floor(word.value / Math.pow(2, i)) & 0xff; - } - else { - buf[offset++] = (word.value >> i) & 0xff; - } - } - } - }); - return buf; - }; - - this.write = function (stream) { - stream.write(this.buffer()); - }; -} diff --git a/node_modules/put/package.json b/node_modules/put/package.json deleted file mode 100644 index f349faf..0000000 --- a/node_modules/put/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "put", - "version": "0.0.6", - "description": "Pack multibyte binary values into buffers", - "main": "./index.js", - "keywords": [ - "put", - "pack", - "binary" - ], - "repository": { - "type": "git", - "url": "http://github.com/substack/node-put.git" - }, - "scripts": { - "test": "expresso" - }, - "engines": { - "node": ">=0.3.0" - }, - "license": { - "type": "MIT/X11" - }, - "readme": "Put\n===\n\nPack multibyte binary values into buffers with specific endiannesses.\n\nInstallation\n============\n\nTo install with [npm](http://github.com/isaacs/npm):\n \n npm install put\n\nTo run the tests with [expresso](http://github.com/visionmedia/expresso):\n\n expresso\n\nExamples\n========\n\nbuf.js\n------\n\nBuild a buffer\n\n #!/usr/bin/env node\n\n var Put = require('put');\n var buf = Put()\n .word16be(1337)\n .word8(1)\n .pad(5)\n .put(new Buffer('pow', 'ascii'))\n .word32le(9000)\n .buffer()\n ;\n console.log(buf);\n\nOutput:\n \n\nstream.js\n---------\n\nSend a buffer to a writeable stream\n\n #!/usr/bin/env node\n\n var Put = require('put');\n Put()\n .word16be(24930)\n .word32le(1717920867)\n .word8(103)\n .write(process.stdout)\n ;\n\nOutput:\n abcdefg\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/substack/node-put/issues" - }, - "homepage": "https://github.com/substack/node-put", - "_id": "put@0.0.6", - "dist": { - "shasum": "f56db18c769a9f4c68c2c7020b41c601e1a5cad6" - }, - "_from": "put@*", - "_resolved": "https://registry.npmjs.org/put/-/put-0.0.6.tgz" -} diff --git a/node_modules/put/test/buf.js b/node_modules/put/test/buf.js deleted file mode 100644 index 299dc13..0000000 --- a/node_modules/put/test/buf.js +++ /dev/null @@ -1,70 +0,0 @@ -var assert = require('assert'); -var Put = require('put'); -var Binary = require('binary'); - -exports.chain = function () { - var buf = Put() - .word16be(1337) - .word8(1) - .pad(5) - .put(new Buffer('pow', 'ascii')) - .word32le(9000) - .word64le(3) - .word64be(4) - .buffer() - ; - assert.equal(buf.length, 2 + 1 + 5 + 3 + 4 + 8 + 8); - var bs = [].slice.call(buf); - - // word16be(1337) - assert.eql(bs.slice(0,2), [ 0x05, 0x39 ]); - - // word8(1) - assert.eql(bs.slice(2,3), [ 0x01 ]); - - // pad(5) - assert.eql(bs.slice(3,8), [ 0x00, 0x00, 0x00, 0x00, 0x00 ]); - - // put(new Buffer('pow', 'ascii')) - assert.eql(bs.slice(8,11), [ 0x70, 0x6f, 0x77 ]); - - // word32le(9000) - assert.eql(bs.slice(11,15), [ 0x28, 0x23, 0x00, 0x00 ]); - - // word64le(3) - assert.eql( - bs.slice(15,23), - [ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ] - ); - - // word64be(4) - assert.eql( - bs.slice(23,31), - [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04 ] - ); -}; - -exports.parity = function () { - [ 'le', 'be' ].forEach(function (end) { - [ 8, 16, 32 ].forEach(function (n) { - var max = Math.pow(2,n); - var step = Math.max(1, Math.floor(max / 1000)); - - for (var i = 0; i < max; i += step) { - var buf = Put()[ 'word' + n + end ](i).buffer(); - var j = Binary.parse(buf)[ 'word' + n + end ]('j').vars.j; - assert.eql(i, j); - } - }); - }); -}; - -exports.b64 = function () { - var buf = Put().word64be(1).buffer(); - assert.eql([].slice.call(buf), [ 0, 0, 0, 0, 0, 0, 0, 1 ]); -}; - -exports.l64 = function () { - var buf = Put().word64le(1).buffer(); - assert.eql([].slice.call(buf), [ 1, 0, 0, 0, 0, 0, 0, 0 ]); -}; diff --git a/node_modules/put/test/c/ftoi b/node_modules/put/test/c/ftoi deleted file mode 100644 index 4eb358b39094b40113c5f4da899768be2aab9e71..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4632 zcmb7HYiL}@6`oyP+naXl$g*N@62)xEDwV;$v5h3`(uZX2T2>-keke{|C!VhMp?l`j2ik#iXTCY#oHH}`%>@PnhHvO@gSWY6Uuxe`$l(bc(RpAUec0@t|0b zD(X6)0|#;iWy(5;1!;n`!bt0s6`*Vercg)Q6qV3cKmuq;VSCZ6^{Vbg=paGbg3vGZ zeq?PRw?Ri)0;W(;ACwO8JK&oV1*RC?(W_1p@Q!5KKbp&qJeo`H%w-Fe3ADt_J)7@U8Dz0ghu6Ct1qTe6b+Q zPQ2tuDKI4oPDQtn14F1yW(%@XP9?>7DO+&TBJLE^XhT}PO+KD2i2lKW{e5zeU3cfl zzw@gx`tap^Qka^v+0XIM_G>7X@n6?tP`8k8;NX6W9Ft-($HWDgqq9%UTs>Z0wrXs4 zYHBfpIGcUpmg~CHZ#(O1+fZA(#?K|#_}Zzr7TvBJu;{km#FuT{c6!LLcQQLf}p>I4u`ghr&H?S`pT{OK&ZnA?JgY>hiAH zSg^Wa&59W-QhOMEedno2+dEOnQ;{8W(a4V3<_lul3d{^gEK*i(yDplqNwC%E|H%`_ zYeR55wfN#D3}Csf_9Pn4T@1m)T$SJLZ@%vOr(Gwq`=i-d^Gq}nKu?fav#|gixj%W8 ztm+%SeYZ>RRWG%jIxU}GoNbH1cYXfOabKw3be+u?SxTR&Uboz(*(Ov~Zsp<<6zve{LdkOYwY4*a@dt zD#L-!#u6|DBk_DT0S84i#K%_Fbjy)4*ok63pDH+Jvi^tsL2&rr_}|r;2*7`95_L=u zLwMYhr_L@Y!YG@>y_sn@#PALx-VTBnQ5yX*yn}#@P1<9;=D^#5GUJqqJW3Su5n_rw z#`ApLZzJz8^o(ip80Qzj`v%JF3yR7XMF<712b0KUIt^h=lgD@-LxF3} z_+>ri83@+^%UlN&D1=e=`UMo zmGxZz3*hZS*(CCqegHAN74TNTJEAoDLmuVF5X0mBst1$wb5_(7=Zb3}urH@3*Kh zJRVBTu(!H-KxcTr_wac5gg(XZB6yr*`sMz_yWJAX{J%`JNBe(-7{9z9EZ@Z*xqtES zxZkdT*EoOV{nf(@;xrAS6L%ZO74TTk{_)gp{S@9+=-Izr5GL~W>Z1BmN8vtCTP6*H z_b&sGlf%TE|IDOiEWR*0{tzm5LO2G-3}e}AFNn&Zr=hV2+8v4e5i9krU++5_YXjV0 zG}a!tk7!KqdcV*ZlZ?cDL1PRGiR)iu{Ws0I)l{Epu4k?1DD=A3Sf9&WpBi)L(d$rS z9qC+e8gu0e^={F4qrzN28sDoh*NMiQIm{u}gU0+T_|J$Jjd==Vepj*Hu^Go&&(mAS ztH%12XIyH$g_%0Nb(Z+I%MqLY`EZNpo!#`$ zhZCg(*!0hb+XdeM+!#_!!LB8bSd*g=wdFBP{s6 zU^9O{MD>q=z5ag&e7-*4^#2O5NwmkyDc2|KeEzNCPsq*qgug}ntpWcB*xX-y{`vx+ zdH9pSra#T-&-a0w>;HR`KO|lN=1m_>#U}q|aTb`*1^x&2?>w+cwEu?&{5IRy?KNZm z-UDv);P)H!{{a3a?9*n8eT^jM!ql`P89TyZ3xljh>j* zm3)5E_=z2kDmMp?^&W~zgXqSTKk=e&ZOTj9DQ4N%{=uRBy@PV-z=7kjVL9Bpe=x>A z^9m^ArBZxSrV7cm73y6pWc1|W-a`X@g7-W9ZUs#}ViVNW3S`Pj4aSZXv| z# -#include - -int main (int argc, char **argv) { - float f = atof(argv[1]); - printf("%i\n", *(int *) &f); -} diff --git a/node_modules/put/test/c/itof b/node_modules/put/test/c/itof deleted file mode 100644 index 4ac24efdb64a6c3ce8cdf47357a2eb0c54c1f94b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4616 zcmb7HZEPIH8J;^|l7qU5^T$)g@lo?s1ii2rAV|H<<1S-(kx8t znrLf&9vtXA>eO}62($`Xhe7H_BT?!WU@C1Ko2mqT1@tBiRQ4A&+OFDOf(=^Dv7q!z zdl*GE$ki{y2Au<@(oP@LCh(i!o7w?PHMV2d+$7*_V){RncKRPmCwHZtY;o8s!5sh+M8Z$nEvq97ykLm58ilqZ2G7FojUyFCfbY-_9YGq z-`~WBc7s)1Vj@N^>#sld@eJ!hG5y#UgYIL+7tU{o0Vs)gSKxbr7hZ@&`5v1YWGM$T zxvVU>@w_XgKu8h{MT?N#y=YB3Sy?RDNimdnvhIM0yEzAaNb~z-;!aj{^>iO>mwPSW zT^Qdktllw%C*w(_)Hu%9`DME_6j$(F*W;xYP;NlE$Pz(WVu`@rWQoZ>arWAY(n6%n zZl^|P>yT&TFD`qYH}<}}uDlJc9%DRt>fKpy-&OSVwwLi_A8$K7q*%Q^k8a*} zdP>oDeNJI|OmUjmXB4LAR6X%U;60z7KKqZ-)y2pAj;D4beyLVGj-5;`Vf~bU1H#hz zRpQV0`EN#kfe949bs>s!I)X7rZwNf!{32Ys5jyZeVcWzX;6s#VLcb=(s~e+P(GPr( zFTcHx1B6O%MNU04JK;VkCjRsd@-cpCq5eV?+_4$A_7dArx#OKkBip>WcW2L&b9J$_ z5F78TF3m*7#o0(>`2o!JY)50m1oW@s(js2t!>1b~G~K-AdFZADeJlNa`{apoFWijI zzPuR|UT7!}qQk^=Jw}`;@wwxjH@)zf=Qi&7e7v&;UZU`fA~N0?g#+)U-;q^%J9OYy z{-e@c4W~}aXJ*G68sXEA*9GnarJJ6+Wtz2t^Q9XRZ*IH_O~oZ0gcYvIg(zlIK8LA1 zh40R_7D9e)AGnht5%A{)OV*JhDj%y+&ip76MM8?p{+dW*ANkKMFE@#jYp@=6uH{R> z9Pt?RYfvW2T~G>r&Likt%P}bT2h2&_4V^-N)+bSNJu>0AN3z6}bHixI6my)@BFZzs zsQ%x={n2z|2~i}7^n=C$QH zJ6~{e*;PQombcU7>&j5t6_%5A@O15AJO=<^$|d7&Tv&EW4&>t*TUZG}kVox+evX_XkNG_5`>o_1 zg`GJ~9`pPXc;7{xb3s*&#e6>rWv-LQby1HB*MkvqDW{>#Y4VuQXHelTbjM1@Ih#^bvZm!O8nbvNaYM;_O>;hjUBb7ec%{|tD$ zQ8z*!wccYMJhpRwJY^%8>{`5QuycO9p%n7=>#BOvM&&-wv5Y(d-oFe$Ne+c2znPIM zSbQ-|{C+g-g7O`hGtA}Sc*~m*$3RCj9%#1-_aipyTfW|RG}Z%ff6-Wb;69=;z3cr# zV+0SveL-V>QN8{()?d?{TUCApxt_J1Z=u(%#`;|5`qY>^k6wow>rCf*)0it)sQ(m= zH!95aqcMU4;X2Wnk<;rzV}2E#_ZssQh9ECkRQWqL^H^h^-a213)~7u4Qsb>G)OoKl zPkAAjXBzX$sPjqVdlWX0Dsk^h9w~PzL?~3V6!5 z)BkTt^o8T`GRpPIrcn59@fVcl{Y1D{{JjEy25jyxq3~Ve3t$t^n5Y;0Kj594nOF;d zTY8-YvMrfdMOlU$^$Y-s7^T`$Ql9_N44sg&u7Wn36d; zn9lXb(^6feWV|>ma7h|U+pe9o_8r*2SI{7xXri$5Tt^Q%5e$iFf#Qy-LH7$Su diff --git a/node_modules/put/test/c/itof.c b/node_modules/put/test/c/itof.c deleted file mode 100644 index 2a988da..0000000 --- a/node_modules/put/test/c/itof.c +++ /dev/null @@ -1,7 +0,0 @@ -#include -#include - -int main (int argc, char **argv) { - int i = atoi(argv[1]); - printf("%f\n", *(float *) &i); -} diff --git a/node_modules/put/test/float.js_ b/node_modules/put/test/float.js_ deleted file mode 100644 index 5250be2..0000000 --- a/node_modules/put/test/float.js_ +++ /dev/null @@ -1,9 +0,0 @@ -var assert = require('assert'); -var Put = require('put'); - -exports.buf = function () { - var ibuf = Put().word32le(1096149893).buffer(); - var fbuf = Put().floatle(13.37).buffer(); - - assert.eql(ibuf, fbuf); -}; diff --git a/node_modules/put/test/stream.js b/node_modules/put/test/stream.js deleted file mode 100644 index d338413..0000000 --- a/node_modules/put/test/stream.js +++ /dev/null @@ -1,28 +0,0 @@ -var assert = require('assert'); -var Put = require('put'); - -exports.stream = function () { - var written = 0; - var stream = { - write : function (buf) { - assert.equal(buf.toString(), 'abcdefg'); - written ++; - } - }; - - Put() - .word16be( - 256 * 'a'.charCodeAt(0) - + 'b'.charCodeAt(0) - ) - .word32le( - Math.pow(256, 0) * 'c'.charCodeAt(0) - + Math.pow(256, 1) * 'd'.charCodeAt(0) - + Math.pow(256, 2) * 'e'.charCodeAt(0) - + Math.pow(256, 3) * 'f'.charCodeAt(0) - ) - .word8('g'.charCodeAt(0)) - .write(stream) - ; - assert.equal(written, 1); -}; diff --git a/node_modules/stream-stack/.npmignore b/node_modules/stream-stack/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/stream-stack/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/stream-stack/API.md b/node_modules/stream-stack/API.md deleted file mode 100644 index e5f3768..0000000 --- a/node_modules/stream-stack/API.md +++ /dev/null @@ -1,63 +0,0 @@ -# API - -## var ss = require('stream-stack') - -The main module (`stream-stack`) contains the primary constructor function for StreamStacks. - -### var streamStack = new ss.StreamStack(stream, [events]) - -Creates a new `StreamStack` instance. "stream" must be an instance of `Stream` (i.e. `net.Socket`, -`fs.ReadStream`, `fs.WriteStream`, `http.{Clinet,Server}{Request,Response}`, etc..), which will be -the "parent" stream of the new instance. - -The optional "events" arg should be an Object with keys being the names of events that _WILL NOT_ -be re-emitted on the new instance, and values being Functions that will be called instead when the -event is emitted. This gives the opportunity for subclasses to intercept event in order to perform -some filter or transformation first. - -Usually, the `StreamStack` class is subclassed, rather than directly instantiated. A bare instance -of "StreamStack" will re-emit all events from it's parent Stream, and any `write()` calls on the -instance will be proxied up to the parent Stream. - - var parent = require('fs').createReadStream(__filename); - var streamStack = new ss.StreamStack(parent, { - data: function(chunk) { - // Re-emit every other byte from the parent to `this` - for (var i=0, l=chunk.length; i= 0.3.0" - }, - "directories": {}, - "dependencies": {}, - "readme": "node-stream-stack\n=================\n### Filter low-level `Stream` instances into stackable, protocol-based streams.\n\nThis module exposes the `StreamStack` interface, which starts off as a node\n`Stream` subclass that accepts a \"parent\" Stream to work with. `StreamStack` is\nmeant to be subclassed in order to implement the layers of a protocol, or run the\nparent Stream's data through some kind of filter (i.e. compression).\n\nBy default, a `StreamStack` instance proxies all events downstream (from the\nparent stream to the child stream), and proxies all functions calls upstream\n(from the child stream to the parent stream).\n\nKeeping the `StreamStack` subclass' implementation independent of the parent\n`Stream` instance allows for the backend transport to be easily swapped out\nfor flexibility and code re-use. For example, storing `netcat` results to a file,\nand using `fs.ReadStream` as your parent stream, rather than `net.Stream`, in your\ntest cases.\n\nSince `StreamStack` inherits from the regular node `Stream`, all it's prototypal\ngoodies can be used along with your subclass instances. This makes it extremely\neasy for you to call `Stream#pipe(writable)`, in order to utilize node's data\ntransfer philosophies.\n\n\nA Simple Example\n----------------\n\nHere's a simple, kinda silly example:\n\n``` js\nvar util = require('util');\nvar StreamStack = require('stream-stack').StreamStack;\n\n// The first argument is the parent stream\nfunction DoubleWrite(stream) {\n StreamStack.call(this, stream);\n}\nutil.inherits(DoubleWrite, StreamStack);\n\n// Overwrite the default `write()` function to call\n// write() on the parent stream twice!\nDoubleWrite.prototype.write = function(data) {\n this.stream.write(data);\n this.stream.write(data);\n}\n\n\n// How to Use:\nvar doubleStdout = new DoubleWrite(process.stdout);\ndoubleStdout.write(\"this will be printed twice!\\n\");\n```\n\nWe've defined a `DoubleWrite` class. It accepts a writable stream, and\nwhenever `write()` is called on the DoubleWrite instance, then in return\n`write()` get called _twice_ on the parent stream. In this example, our\nwritable stream, `process.stdout`, will get the string printed to it twice.\n\n\nKnown Subclasses\n----------------\n\nCheck out the [Wiki][] page to see the list of [Known Subclasses][Wiki].\n\n[Wiki]: https://github.com/TooTallNate/node-stream-stack/wiki\n", - "readmeFilename": "README.md", - "_id": "stream-stack@1.1.4", - "dist": { - "shasum": "8b9bfd0218acf670f82ba5b83cffeb633216b8a5" - }, - "_from": "stream-stack@>= 1.0.1", - "_resolved": "https://registry.npmjs.org/stream-stack/-/stream-stack-1.1.4.tgz" -} diff --git a/node_modules/stream-stack/stream-stack.js b/node_modules/stream-stack/stream-stack.js deleted file mode 100644 index a0a1fb9..0000000 --- a/node_modules/stream-stack/stream-stack.js +++ /dev/null @@ -1,209 +0,0 @@ -var Stream = require('stream').Stream; - -/** - * StreamStack - * ----------- - * Turns low-level `Stream` objects into stackable stream, meant - * to fill out your desired protocol stack. But also allow for - * the protocol to be implemented independent of the underlying - * transport. - * An example overall stack could look like: - * - net.Stream <- TCP Layer - * - HttpRequestStack <- HTTP Layer - * - `write()`s an HTTP request upstream - * - Response comes back with 'gzip' transfer-encoding - * - GzipDecoderStack <- Decoding Layer - * - `.pipe()` into a 'fs.WriteStream' <- Save to a File - */ -function StreamStack(stream, events) { - if (!(stream instanceof Stream)) { - throw new Error("StreamStack expects an instance of 'Stream' as an argument!"); - } - if (!(this instanceof StreamStack)) { - return new StreamStack(stream, events); - } - - Stream.call(this); - - // If this is the first time the parent stream has been used in a - // StreamStack, then a StackEmitter will need to be injected into the stream. - if (!stream._stackEmitter) { - StackEmitter.call(stream); - } - stream._stacks.push(this); - - // A reference to the parent stream for event handlers, etc. - this.stream = stream; - - // TODO: Remove, if I can find a good reason to. - events = events || {}; - if (!('data' in events)) - events.data = proxyEvent('data'); - if (!('end' in events)) - events.end = proxyEvent('end'); - if (!('error' in events)) - events.error = proxyEvent('error'); - if (!('close' in events)) - events.close = proxyEvent('close'); - if (!('fd' in events)) - events.fd = proxyEvent('fd'); - if (!('drain' in events)) - events.drain = proxyEvent('drain'); - - // If the StreamStack instance intends on intercepting events emitted from - // the parent stream, then the handlers need to be passed as a second 'events' - // object in the constructor. It takes care of attaching them to the parent - // stream. Handlers are invoked in 'this' StreamStack instance. - if (events) { - this._stackEvents = {}; - for (var ev in events) { - this._stackEvents[ev] = events[ev].bind(this); - stream.on(ev, this._stackEvents[ev]); - } - } - -} -require('util').inherits(StreamStack, Stream); -exports.StreamStack = StreamStack; - -// By default, just proxy all the standard ReadStream and WriteStream -// functions upstream. If the StreamStack implementation needs to overwrite -// or augment any of the behavior, then simply overwrite that function. -// The most common is to augment the 'write()' function, such that the -// passed data goes through some kind of filter before being passed to -// the parent stream. -StreamStack.prototype.write = function(buf, type) { - return this.stream.write(buf, type); -} -StreamStack.prototype.end = function(buf, type) { - if (buf) { - this.write(buf, type); - } - return this.stream.end(); -} -StreamStack.prototype.pause = function() { - if (this.stream.pause) { - return this.stream.pause(); - } else { - return this.stream.emit('pause'); - } -} -StreamStack.prototype.resume = function() { - if (this.stream.resume) { - return this.stream.resume(); - } else { - return this.stream.emit('resume'); - } -} -StreamStack.prototype.destroy = function(error) { - return this.stream.destroy(error); -} - -// The 'cleanup()' function should be called after a StreamStack instance is -// finished doing it's "thing", to cleanly allow another new StreamStack -// instance to be attached to the parent Stream. -StreamStack.prototype.cleanup = function() { - // Remove 'this' from the parent Stream's '_stacks' Array - var index = this.stream._stacks.indexOf(this); - this.stream._stacks.splice(index, 1); - // Set 'this.stream' to null. - // If any events were binded through the constructor, they get unbinded here - if (this._stackEvents) { - for (var ev in this._stackEvents) { - this.stream.removeListener(ev, this._stackEvents[ev]); - } - this._stackEvents = null; - } - // TODO: Maybe 'delete' instead? Is there any benefit? - this.stream = null; -} - -// By default, the 'readable' and 'writable' property lookups get proxied -// to the parent stream. You can set the variables if needed, and to relinquish -// control of the variable back upstream, set it to `undefined`. -Object.defineProperty(StreamStack.prototype, "readable", { - get: function() { - if (this._readable != undefined) { - return this._readable; - } - return this.stream.readable; - }, - set: function(value) { - this._readable = value; - }, - enumerable: true -}); -Object.defineProperty(StreamStack.prototype, "writable", { - get: function() { - if (this._writable != undefined) { - return this._writable; - } - return this.stream.writable; - }, - set: function(value) { - this._writable = value; - }, - enumerable: true -}); - -// Walks up the 'stream' properties until it finds and returns the top-most -// stream. i.e. it gets the low-level stream this stack is based on. -Object.defineProperty(StreamStack.prototype, "topStream", { - get: function() { - var rtn = this.stream; - while (rtn.stream) { - rtn = rtn.stream; - } - return rtn; - }, - enumerable: true -}); - -// Stupid workaround. Attach a listener for the given 'eventName'. -// The callback simply re-emits the events and all arguments on 'this'. -function proxyEvent(eventName) { - return function() { - var args = [eventName]; - args = args.concat(args.slice.call(arguments)); - this.emit.apply(this, args); - } -} - - -// Parent streams need to have StackEmitter called on them the first time a -// StreamStack instance is attempting to use it. The __proto__ of the parent -// stream will be injected with StackEmitter's prototype, to benefit from -// the overwritten 'emit()' function. -function StackEmitter() { - // The Array that holds the active StreamStack instances on a parent Stream. - this._stacks = []; - // Get a reference to the original 'emit' function, since we're about to - // monkey-patch with our own 'emit' function. - this._origEmit = this.emit; - // Mix-in the rest of the StackEmitter properties. - for (var prop in StackEmitter.prototype) { - this[prop] = StackEmitter.prototype[prop]; - } -} - -// A flag to indicate that the parent stream has already been injected. -StackEmitter.prototype._stackEmitter = true; - -// The custom 'emit()' function is responsible for iterating through the list -// of active StreamStack instances, and IFF the StreamStack instance didn't -// pass a handler to the current event, it should re-emit on the child as well. -StackEmitter.prototype.emit = function(eventName) { - var stack; - // Emit on the parent Stream first - var rtn = this._origEmit.apply(this, arguments); - // Next re-emit on all the active StreamStack instances (if any) - for (var i=0, l=this._stacks.length; i Date: Thu, 19 Dec 2013 07:30:57 +0100 Subject: [PATCH 3/3] removed junk code (console.log ..) --- server.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server.js b/server.js index 78f1629..ee7e08e 100644 --- a/server.js +++ b/server.js @@ -33,8 +33,8 @@ Server.prototype._setupConn = function(stream) { }); response.on('not_implemented', function (request) { - console.log("on not_implemented"); - console.log(JSON.stringify(request)); + //console.log("on not_implemented"); + //console.log(JSON.stringify(request)); self.emit('request', request, response); if (stream.readable && stream.writable) { self._setupConn(stream); @@ -45,7 +45,7 @@ Server.prototype._setupConn = function(stream) { // Called for every 'request' event, when a "handlers" Object was passed. Server.prototype._handler = function(request, response) { - console.log("server.js: " + JSON.stringify(request)); + //console.log("server.js: " + JSON.stringify(request)); if (request.functionCode in this.handlers) { this.handlers[request.functionCode].call(this, request, response); } else { @@ -102,7 +102,7 @@ Server.REQUESTS = { 17: no_parameters, //unknown function code - error case - 666: no_parameters + //666: no_parameters }; Server.RESPONSES = {