Exemple #1
0
function decodeTopicMetadatas(resp) {
    var out = {},
        topicMetadata = {},
        errors = [],
        cur,
        topicNum = Binary.parse(resp).word32bu('num').vars.num;
    resp = resp.slice(4);
    for(var i=0; i<topicNum; i++) {
        cur = 2 + 2 + 4;
        var topic = Binary.parse(resp)
            .word16bu('topicError')
            .word16bu('topicName')
            .tap(function (vars) {
                cur += vars.topicName;
                this.buffer('topicName', vars.topicName);
            })
            .word32bu('partitionNum')
            .vars;
        resp = resp.slice(cur);
        if (topic.topicError !== 0) {
            topic.error = ERROR_CODE[topic.topicError];
            out.error = topic;
            continue;
        } 
        var partitionMetadata = {};
        for (var j=0; j<topic.partitionNum; j++) {
            cur = 2 + 4 + 4 + 4 + 4;
            var p = Binary.parse(resp)
                .word16bu('errorCode')
                .word32bu('partition')
                .word32bu('leader')
                .word32bu('replicasNum')
                .tap(function (vars) {
                    cur += vars.replicasNum * 4;
                    var buffer = this.buffer('replicas', vars.replicasNum * 4).vars.replicas; 
                    this.vars.replicas = bufferToArray(vars.replicasNum, buffer);
                })
                .word32bu('isrNum')
                .tap(function (vars) {
                    cur += vars.isrNum * 4;
                    var buffer = this.buffer('isr', vars.isrNum * 4).vars.isr;
                    this.vars.isr = bufferToArray(vars.isrNum, buffer);
                }).vars;
            
            resp = resp.slice(cur);
            p.topic = topic.topicName.toString();
            if (p.errorCode !==0) {
                p.error = ERROR_CODE[p.errorCode];
                errors.push(p);
            } else {
                partitionMetadata[p.partition] = 
                    new PartitionMetadata(p.topic, p.partition, p.leader, p.replicas, p.isr);
            }
        }
        topicMetadata[topic.topicName] = partitionMetadata;
    }
    if (!_.isEmpty(errors)) out.error = errors;
    out.metadata = topicMetadata;
    return out;
}
Exemple #2
0
function decodeOffsetCommitResponse(resp) {
    var vars = Binary.parse(resp)
                .word32bu('size')
                .word32bu('correlationId')
                .word32bu('topicNum')
                .vars;
    var cur = 4 + 4 + 4;
    resp = resp.slice(cur);
    var out = {}; 
    for (var i=0; i<vars.topicNum; i++) {
        cur = 2 + 4;
        var topic = Binary.parse(resp)
                    .word16bu('topic')
                    .tap(function (vars) {
                        cur += vars.topic;
                        this.buffer('topic', vars.topic);
                    })
                    .word32bu('partitionNum')
                    .vars;
        resp = resp.slice(cur);
        out[topic.topic] = {};

        for (var j=0; j<topic.partitionNum; j++) {
            cur = 4 + 2;
            var partition = Binary.parse(resp)
                            .word32bu('partition')
                            .word16bu('errorCode')
                            .vars;
            resp = resp.slice(cur);
            out[topic.topic] = partition;
        } 
    }
    return out;
}
Exemple #3
0
  function parseResult(err, result) {
    var i;
    if (err) {
      cb(err);
      return;
    }
    console.log('About to parse:', result.data);
    var parsed = binary.parse(result.data)
      .word16be('d505')
      .word8('err')
      .word8('field')
      .word8('nbTg')
      .vars;
    var status = { raw: parsed, tags: [] };

    if (parsed.d505 != 0xd505) {
      cb(new Error('Received unexpected response to getGeneralStatus (' +
              parsed.d505 + ', expected ' + 0xd505),
         status);
      return;
    }

    if (errorStrings[parsed.err]) {
      status.error = errorStrings[parsed.err];
    }

    status.field = parsed.field ? true : false;

    for (i = 0; i < parsed.nbTg + 0; ++i) {
      var tagOffset = 5 + 3*i;
      var tagRaw = result.data.slice(tagOffset, tagOffset + 4);
      if (tagRaw.length < 4) {
        status.tags[i] = {};
        cb(new Error('Mismatch in tag count: ' + parsed.nbTg + ' reported, ' +
            i + ' found'),
           status);
        return;
      }
      var tag = {
        'raw' : binary.parse(tagRaw)
         .word8('tg')
         .word8('brRx')
         .word8('brTx')
         .word8('type')
         .vars,
      };
      tag.rxRate = convertRateByteToRate(tag.raw.brRx);
      tag.txRate = convertRateByteToRate(tag.raw.brTx);
      tag.type = convertModulationByteToModulation(tag.raw.type);
      status.tags[i] = tag;
    }
    cb(null, status);
  }
Exemple #4
0
function _decodeFetchResponse(resp, cb) {
    var cur = 4 + 4 + 4,
        fetchResponse = new FetchResponse(),
        responses = [],
        topics = {};
    var topicNum = Binary.parse(resp)
                    .word32bu('size')
                    .word32bu('correlationId')
                    .word32bu('topicNum')
                    .vars.topicNum;
    resp = resp.slice(cur);
    for (var i=0; i< topicNum; i++) {
        cur = 2 + 4;
        var topic = Binary.parse(resp)
                            .word16bu('topic')
                            .tap(function (vars) {
                                cur += vars.topic;
                                this.buffer('topic', vars.topic);
                                vars.topic = vars.topic.toString();
                            })
                            .word32bu('partitionNum')
                            .vars;
        resp = resp.slice(cur);
        fetchResponse.topic = topic.topic;
        fetchResponse.fetchPartitions = fetchResponse.fetchPartitions || [];
        topics[topic.topic] = {};
        for(var j=0; j<topic.partitionNum; j++) {
            cur = 4 + 2 + 8 + 4;
            var vars  = Binary.parse(resp)
                                .word32bu('partition')
                                .word16bu('errorCode')
                                .word64bu('highWaterOffset')
                                .word32bu('messageSetSize')
                                .tap(function (vars) {
                                    cur += vars.messageSetSize;
                                    this.buffer('messageSet', vars.messageSetSize)
                                })
                                .vars;
            if (vars.errorCode !== 0) cb && cb({ topic: topic.topic, partition: vars.partition, message:  ERROR_CODE[vars.errorCode] });
            vars.messageSet = decodeMessageSet(topic.topic, vars.partition, vars.messageSet, cb);
            fetchResponse.fetchPartitions.push(vars);
            if (vars.messageSet.length) {
                var offset = vars.messageSet[vars.messageSet.length-1].offset;
                topics[topic.topic][vars.partition] = offset;
            }
            resp = resp.slice(cur);
        }
        responses.push(fetchResponse);
    }
    cb && cb(null, 'done', topics);
    return responses;
}
Exemple #5
0
KafkaTransport.prototype.decodeMessageSet = function(bytesOrBin, callback, end) {
	var self = this;
	var bin;
	bytesOrBin instanceof Buffer
		? bin = Binary.parse(bytesOrBin)
		: bin = bytesOrBin

	if(!bin.eof()) {
		var header = this.decode(this.schema.MessageHeader, bin);
		var msg = this.decode(this.schema.Message, Binary.parse(header.Message));
		switch(msg.Attributes) {
			case this.compressions.gzip:
				try {
					zlib.gunzip(msg.Value, function(err, gunzipped) {				
						process.nextTick(function() {
              self.decodeMessageSet(gunzipped, callback, end);
            });
					})
				}
				catch(e) {
					console.log('zlib decompression error:', e);
				}
			break;
			case this.compressions.snappy:
				try {
					snappy.decompress(msg.Value, snappy.parsers.raw, function(err, unsnapped){
						process.nextTick(function() {
              self.decodeMessageSet(unsnapped, callback, end);
            })
					});
				}
				catch(e) {
					console.log('snappy decompression error:', e)
				}
			break;
			default:
				callback(msg.Value, msg, function() {
					process.nextTick(function() {
            self.decodeMessageSet(bin, callback, end);
          })
				});
		}
	}
	else {
		process.nextTick(function() {
        end();
    })
	}
}
Exemple #6
0
Response.fromBytes = function(data){
  if (!Buffer.isBuffer(data)){
    throw "The data parameter must be a Buffer object.";
  }
  var length = binary.parse(data).word32bu('length').vars.length;
  var unpacked = binary.parse(data)
      .word32bu('length')
      .word16bs('error')
      .buffer('body', length)
      .vars;
      if (unpacked.body.length + 4 < length){
        throw "incomplete response";
      }
  return new Response(unpacked.error, unpacked.body);
};
Exemple #7
0
function decodeProduceResponse(resp) {
    var topics = {};
    var error;
    Binary.parse(resp)
        .word32bs('size')
        .word32bs('correlationId')
        .word32bs('topicNum')
        .loop(decodeTopics(decodePartitions));

    function decodePartitions (end, vars) {
        if (--vars.partitionNum === 0) end();
        topics[vars.topic] = topics[vars.topic] || {};
        this.word32bs('partition')
            .word16bs('errorCode')
            .word64bs('offset')
            .tap(function (vars) {
                if (vars.errorCode) {
                    error = new Error(ERROR_CODE[vars.errorCode]);
                } else {
                    topics[vars.topic][vars.partition] = vars.offset;
                }
            });
    }
    return error || topics;
}
Exemple #8
0
                c.on('data', function (data) {
                    //logger.info("server receiving:");
                    //logger.info(data);

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

                    }
                    chunk = chunk + 1;

                    //logger.info("receiver.length="+receiver.length);

                    if (receiver.length >= (length + 8)) {
                        //var res = this.parseResponse(receiver);
                        //if (callback) { callback(res); }
                        //logger.info(res.content);

                        var response = that.parseRequest(receiver, name);

                        var buf = that.buildResponse(response);
                        logger.verbose('binrpc --> '+name+' response ' + JSON.stringify(response));
                        logger.silly(buf);

                        c.write(buf);
                    }

                });
Exemple #9
0
exports.posbs = function () {
    var to = setTimeout(function () {
        assert.fail('never tapped');
    }, 500);
    
    // note: can't store 12667700813876161 exactly in an ieee float
    
    var buf = new Buffer([
        30, // a == -30
        9, 37, // b == -2341
        0, 12, 10, 20, // c == -789012
        0, 45, 1, 52, 239, 33, 203, 193, // d == 12667700813876161
    ]);
    
    Binary.parse(buf)
        .word8bs('a')
        .word16bs('b')
        .word32bs('c')
        .word64bs('d')
        .tap(function (vars) {
            clearTimeout(to);
            assert.eql(vars.a, 30);
            assert.eql(vars.b, 2341);
            assert.eql(vars.c, 789012);
            assert.ok(
                Math.abs(vars.d - 12667700813876161) < 1000
            );
        })
    ;
};
Exemple #10
0
exports.loop = function () {
    var to = setTimeout(function () {
        assert.fail('never tapped');
    }, 50);
    
    var res = Binary.parse(new Buffer([ 97, 98, 99, 4, 5, 2, -3, 9 ]))
        .word8('a')
        .word16be('bc')
        .loop(function (end) {
            var x = this.word8s('x').vars.x;
            if (x < 0) end();
        })
        .tap(function (vars) {
            clearTimeout(to);
            assert.eql(vars, {
                a : 97,
                bc : 25187,
                x : -3,
            });
        })
        .word8('y')
        .vars
    ;
    assert.eql(res, {
        a : 97,
        bc : 25187,
        x : -3,
        y : 9,
    });
};
Exemple #11
0
exports.parse = function () {
    var to = setTimeout(function () {
        assert.fail('never tapped');
    }, 50);
    
    var res = Binary.parse(new Buffer([ 97, 98, 99, 99, 99, 99, 1, 2, 3 ]))
        .word8('a')
        .word16be('bc')
        .skip(3)
        .buffer('def', 3)
        .tap(function (vars) {
            clearTimeout(to);
            assert.eql(vars, {
                a : 97,
                bc : 25187,
                def : new Buffer([ 1, 2, 3]),
            });
        })
        .vars
    ;
    assert.eql(res, {
        a : 97,
        bc : 25187,
        def : new Buffer([ 1, 2, 3 ]),
    });
};
Exemple #12
0
exports.negbs = function () {
    var to = setTimeout(function () {
        assert.fail('never tapped');
    }, 500);
    
    // note: can't store -12667700813876161 exactly in an ieee float
    
    var buf = new Buffer([
        226, // a == -30
        246, 219, // b == -2341
        255, 243, 245, 236, // c == -789012
        255, 210, 254, 203, 16, 222, 52, 63, // d == -12667700813876161
    ]);
    
    Binary.parse(buf)
        .word8bs('a')
        .word16bs('b')
        .word32bs('c')
        .word64bs('d')
        .tap(function (vars) {
            clearTimeout(to);
            assert.eql(vars.a, -30);
            assert.eql(vars.b, -2341);
            assert.eql(vars.c, -789012);
            assert.ok(
                Math.abs(vars.d - -12667700813876161) < 1500
            );
        })
    ;
};
Exemple #13
0
        client.on('data', function(data) {
            //console.log("--> receiving chunk "+chunk+" data.length="+data.length);
    
            if (chunk == 0) {
                var vars = binary.parse(data)
                    .buffer("head", 3)
                    .word8("msgType")
                    .word32bu("msgSize")
                    .vars;
                length = vars.msgSize;
                response = data;
            } else {
                response = Buffer.concat([response, data]);
    
            }
            chunk = chunk + 1;
    
            //console.log("receive response chunk=" + chunk + " response.length="+response.length+ " length=" + length);
    
            if (response.length >= (length)) {
                //console.log('received response', response.length, response);
                var name = client.remoteAddress+":"+client.remotePort;
                client.end();
                var res = that.parseResponse(response, name);
                //console.log('--> '+name+ " closing connection");
                if (typeof callback === 'function') callback(null, res);
                response = new Buffer(0);
                chunk = 0;
            }

        });
Exemple #14
0
  self.pull(42).then(function(data) {
    
    var vars = binary.parse(data)
      .word16lu('versionMadeBy')
      .word16lu('versionsNeededToExtract')
      .word16lu('flags')
      .word16lu('compressionMethod')
      .word16lu('lastModifiedTime')
      .word16lu('lastModifiedDate')
      .word32lu('crc32')
      .word32lu('compressedSize')
      .word32lu('uncompressedSize')
      .word16lu('fileNameLength')
      .word16lu('extraFieldLength')
      .word16lu('fileCommentLength')
      .word16lu('diskNumber')
      .word16lu('internalFileAttributes')
      .word32lu('externalFileAttributes')
      .word32lu('offsetToLocalFileHeader')
      .vars;

    return self.pull(vars.fileNameLength).then(function(fileName) {
      vars.fileName = fileName.toString('utf8');
      return self.pull(vars.extraFieldLength);
    })
    .then(function(extraField) {
      return self.pull(vars.fileCommentLength);
    })
    .then(function(fileComment) {
      return self._readRecord();
    });
  });
Exemple #15
0
Client.prototype.handleReceivedData = function (socket) {
        var vars = Binary.parse(socket.buffer).word32bu('size').word32bu('correlationId').vars,
            size = vars.size + 4,
            correlationId = vars.correlationId;
        if (socket.buffer.length >= size) {
            var resp = socket.buffer.slice(0, size);
            var handlers = this.cbqueue[correlationId],
                decoder = handlers[0],
                cb = handlers[1];
            // Delete callback functions after finish a request
            delete this.cbqueue[correlationId];

            var decoded = decoder(resp);
            // ProduceResponse and MetadataResponse decoders return the results in a format different than the other decoders (wrapped in a 'response' object to differentiate it from other decoders).
            // TODO: standarize return object with other decoders.
            if (decoded && decoded.response) {
                cb.call(this, decoded.response.error, decoded.response.success);
            } else {
                cb.call(this, null, decoded);
            }

            socket.buffer = socket.buffer.slice(size);
            if (socket.longpolling) socket.waitting = false;
        } else { return }

    if (socket.buffer.length) 
        setImmediate(function () { this.handleReceivedData(socket);}.bind(this));
}
Exemple #16
0
function decodeOffsetFetchResponse(resp) {
    var topics = {};
    Binary.parse(resp)
        .word32bs('size')
        .word32bs('correlationId')
        .word32bs('topicNum')
        .loop(decodeTopics(decodePartitions));

    function decodePartitions (end, vars) {
        if (--vars.partitionNum === 0) end();
        topics[vars.topic] = topics[vars.topic] || {};
        this.word32bs('partition')
            .word64bs('offset')
            .word16bs('metadata')
            .tap(function (vars) {
                if (vars.metadata === -1) {
                    return
                }

                this.buffer('metadata', vars.metadata);
            })
            .word16bs('errorCode')
            .tap(function (vars) {
                topics[vars.topic][vars.partition] = vars.errorCode === 0 ? vars.offset : -1;
            });
    }
    return topics;
}
Exemple #17
0
function _decodeFetchResponse(resp, cb, maxTickMessages) {
    var topics = {};
    Binary.parse(resp)
        .word32bs('size')
        .word32bs('correlationId')
        .word32bs('topicNum')
        .loop(decodeTopics(decodePartitions));

    function decodePartitions (end, vars) {
        if (--vars.partitionNum === 0) end();
        topics[vars.topic] = topics[vars.topic] || {};
        this.word32bs('partition')
            .word16bs('errorCode')
            .word64bs('highWaterOffset')
            .word32bs('messageSetSize')
            .tap(function (vars) {
                this.buffer('messageSet', vars.messageSetSize)
                if (vars.errorCode !== 0)
                    return cb({ topic: vars.topic, partition: vars.partition, message:  ERROR_CODE[vars.errorCode] });
                var messageSet = decodeMessageSet(vars.topic, vars.partition, vars.messageSet, cb, maxTickMessages);
                if (messageSet.length) {
                    var offset = messageSet[messageSet.length-1];
                    topics[vars.topic][vars.partition] = offset;
                }
            });
    }
    cb && cb(null, 'done', topics);
}
server.on('message', function(buf) {
	Binary.parse(buf)
		.word8('ver')
		.word8('type')
		.tap(function(vars) {
			if (vars.type === 1) {
				this
					.word16bu('flags')
					.word16bu('notlen')
					.word16bu('titlen')
					.word16bu('desclen')
					.word16bu('applen')
					.buffer('notbuf', 'notlen')
					.buffer('titbuf', 'titlen')
					.buffer('descbuf', 'desclen')
					.buffer('appbuf', 'applen')
					.buffer('mdf', 16)
					.tap(function(vars) {
						var notification = vars.notbuf.toString('UTF8');
						var title = vars.titbuf.toString('UTF8');
						var description = vars.descbuf.toString('UTF8');
						var application = vars.appbuf.toString('UTF8');
						
						exec('notify-send "' + title + '" "' + description + '"');
					})
			}
		});
});
Exemple #19
0
  it("should binary encode a request with a message, using a specific wire format", function(){
    var message = new Message("ale");

    var encodedRequest;
    try {
      encodedRequest = new ProduceRequest('test', 0, [message]).toBytes();
    } catch (ex){
      console.log("EX!: ", ex);
    }


    var unpacked = binary.parse(encodedRequest)
    .word32bu('dataSize')
    .word16bu('requestId')
    .word16bu('topicLength')
    .buffer('topic', 4)
    .word32bu('partition')
    .word32bu('messagesLength')
    .tap(function(vars){
      this.buffer('messages', vars.messagesLength);
    })
    .vars;


    encodedRequest.length.should.equal(33);
    unpacked.dataSize.should.eql(29);
    unpacked.requestId.should.eql(0);
    unpacked.topicLength.should.eql(4);
    unpacked.topic.toString('utf8').should.eql("test");
    unpacked.partition.should.eql(0);
    unpacked.messagesLength.should.eql(13);
  });
				function extractChrsAndDetermineEncoding(callback) {
					//
					//	From FTS-5003.001:
					//	"The CHRS control line is formatted as follows:
					//
					//	^ACHRS: <identifier> <level>
					//
					//	Where <identifier> is a character string of no more than eight (8)
					//	ASCII characters identifying the character set or character encoding
					//	scheme used, and level is a positive integer value describing what
					//	level of CHRS the  message is written in."
					//
					//	Also according to the spec, the deprecated "CHARSET" value may be used
					//	:TODO: Look into CHARSET more - should we bother supporting it?
					//	:TODO: See encodingFromHeader() for CHRS/CHARSET support @ https://github.com/Mithgol/node-fidonet-jam
					const FTN_CHRS_PREFIX 	= new Buffer( [ 0x01, 0x43, 0x48, 0x52, 0x53, 0x3a, 0x20 ] );	//	"\x01CHRS:"
					const FTN_CHRS_SUFFIX	= new Buffer( [ 0x0d ] );
					binary.parse(messageBodyBuffer)
						.scan('prefix', FTN_CHRS_PREFIX)
						.scan('content', FTN_CHRS_SUFFIX)
						.tap(chrsData => {
							if(chrsData.prefix && chrsData.content && chrsData.content.length > 0) {
								const chrs = iconv.decode(chrsData.content, 'CP437');
								const chrsEncoding = ftn.getEncodingFromCharacterSetIdentifier(chrs);
								if(chrsEncoding) {
									encoding = chrsEncoding;
								}
								callback(null);
							} else {
								callback(null);
							}
						});
				},
Exemple #21
0
function decodeMessageSet(topic, partition, messageSet, cb) {
    var set = [];
    while (messageSet.length > 0) {
        var cur = 8 + 4 + 4 + 1 + 1 + 4 + 4;
        Binary.parse(messageSet)
            .word64bu('offset')
            .word32bu('messageSize')
            .word32bu('crc')
            .word8bu('magicByte')
            .word8bu('attributes')
            .word32bs('key')
            .tap(function (vars) {
                if (vars.key == -1)  return;
                cur += vars.key;
                this.buffer('key', vars.key);
            })
            .word32bu('value')
            .tap(function (vars) {
                if (vars.value == -1)  return;
                cur += vars.value;
                this.buffer('value', vars.value);
                vars.value = vars.value.toString();
                cb && cb(null, 'message', { topic: topic, value: vars.value, offset: vars.offset, partition: partition });  
                set.push(vars.offset);
            });
        messageSet = messageSet.slice(cur);
    }
    return set;
}
Exemple #22
0
exports.getBuffer = function () {
    var t1 = setTimeout(function () {
        assert.fail('first buffer never finished');
    }, 20);
    
    var t2 = setTimeout(function () {
        assert.fail('second buffer never finished');
    }, 20);
    
    var buf = new Buffer([ 4, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]);
    Binary.parse(buf)
        .word8('a')
        .buffer('b', 7)
        .word16lu('c')
        .tap(function (vars) {
            clearTimeout(t1);
            assert.eql(vars, {
                a : 4, 
                b : new Buffer([ 2, 3, 4, 5, 6, 7, 8 ]),
                c : 2569,
            });
        })
        .buffer('d', 'a')
        .tap(function (vars) {
            clearTimeout(t2);
            assert.eql(vars.d, new Buffer([ 11, 12, 13, 14 ]));
        })
    ;
};
Exemple #23
0
function decodeOffsetResponse(resp) {
    var topics = {};
    Binary.parse(resp)
        .word32bs('size')
        .word32bs('correlationId')
        .word32bs('topicNum')
        .loop(decodeTopics(decodePartitions));

    function decodePartitions (end, vars) {
        if (--vars.partitionNum === 0) end();
        topics[vars.topic] = topics[vars.topic] || {};
        this.word32bs('partition')
            .word16bs('errorCode')
            .word32bs('offsetNum')
            .loop(decodeOffsets);
    }

    function decodeOffsets (end, vars) {
        if (--vars.offsetNum <= 0) end();
        topics[vars.topic][vars.partition] = topics[vars.topic][vars.partition] || [];
        this.word64bs('offset')
            .tap(function (vars) {
                if (vars.offset != null) topics[vars.topic][vars.partition].push(vars.offset);
            });
    }
    return topics;
}
Exemple #24
0
            function processDescriptor(bufs, sigIndex) {
              if (bufs.length < sigIndex + 16) {
                process.nextTick(function() {
                  self._untilStream.pull(sigIndex + 16 - bufs.length, function(err, data) {
                    if (err) {
                      return self.emit('error', err);
                    }

                    bufs.push(data)
                    processDescriptor(bufs, sigIndex);
                  })
                })
              } else {
                var dataDescriptor = binary.parse(bufs.slice(sigIndex + 4, sigIndex + 16))
                  .word32lu('crc32')
                  .word32lu('compressedSize')
                  .word32lu('uncompressedSize')
                  .vars;

                entry.size = dataDescriptor.uncompressedSize;
                self._untilStream.prepend(bufs.slice(sigIndex + 16, bufs.length));
                inflater.write(bufs.slice(0, sigIndex));
                inflater.end();
              }
            }
Exemple #25
0
Script.prototype.parse = function () {
  this.chunks = [];

  var parser = Binary.parse(this.buffer);
  while (!parser.eof()) {
    var opcode = parser.word8('opcode').vars.opcode;
    if (opcode >= 0xF0) {
      // Two byte opcode
      opcode = (opcode << 8) | parser.word8('opcode2').vars.opcode2;
    }

    if (opcode > 0 && opcode < OP_PUSHDATA1) {
      // Read some bytes of data, opcode value is the length of data
      this.chunks.push(parser.buffer('data', opcode).vars.data);
    } else if (opcode == OP_PUSHDATA1) {
      parser.word8('len');
      this.chunks.push(parser.buffer('data', 'len').vars.data);
    } else if (opcode == OP_PUSHDATA2) {
      parser.word16le('len');
      this.chunks.push(parser.buffer('data', 'len').vars.data);
    } else if (opcode == OP_PUSHDATA4) {
      parser.word32le('len');
      this.chunks.push(parser.buffer('data', 'len').vars.data);
    } else {
      this.chunks.push(opcode);
    }
  }
};
OPTION_IMPLS[OPTIONS.WINDOW_SIZE] = function (bufs, i, event) {
  if (event.commandCode !== COMMANDS.SB) {
    OPTION_IMPLS.NO_ARGS(bufs, i, event)
  } else {
    // receiving a "resize" event
    if (bufs.length < 9) return MORE
    event.buf = bufs.splice(0, 9).toBuffer()
    Binary.parse(event.buf)
      .word8('iac1')
      .word8('sb')
      .word8('naws')
      .word16bu('width')
      .word16bu('height')
      .word8('iac2')
      .word8('se')
      .tap(function (vars) {
        //console.error(vars)
        assert(vars.iac1 === COMMANDS.IAC)
        assert(vars.iac2 === COMMANDS.IAC)
        assert(vars.sb === COMMANDS.SB)
        assert(vars.se === COMMANDS.SE)
        assert(vars.naws === OPTIONS.WINDOW_SIZE)
        event.cols = event.columns = event.width = vars.width
        event.rows = event.height = vars.height
      })
  }
  return event
}
Exemple #27
0
        client.on('data', function (data) {
            if (chunk === 0) {
                // request header
                var vars = binary.parse(data)
                    .buffer('head', 3)
                    .word8('msgType')
                    .word32bu('msgSize')
                    .vars;
                length = vars.msgSize;
                receiver = data;
            } else {
                // append request data
                receiver = Buffer.concat([receiver, data]);
            }

            chunk += 1;

            if (receiver.length >= (length + 8)) {
                // request complete
                var request = binrpc.decodeRequest(receiver);

                receiver = Buffer.alloc(0);
                chunk = 0;

                that.handleCall(request, client);
            }
        });
  3: function(buf) {
      var response = [];
      var unpacker = NBinary.parse(buf);
      unpacker
        .loop(
          function(end, val) {
            if (this.eof()) {
              end();
            } else {
              this
                .word16bu('this')
                .tap(
                  function(vars) {
                    response.push(vars.this);
      //              console.log(vars);
                  }
                )
              ;
            }
          }
        )
      ; 

      return response;

    },
Exemple #29
0
  this._pullStream.pull(18, function (err, data) {
    if (err) {
      return self.emit('error', err);
    }

    var vars = binary.parse(data)
      .word16lu('diskNumber')
      .word16lu('diskStart')
      .word16lu('numberOfRecordsOnDisk')
      .word16lu('numberOfRecords')
      .word32lu('sizeOfCentralDirectory')
      .word32lu('offsetToStartOfCentralDirectory')
      .word16lu('commentLength')
      .vars;

    if (vars.commentLength) {
      process.nextTick(function() {
        self._pullStream.pull(vars.commentLength, function (err, comment) {
          if (err) {
            return self.emit('error', err);
          }
          comment = comment.toString('utf8');
          return self._pullStream.end();
        });
      });

    } else {
      self._pullStream.end();
    }
  });
Exemple #30
0
    decodeData: function (data) {
        if (!(data instanceof Buffer)) throw new TypeError('argument \'elem\' must be an instance of Buffer');
        if (!data) return;

        var res = binary.parse(data)
            .word32bu('dataType')
            .buffer('elements', data.length)
            .vars
            ;

        switch (res.dataType) {
            case 0x101:
                return this.decodeStruct(res.elements);
                break;
            case 0x100:
                return this.decodeArray(res.elements);
                break;
            case 0x04:
                return this.decodeDouble(res.elements);
                break;
            case 0x03:
                return this.decodeString(res.elements);
                break;
            case 0x02:
                return this.decodeBool(res.elements);
                break;
            case 0x01:
                return this.decodeInteger(res.elements);
                break;
            default:
                console.log("<-- binrpc error: unknow data type " + res.dataType.toString(16) + " :(");
                return;

        }
    },