From a7130245796dc6a422063af2b0b55ca1120a9dc9 Mon Sep 17 00:00:00 2001
From: Trevor Norris <trev.norris@gmail.com>
Date: Fri, 9 Oct 2015 16:51:42 -0600
Subject: [PATCH] net: don't throw on bytesWritten access

If bytesWritten is accessed before the object has been properly
constructed then return undefined.

Fixes: https://github.com/nodejs/node/issues/3298
PR-URL: https://github.com/nodejs/node/pull/3305
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
---
 lib/net.js                                    |  3 +++
 test/parallel/test-net-access-byteswritten.js | 16 ++++++++++++++++
 2 files changed, 19 insertions(+)
 create mode 100644 test/parallel/test-net-access-byteswritten.js

diff --git a/lib/net.js b/lib/net.js
index 47422c30dbbea1..a7a8eb1fcc21a7 100644
--- a/lib/net.js
+++ b/lib/net.js
@@ -727,6 +727,9 @@ Socket.prototype.__defineGetter__('bytesWritten', function() {
       data = this._pendingData,
       encoding = this._pendingEncoding;
 
+  if (!state)
+    return undefined;
+
   state.getBuffer().forEach(function(el) {
     if (el.chunk instanceof Buffer)
       bytes += el.chunk.length;
diff --git a/test/parallel/test-net-access-byteswritten.js b/test/parallel/test-net-access-byteswritten.js
new file mode 100644
index 00000000000000..362d533bbb87c1
--- /dev/null
+++ b/test/parallel/test-net-access-byteswritten.js
@@ -0,0 +1,16 @@
+'use strict';
+
+require('../common');
+const assert = require('assert');
+const net = require('net');
+const tls = require('tls');
+const tty = require('tty');
+
+// Check that the bytesWritten getter doesn't crash if object isn't
+// constructed.
+assert.strictEqual(net.Socket.prototype.bytesWritten, undefined);
+assert.strictEqual(tls.TLSSocket.super_.prototype.bytesWritten, undefined);
+assert.strictEqual(tls.TLSSocket.prototype.bytesWritten, undefined);
+assert.strictEqual(tty.ReadStream.super_.prototype.bytesWritten, undefined);
+assert.strictEqual(tty.ReadStream.prototype.bytesWritten, undefined);
+assert.strictEqual(tty.WriteStream.prototype.bytesWritten, undefined);