Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 80 additions & 33 deletions lib/_http_outgoing.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ let debug = require('internal/util/debuglog').debuglog('http', (fn) => {
});

const kCorked = Symbol('corked');
const kLenientValidation = Symbol('kLenientValidation');
const kSocket = Symbol('kSocket');
const kChunkedBuffer = Symbol('kChunkedBuffer');
const kChunkedLength = Symbol('kChunkedLength');
Expand Down Expand Up @@ -143,6 +144,7 @@ function OutgoingMessage(options) {
this[kChunkedBuffer] = [];
this[kChunkedLength] = 0;
this._closed = false;
this[kLenientValidation] = undefined;

this[kSocket] = null;
this._header = null;
Expand All @@ -163,28 +165,40 @@ ObjectSetPrototypeOf(OutgoingMessage, Stream);
// For ClientRequest: checks this.httpValidation or this.insecureHTTPParser
// For ServerResponse: checks the server's httpValidation or insecureHTTPParser
// Falls back to global --insecure-http-parser flag.
// The answer is invariant for the lifetime of the message (the options are
// fixed at construction time), but this runs on every setHeader/appendHeader
// call and once per stored header block, so the multi-step lookup chain is
// resolved once per message and cached.
OutgoingMessage.prototype._isLenientHeaderValidation = function() {
return (this[kLenientValidation] ??= lenientHeaderValidation(this));
};

function lenientHeaderValidation(msg) {
const {
httpValidation,
insecureHTTPParser,
} = msg;
// New httpValidation option takes priority (ClientRequest case)
if (this.httpValidation !== undefined) {
return this.httpValidation !== 'strict';
if (httpValidation !== undefined) {
return httpValidation !== 'strict';
}
// ServerResponse: check server's httpValidation option
const serverHttpValidation = this.req?.socket?.server?.httpValidation;
const serverHttpValidation = msg.req?.socket?.server?.httpValidation;
if (serverHttpValidation !== undefined) {
return serverHttpValidation !== 'strict';
}
// Legacy insecureHTTPParser - ClientRequest has it directly
if (typeof this.insecureHTTPParser === 'boolean') {
return this.insecureHTTPParser;
if (typeof insecureHTTPParser === 'boolean') {
return insecureHTTPParser;
}
// ServerResponse can access via req.socket.server
const serverOption = this.req?.socket?.server?.insecureHTTPParser;
const serverOption = msg.req?.socket?.server?.insecureHTTPParser;
if (typeof serverOption === 'boolean') {
return serverOption;
}
// Fall back to global option
return isLenient();
};
}

ObjectDefineProperty(OutgoingMessage.prototype, 'errored', {
__proto__: null,
Expand Down Expand Up @@ -315,11 +329,12 @@ OutgoingMessage.prototype.uncork = function uncork() {
callbacks.push(buf[n + 2]);
}
}
this._send(crlf_buf, null, callbacks.length ? (err) => {
for (const callback of callbacks) {
callback(err);
}
} : null);
// The runner is a shared top-level function so flushing a corked
// chunked buffer does not allocate a fresh closure environment per
// flush.
this._send(crlf_buf, null, callbacks?.length ?
runChunkCallbacks.bind(undefined, callbacks) :
null);

this[kChunkedBuffer].length = 0;
this[kChunkedLength] = 0;
Expand Down Expand Up @@ -381,14 +396,14 @@ OutgoingMessage.prototype._send = function _send(data, encoding, callback, byteL
// This is a shameful hack to get the headers and first body chunk onto
// the same packet. Future versions of Node are going to take care of
// this at a lower level and in a more general way.
if (!this._headerSent && this._header !== null) {
let header;
if (!this._headerSent && (header = this._header) !== null) {
// `this._header` can be null if OutgoingMessage is used without a proper Socket
// See: /test/parallel/test-http-outgoing-message-inheritance.js
if (typeof data === 'string' &&
(encoding === 'utf8' || encoding === 'latin1' || !encoding)) {
data = this._header + data;
data = header + data;
} else {
const header = this._header;
this.outputData.unshift({
data: header,
encoding: 'latin1',
Expand Down Expand Up @@ -454,17 +469,21 @@ function _storeHeader(firstLine, headers) {
processHeader(this, state, entry[0], entry[1], false, lenient);
}
} else if (ArrayIsArray(headers)) {
if (headers.length && ArrayIsArray(headers[0])) {
for (let i = 0; i < headers.length; i++) {
// The length is hoisted into a local because the engine cannot fold
// the reload across the processHeader calls; the array is never
// mutated while this loop runs.
const headersLength = headers.length;
if (headersLength && ArrayIsArray(headers[0])) {
for (let i = 0; i < headersLength; i++) {
const entry = headers[i];
processHeader(this, state, entry[0], entry[1], true, lenient);
}
} else {
if (headers.length % 2 !== 0) {
if (headersLength % 2 !== 0) {
throw new ERR_INVALID_ARG_VALUE('headers', headers);
}

for (let n = 0; n < headers.length; n += 2) {
for (let n = 0; n < headersLength; n += 2) {
processHeader(this, state, headers[n + 0], headers[n + 1], true, lenient);
}
}
Expand Down Expand Up @@ -515,11 +534,13 @@ function _storeHeader(firstLine, headers) {
header += 'Connection: close\r\n';
} else if (shouldSendKeepAlive) {
header += 'Connection: keep-alive\r\n';
if (this._keepAliveTimeout && this._defaultKeepAlive) {
const timeoutSeconds = MathFloor(this._keepAliveTimeout / 1000);
const keepAliveTimeout = this._keepAliveTimeout;
if (keepAliveTimeout && this._defaultKeepAlive) {
const timeoutSeconds = MathFloor(keepAliveTimeout / 1000);
const maxRequestsPerSocket = this._maxRequestsPerSocket;
let max = '';
if (~~this._maxRequestsPerSocket > 0) {
max = `, max=${this._maxRequestsPerSocket}`;
if (~~maxRequestsPerSocket > 0) {
max = `, max=${maxRequestsPerSocket}`;
}
header += `Keep-Alive: timeout=${timeoutSeconds}${max}\r\n`;
}
Expand All @@ -529,6 +550,7 @@ function _storeHeader(firstLine, headers) {
}
}

let contentLength;
if (!state.contLen && !state.te) {
if (!this._hasBody) {
// Make sure we don't end the 0\r\n\r\n at the end of the message.
Expand All @@ -537,8 +559,8 @@ function _storeHeader(firstLine, headers) {
this._last = true;
} else if (!state.trailer &&
!this._removedContLen &&
typeof this._contentLength === 'number') {
header += 'Content-Length: ' + this._contentLength + '\r\n';
typeof (contentLength = this._contentLength) === 'number') {
header += 'Content-Length: ' + contentLength + '\r\n';
} else if (!this._removedTE) {
header += 'Transfer-Encoding: chunked\r\n';
this.chunkedEncoding = true;
Expand Down Expand Up @@ -590,13 +612,14 @@ function processHeader(self, state, key, value, validate, lenient) {
}

if (ArrayIsArray(value)) {
const valueLength = value.length;
if (
(value.length < 2 || !isCookieField(key)) &&
(valueLength < 2 || !isCookieField(key)) &&
(!self[kUniqueHeaders] || !self[kUniqueHeaders].has(key.toLowerCase()))
) {
// Retain for(;;) loop for performance reasons
// Refs: https://github.com/nodejs/node/pull/30958
for (let i = 0; i < value.length; i++)
for (let i = 0; i < valueLength; i++)
storeHeader(self, state, key, value[i], validate, lenient);
return;
}
Expand All @@ -613,8 +636,23 @@ function storeHeader(self, state, key, value, validate, lenient) {
}

function matchHeader(self, state, field, value) {
if (field.length < 4 || field.length > 17)
return;
const len = field.length;
// Cheap (length, first character) pre-filter so the common case, a
// header that is not one of the eight known fields below, returns
// without paying the per-header toLowerCase() allocation. The filter
// only rejects names that cannot possibly match the switch: `| 0x20`
// lower-cases ASCII letters and maps no other token character onto a
// letter, and every known field length is enumerated.
const c = field.charCodeAt(0) | 0x20;
switch (len) {
case 4: if (c !== 0x64) return; break; // Date
case 6: if (c !== 0x65) return; break; // Expect
case 7: if (c !== 0x74) return; break; // Trailer
case 10: if (c !== 0x63 && c !== 0x6b) return; break; // Connection, Keep-Alive
case 14: if (c !== 0x63) return; break; // Content-Length
case 17: if (c !== 0x74) return; break; // Transfer-Encoding
default: return; // No known field has this length
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not blocking but I doubt this is going to save much. There's also an inherent risk of false positives (e.g. that first clause also matches any other 4-letter string that starts with d). My fear is that this is straining into unnecessary micro-optimization territory.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On false positives: they're safe by design — a 4-letter d-starting name that isn't date passes the pre-filter and then falls through the toLowerCase()+switch exactly as before; the filter only skips work for names that provably cannot match, it never misclassifies (test-http-outgoing-known-header-casing.js locks exactly this: Dote/Xonnection etc. are emitted verbatim, odd-cased known fields still recognized).

On whether it saves much: this line is what carries most of the PR's measured effect. Without it, the hoists alone were inside the noise (+0.9%, n.s.); with it, the mechanism benchmarks (fresh process per sample, 30 interleaved samples per binary, Welch t-test, re-confirmed against a clean rebuilt baseline on an idle machine) show flushHeaders with five headers +10.8% (p=1.5e-25) and a 24-custom-header response +6.0% (p=5.1e-12) — the per-header lowercase allocation dominates _storeHeader for responses with ordinary X-*/custom headers, which never match the switch. Happy to drop it if you feel the extra branching isn't worth it, but the data says it's the payload of this PR rather than the garnish.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not worried about safety. Raw performance isn't the only goal. Keeping code easily readable, maintainable, etc is also important. Running a local artificial benchmark here, the impact is noticeable in isolation but shows zero statistically relevant impact in any of the http benchmarks.

I suspect caching the lenient header validation is likely a more meaningful change.

Not blocking, but I'm not convinced the additional complexity is actually worthwhile.

field = field.toLowerCase();
switch (field) {
case 'connection':
Expand Down Expand Up @@ -997,9 +1035,12 @@ function write_(msg, chunk, encoding, callback, fromEnd) {
}
}

if (!fromEnd && msg.socket && !msg.socket.writableCorked) {
msg.socket.cork();
process.nextTick(connectionCorkNT, msg.socket);
// `socket` is an accessor on the prototype: load it once instead of
// paying the getter three times on every body write.
let socket;
if (!fromEnd && (socket = msg.socket) && !socket.writableCorked) {
socket.cork();
process.nextTick(connectionCorkNT, socket);
}

let ret;
Expand Down Expand Up @@ -1028,6 +1069,12 @@ function connectionCorkNT(conn) {
conn.uncork();
}

function runChunkCallbacks(callbacks, err) {
for (let i = 0; i < callbacks.length; i++) {
callbacks[i](err);
}
}

OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
if (this.finished) {
throw new ERR_HTTP_HEADERS_SENT('set trailing');
Expand All @@ -1036,6 +1083,7 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
this._trailer = '';
const keys = ObjectKeys(headers);
const isArray = ArrayIsArray(headers);
const lenient = this._isLenientHeaderValidation();
// Retain for(;;) loop for performance reasons
// Refs: https://github.com/nodejs/node/pull/30958
for (let i = 0, l = keys.length; i < l; i++) {
Expand All @@ -1052,7 +1100,6 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {

// Check if the field must be sent several times
const isArrayValue = ArrayIsArray(value);
const lenient = this._isLenientHeaderValidation();
if (
isArrayValue && value.length > 1 &&
(!this[kUniqueHeaders] || !this[kUniqueHeaders].has(field.toLowerCase()))
Expand Down
65 changes: 65 additions & 0 deletions test/parallel/test-http-outgoing-known-header-casing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
'use strict';

const common = require('../common');
const assert = require('assert');
const http = require('http');

// The outgoing-header known-field matcher short-circuits on
// (length, first character) before lower-casing the name. Verify that
// known connection-relevant headers are still recognized in any casing,
// and that unknown headers sharing a known field's length and first
// letter are still sent through untouched.

const server = http.createServer(common.mustCall((req, res) => {
switch (req.url) {
case '/upper':
// Must be recognized: response uses identity framing, no chunking.
res.writeHead(200, {
'CONTENT-LENGTH': '2',
'CoNnEcTiOn': 'close',
});
res.end('ok');
break;
case '/nearmiss':
// Same length/first letter as known fields ('date', 'connection',
// 'content-length', 'transfer-encoding') but NOT known: they must
// be emitted verbatim and must not affect framing decisions.
res.writeHead(200, {
'Dote': 'x', // Len 4, 'd' (like date)
'Xonnection': 'y', // Len 10, wrong first char
'Continues-Len': 'z', // Len 13, no known field
'Content-Lengthy': 'w', // Len 15, no known field
'Transfer-Encoders': 'v', // Len 17 minus... 18: unknown
});
res.end('hi');
break;
default:
res.writeHead(404);
res.end();
}
}, 2));

server.listen(0, common.mustCall(() => {
const port = server.address().port;

http.get({ port, path: '/upper' }, common.mustCall((res) => {
// Content-Length was recognized despite the casing: no chunking.
assert.strictEqual(res.headers['content-length'], '2');
assert.strictEqual(res.headers['transfer-encoding'], undefined);
assert.strictEqual(res.headers.connection, 'close');
res.resume();
res.on('end', common.mustCall(() => {
http.get({ port, path: '/nearmiss' }, common.mustCall((res2) => {
assert.strictEqual(res2.headers.dote, 'x');
assert.strictEqual(res2.headers.xonnection, 'y');
assert.strictEqual(res2.headers['continues-len'], 'z');
assert.strictEqual(res2.headers['content-lengthy'], 'w');
assert.strictEqual(res2.headers['transfer-encoders'], 'v');
// None of them are Content-Length/TE: chunked framing applies.
assert.strictEqual(res2.headers['transfer-encoding'], 'chunked');
res2.resume();
res2.on('end', common.mustCall(() => server.close()));
}));
}));
}));
}));
Loading