Node JS UDP server: Offset into buffer too large (Error) - node.js

I am trying to send a message to a client by doing:
server.send(new Buffer("Hello World!"), data.port, data.ip);
but I always get the following error:
dgram.js:256
throw new RangeError('Offset into buffer too large');
^
RangeError: Offset into buffer too large
at Socket.send (dgram.js:256:11)
at Socket.<anonymous> (/home/lchost/fishy.io/server/custom_modules/game.js:50:14)
at Socket.emit (events.js:98:17)
at UDP.onMessage (dgram.js:441:8)
Any Ideas what am I doing wrong?

I should have done this:
server.send(new Buffer("Hello World!"), 0, 0, data.port, data.ip);

var data = new Buffer("Hello World!");
server.send(data, 0, data.length, data.port, data.ip);
Tested in node v0.10.29

Related

Issue with connecting to rethinkdb from Windows 11 via thinky (nodejs)

I'm trying to onboard a new developer, that is using Windows 11 as the only one on our small team. I've guided him through installing WSL2 and Ubuntu 20.04.3 LTS (linux kernel: 5.10.93.2-microsoft-standard-WSL2).
We are 3 other developers who are using native Ubuntu, WSL2 Ubuntu 21.04 and macOS, respectively.
We are all on nodejs 16.14 with the exact same package-lock.json file.
He is the only one getting an Error [ERR_STREAM_WRITE_AFTER_END]: write after end.
tldr;
Both errors are about writing to a Buffer.
Is anyone aware of any related issues to nodejs's Buffer implementation on Windows 11?
We are using thinky as outlined below:
'use strict';
const createThinky = require('thinky');
const { rethinkdbConfig } = require ('./utils/config.js');
const thinky = createThinky (rethinkdbConfig);
// Thinky is our ORM
var type = thinky.type;
// Creates the thinky DB model for payments - we save the amount and the stripe customerID for each transaction
// You can execute any rethinkdb query language on the model, eg Payment.count().execute()
var Payment = thinky.createModel("payments", {
id: type.string(),
amount: type.number(),
customerID: type.string(),
project: type.string(),
projectName: type.string(),
projectPercentage: type.number(),
firefundPercentage: type.number(),
type: type.string(),
processor: type.string(),
email: type.string(),
charged: type.boolean(),
recharged: type.boolean()
});
module.exports = {
model: Payment,
};
Now, it doesn't matter if he connects to a local instance of rethinkdb (2.4.1~0focal), our staging or production rethinkdb (2.3.5~0trusty) on AWS.
I got him to try Netcat with nc -zv [url] 28015 to see if he could connect at all and he got connectıon successful. So I do not think it is a firewall issue.
Error stack trace
node ./bin/www
firefund:www Listening on port 3000 +0ms
node:events:498
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:371:5)
at _write (node:internal/streams/writable:319:11)
at Socket.Writable.write (node:internal/streams/writable:334:10)
at Connection._sendProof (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:294:19)
at /home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:248:12
at Object.tryCatch (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/helper.js:170:3)
at Connection._computeSaltedPassword (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:247:12)
at Socket.<anonymous> (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:184:18)
at Socket.emit (node:events:520:28)
at Socket.emit (node:domain:475:12)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
Emitted 'error' event on Connection instance at:
at Socket.<anonymous> (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:129:12)
at Socket.emit (node:events:520:28)
at Socket.emit (node:domain:475:12)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
The stack trace indicates that it is a connection error in node_modules/rethinkdbdash/lib/connection.js.
connection.js
connection.js: line 294 is this.connection.write(Buffer.concat([new Buffer(message.toString()), NULL_BUFFER])) at the bottom.
Connection.prototype._sendProof = function(authentication, randomNonce, saltedPassword) {
var clientFinalMessageWithoutProof = "c=biws,r=" + randomNonce;
var clientKey = crypto.createHmac("sha256", saltedPassword).update("Client Key").digest()
var storedKey = crypto.createHash("sha256").update(clientKey).digest()
var authMessage =
"n=" + this.user + ",r=" + this.randomString + "," +
authentication + "," +
clientFinalMessageWithoutProof
var clientSignature = crypto.createHmac("sha256", storedKey).update(authMessage).digest()
var clientProof = helper.xorBuffer(clientKey, clientSignature)
var serverKey = crypto.createHmac("sha256", saltedPassword).update("Server Key").digest()
this.serverSignature = crypto.createHmac("sha256", serverKey).update(authMessage).digest()
this.state = 2
var message = JSON.stringify({
authentication: clientFinalMessageWithoutProof + ",p=" + clientProof.toString("base64")
})
this.connection.write(Buffer.concat([new Buffer(message.toString()), NULL_BUFFER]))
}
Variant Error
He has also reported a variant of the same error as posted below:
node ./bin/www
firefund:www Listening on port 3000 +0ms
node:events:498
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:371:5)
at _write (node:internal/streams/writable:319:11)
at Socket.Writable.write (node:internal/streams/writable:334:10)
at /home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:143:23
at Object.tryCatch (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/helper.js:170:3)
at Socket.<anonymous> (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:142:12)
at Socket.emit (node:events:523:35)
at Socket.emit (node:domain:475:12)
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1143:10)
Emitted 'error' event on Connection instance at:
at Socket.<anonymous> (/home/edel_weiss/firefund-production/node_modules/rethinkdbdash/lib/connection.js:129:12)
at Socket.emit (node:events:520:28)
at Socket.emit (node:domain:475:12)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
This variant suggest that the error is at line 143 in connection.js:
self.connection.write(Buffer.concat([versionBuffer, authBuffer, NULL_BUFFER]));
self.connection.on('connect', function() {
self.connection.removeAllListeners('error');
self.connection.on('error', function(error) {
self.emit('error', error);
});
var versionBuffer = new Buffer(4)
versionBuffer.writeUInt32LE(protodef.VersionDummy.Version.V1_0, 0)
self.randomString = new Buffer(crypto.randomBytes(18)).toString('base64')
var authBuffer = new Buffer(JSON.stringify({
protocol_version: PROTOCOL_VERSION,
authentication_method: AUTHENTIFICATION_METHOD,
authentication: "n,,n=" + self.user + ",r=" + self.randomString
}));
helper.tryCatch(function() {
self.connection.write(Buffer.concat([versionBuffer, authBuffer, NULL_BUFFER]));
}, function(err) {
// The TCP connection is open, but the ReQL connection wasn't established.
// We can just abort the whole thing
self.open = false;
reject(new Err.ReqlDriverError('Failed to perform handshake with '+self.host+':'+self.port).setOperational());
});
});
If you read this far - THANK YOU!
Both errors are about writing to a Buffer.
Is anyone aware of any related issues to nodejs's Buffer implementation on Windows 11?
Definitely not sure if this is THE answer, just spit-balling here that maybe you could make a custom Buffer.concat function to work in case it really is the nodejs Buffer.concat being the cause of the problem here ;-; hope it works I'm on windows 10 however
function BufferConcat(buffers){ //buffers is the array of buffers
var bytes=Buffer.byteLength, i=0
var length=buffers.reduce((b1,b2)=>bytes(b1)+bytes(b2))
const BufferToReturn=Buffer.alloc(length)
for(let buffer in buffers){
let values=Object.values(buffer)
for(let item of buffer){BufferToReturn[i++]=item}
}
return BufferToReturn
}

NodeJS : Error: read ECONNRESET at TCP.onStreamRead (internal/stream_base_commons.js:111:27)

Using Polling like below to check if the content of the file is changed then, other two functions are called
var poll_max_date=AsyncPolling(function (end,err) { if(err) {
console.error(err); } var stmp_node_id=fs.readFileSync(path.join(__dirname,'node_id'),"utf8");
console.log("--------loaded node : "+stmp_node_id);
if(druid_stmp_node_id!=stmp_node_id) {
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// // DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire();
druid_stmp_node_id=stmp_node_id; }
end(); }, 1800000).run();//30 mins
Its working fine for sometime, but then getting below error like after 4 - 5hours :
events.js:167
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27) Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
tried using fs.watch to monitor the changes in the file instead of polling like below :
let md5Previous = null; let fsWait = false;
fs.watch(dataSourceLogFile, (event, filename) => { if (filename) {
if (fsWait) return;
fsWait = setTimeout(() => {
fsWait = false;
}, 1000);
const md5Current = md5(fs.readFileSync(dataSourceLogFile));
if (md5Current === md5Previous) {
return;
}
md5Previous = md5Current;
console.log(`${filename} file Changed`);
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire(); } });
Its is also working fine for sometime, but then getting same error like after 4 - 5hours :
events.js:167 throw er; // Unhandled 'error' event ^
Error: read ECONNRESET at TCP.onStreamRead
(internal/stream_base_commons.js:111:27) Emitted 'error' event at: at
emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT
(internal/streams/destroy.js:50:3)
But when run in Local Machine, its working fine. the error occurs only when run in remote Linux Machine.
somebody can help me how I can fix that problem?
Use fs.watchFile once , because fs.watch is not consistent across platforms,
https://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener
Change your code according to the requirement.
It has been happening since the users are closing the browser before the data request is received, leading to Connection Reset.
Used PM2 (http://pm2.keymetrics.io/) to run the application, and it is working great now .

UDP multicast failing - NodeJS / Windows 10

I am beating my brains out trying to get this to work. I read all the other answers related to NodeJS UDP on SO already, but to no avail. I am on Windows 10.
Here is the error I am getting:
Uncaught Exception: Error: write ENOTSUP
at exports._errnoException (util.js:1022:11)
at ChildProcess.target._send (internal/child_process.js:654:20)
at ChildProcess.target.send (internal/child_process.js:538:19)
at sendHelper (cluster.js:751:15)
at send (cluster.js:534:12)
at cluster.js:509:7
at SharedHandle.add (cluster.js:99:3)
at queryServer (cluster.js:501:12)
at Worker.onmessage (cluster.js:450:7)
at ChildProcess.<anonymous> (cluster.js:765:8)
at emitTwo (events.js:111:20)
at ChildProcess.emit (events.js:191:7)
at process.nextTick (internal/child_process.js:744:12)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickDomainCallback [as _tickCallback] (internal/process/next_tick.js:122:9)
Here is my code:
let dgram = require('dgram'),
server = dgram.createSocket('udp4'),
multicastAddress = '239.255.255.250',
multicastPort = 1900,
myIp = '192.168.51.133';
server.bind(multicastPort, myIp, function () {
server.setBroadcast(true);
server.setMulticastTTL(128);
server.setInterface.getbyname(myIp);
server.addMembership(multicastAddress, myIp);
});
//wait for incoming messages and print ip address
server.on('message', function (data, rinfo) {
console.log(new Date() + ' RECEIVER received from ', rinfo.address, ':');
console.log(data.toString());
});
//Set up discovery message. Make sure to leave out any extra space in the message.
var discover_message = new Buffer('M-SEARCH * HTTP/1.1\r\nHost: 239.255.255.250:1900\r\nMan: ssdp:discover\r\nST: colortouch:ecp\r\n');
server.send(discover_message, 0, discover_message.length, 1900, multicastAddress);
Finally found an answer for this. The issue is due to being on Windows and using clusters in Node. The problem is on the server.bind call. Here is the correct, working code:
server.bind({port: 1900, exclusive: true}, function () {
console.log('PORT BIND SUCCESS');
server.setBroadcast(true);
server.setMulticastTTL(128);
server.addMembership(multicastAddress, myIp);
});
The fix was to pass in the object {port: 1900, exclusive: true}. Source: https://github.com/misterdjules/node/commit/1a87a95d3d7ccc67fd74145c6f6714186e56f571

Chunking stream into data chunks using Node.js

I am trying to chunk a file into data chunks. I found that link does the job beautifully but when I use the above library in the following manner:
var in = fs.createReadStream(__dirname+'/try.html'),
chunker = new SizeChunker({
chunkSize: 2048
}),
output;
chunker.on('chunkStart', function(id, done) {
output = fs.createWriteStream('./output-' + id);
console.log("Chunkstart!");
console.log("Input: "+in.length);
done();
});
chunker.on('chunkEnd', function(id, done) {
output.end();
console.log("Chunkend!");
done();
});
chunker.on('data', function(dat) {
console.log("Writing chunk to output!")
output.write(dat.chunk);
console.log(dat.chunk);
});
input.pipe(chunker);
But I am getting this error :
_stream_writable.js:201
var len = state.objectMode ? 1 : chunk.length;
^
TypeError: Cannot read property 'length' of undefined
at writeOrBuffer (_stream_writable.js:201:41)
at WriteStream.Writable.write (_stream_writable.js:180:11)
at SizeChunker.<anonymous> (/Users/admin/Documents/chunk.js:16:15)
at SizeChunker.EventEmitter.emit (events.js:95:17)
at SizeChunker.<anonymous> (_stream_readable.js:746:14)
at SizeChunker.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
at SizeChunker.Readable.push (_stream_readable.js:127:10)
Also, in.length is undefined when displayed using console.log(). Can anyone please help me resolve this issue? Thanks in advance.
When you listen for data on the chunker stream, the dat argument has no property chunk. You can read on the chunking-stream readme the following:
Each data chunk is an object with the following fields:
id: number of chunk (starts from 1) data: Buffer with data
You can do something like this instead:
chunker.on('data', function(dat) {
console.log("Writing chunk to output!")
output.write(dat.data);
console.log(dat);
});
Also, in is a stream and has no length property defined.

ForEachLine() in node.js

Referring to slide no 35 in ppt on slideshare
When I run this code
var server = my_http.createServer();
server.on("request", function(request,response){
var chunks = [];
output = fs.createWriteStream("./output");
request.on("data",function(chunk){
chunks = forEachLine(chunks.concat(chunk),function(line){
output.write(parseInt(line,10)*2);
output.write("\n");
})
});
request.on("end",function(){
response.writeHeader(200,{"Content-Type":"plain/text"})
response.end("OK\n");
output.end()
server.close()
})
});
server.listen("8080");
I get error as
chunks = forEachLine(chunks.concat(chunk),function(line){
^
ReferenceError: forEachLine is not defined
Of course I unserstand that I need to include some library but when I googled this I found nothing . Since I am complete newbie to this I have absolutely no idea how to resolve it.
Any suggestions will be appreciable.
EDIT
Using the suggested answer I am getting error as
events.js:72
throw er; // Unhandled 'error' event
^
TypeError: Invalid non-string/buffer chunk
at validChunk (_stream_writable.js:150:14)
at WriteStream.Writable.write (_stream_writable.js:179:12)
at /var/www/html/experimentation/nodejs/first.js:18:20
at Array.forEach (native)
at forEachLine (/var/www/html/experimentation/nodejs/first.js:8:60)
at IncomingMessage.<anonymous> (/var/www/html/experimentation/nodejs/first.js:17:18)
at IncomingMessage.EventEmitter.emit (events.js:95:17)
at IncomingMessage.<anonymous> (_stream_readable.js:736:14)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
Thanks
See proxy_stream.js
function forEachLine(chunks, callback) {
var buffer = chunks.join("")
buffer.substr(0, buffer.lastIndexOf("\n")).split("\n").forEach(callback)
return buffer.substr(buffer.lastIndexOf("\n") + 1).split("\n")
}
The link to the repo was on the first slide.
EDIT BY LET's CODE FOR ERROR MESSAGE
Came to know the actual issue now .
I was using nod v0.10 and it is buggy in getting the streams so I was getting the error. Downgraded to v0.8 and same code is working perfect .

Resources