diff --git a/lib/dgram.js b/lib/dgram.js index 931d9a49544dcc..e31333e33e3b5c 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -42,6 +42,7 @@ const { guessHandleType } = internalBinding('util'); const { ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, + ERR_OUT_OF_RANGE, ERR_SOCKET_ALREADY_BOUND, ERR_SOCKET_BAD_BUFFER_SIZE, ERR_SOCKET_BUFFER_SIZE, @@ -476,6 +477,18 @@ Socket.prototype.sendto = function(buffer, function sliceBuffer(buffer, offset, length) { if (typeof buffer === 'string') { buffer = Buffer.from(buffer); + offset = offset >>> 0; + length = length >>> 0; + + if (offset > buffer.byteLength) { + throw new ERR_OUT_OF_RANGE('offset', `<= ${buffer.byteLength}`, offset); + } + + if (offset + length > buffer.byteLength) { + throw new ERR_OUT_OF_RANGE('length', + `<= ${buffer.byteLength - offset}`, length); + } + } else if (!isArrayBufferView(buffer)) { throw new ERR_INVALID_ARG_TYPE('buffer', ['Buffer', diff --git a/test/parallel/test-dgram-send-bad-arguments.js b/test/parallel/test-dgram-send-bad-arguments.js index 3e42f31b1af4b6..9563c0ceb0ab73 100644 --- a/test/parallel/test-dgram-send-bad-arguments.js +++ b/test/parallel/test-dgram-send-bad-arguments.js @@ -77,6 +77,36 @@ function checkArgs(connected) { message: 'Already connected' } ); + + assert.throws( + () => { sock.send('hello', 6, 0); }, + { + code: 'ERR_OUT_OF_RANGE', + name: 'RangeError', + message: 'The value of "offset" is out of range. ' + + 'It must be <= 5. Received 6' + } + ); + + assert.throws( + () => { sock.send('hello', 0, 6); }, + { + code: 'ERR_OUT_OF_RANGE', + name: 'RangeError', + message: 'The value of "length" is out of range. ' + + 'It must be <= 5. Received 6' + } + ); + + assert.throws( + () => { sock.send('hello', 3, 4); }, + { + code: 'ERR_OUT_OF_RANGE', + name: 'RangeError', + message: 'The value of "length" is out of range. ' + + 'It must be <= 2. Received 4' + } + ); } else { assert.throws(() => { sock.send(buf, 1, 1, -1, host); }, RangeError); assert.throws(() => { sock.send(buf, 1, 1, 0, host); }, RangeError);