Skip to content

Instantly share code, notes, and snippets.

@crawfordcomeaux
Last active August 29, 2015 14:22
Show Gist options
  • Save crawfordcomeaux/50337c281e82c556b123 to your computer and use it in GitHub Desktop.
Save crawfordcomeaux/50337c281e82c556b123 to your computer and use it in GitHub Desktop.
[SOLVED] Testing odd cap.js behavior where packets aren't being recorded properly
var ip = require('ip');
var myIP = ip.address();
var Cap = require('cap').Cap,
decoders = require('cap').decoders,
PROTOCOL = decoders.PROTOCOL;
var c = new Cap(),
device = Cap.findDevice(myIP),
filter = 'tcp port 80',
bufSize = 10 * 1024 * 1024,
buffer = new Buffer(65535);
var linkType = c.open(device, filter, bufSize, buffer);
//c.setMinBytes && c.setMinBytes(0);
var p = [];
c.on('packet', function(nbytes, trunc) {
// Previously:
// p.push(buffer.slice(0, nbytes));
// The problem: Buffer.slice() doesn't copy the memory, it references it.
// So a reference to the memory allocated to buffer was being push into the array on each packet.
// Each cell in the array thus contained a reference to the same spot in memory: buffer's.
// Now:
var x = new Buffer(nbytes);
buffer.copy(x,0,0,nbytes);
p.push(x);
});
Performed these steps with Wireshark running alongside it. Afterward, p contains the right number of entries with the correct lengths, but the buffers themselves have the wrong data. Each begins with the same packet data: the last packet Wireshark picked up to/from port 80. Am I breaking some kind of async coding laws?
$ sudo node
> .load capture.js
# .....do some stuff to generate packets.....
> c.close();
> function seq(x){return decoders.TCP(x,decoders.IPV4(x,decoders.Ethernet(x).offset).offset).info.seqno;}
> p.map(seq);
# output is an array of the same sequence number, but they should all be different
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment