fs: guarantee order of callbacks in ws.close

Refactor WriteStream.prototype.close and WriteStream.prototype._destroy
to always call the callback passed to close in order. Protects from
calling .close() without a callback.

Fixes: https://github.com/nodejs/node/issues/17951
See: https://github.com/nodejs/node/pull/15407

PR-URL: https://github.com/nodejs/node/pull/18002
Fixes: https://github.com/nodejs/node/issues/17951
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Matteo Collina authored and Myles Borins committed 2018-01-10 01:42:24 -05:00
1 parent 0e116a01c8
commit f1485565ef
4 files changed
+77 -27

No files matched your search

+19 -19
View File
@@ -2002,6 +2002,7 @@ function ReadStream(path, options) {
this.autoClose = options.autoClose === undefined ? true : options.autoClose;
this.pos = undefined;
this.bytesRead = 0;
this.closed = false;
if (this.start !== undefined) {
if (typeof this.start !== 'number') {
@@ -2115,20 +2116,12 @@ ReadStream.prototype._read = function(n) {
};
ReadStream.prototype._destroy = function(err, cb) {
if (this.closed || typeof this.fd !== 'number') {
if (typeof this.fd !== 'number') {
this.once('open', closeFsStream.bind(null, this, cb, err));
return;
}
return process.nextTick(() => {
cb(err);
this.emit('close');
});
const isOpen = typeof this.fd !== 'number';
if (isOpen) {
this.once('open', closeFsStream.bind(null, this, cb, err));
return;
}
this.closed = true;
closeFsStream(this, cb);
this.fd = null;
};
@@ -2137,6 +2130,7 @@ function closeFsStream(stream, cb, err) {
fs.close(stream.fd, (er) => {
er = er || err;
cb(er);
stream.closed = true;
if (!er)
stream.emit('close');
});
@@ -2169,6 +2163,7 @@ function WriteStream(path, options) {
this.autoClose = options.autoClose === undefined ? true : !!options.autoClose;
this.pos = undefined;
this.bytesWritten = 0;
this.closed = false;
if (this.start !== undefined) {
if (typeof this.start !== 'number') {
@@ -2294,19 +2289,24 @@ WriteStream.prototype._writev = function(data, cb) {
WriteStream.prototype._destroy = ReadStream.prototype._destroy;
WriteStream.prototype.close = function(cb) {
if (this._writableState.ending) {
this.on('close', cb);
return;
if (cb) {
if (this.closed) {
process.nextTick(cb);
return;
} else {
this.on('close', cb);
}
}
if (this._writableState.ended) {
process.nextTick(cb);
return;
// If we are not autoClosing, we should call
// destroy on 'finish'.
if (!this.autoClose) {
this.on('finish', this.destroy.bind(this));
}
// we use end() instead of destroy() because of
// https://github.com/nodejs/node/issues/2006
this.end(cb);
this.end();
};
// There is no shutdown() for files.