GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — http: avoid toLowerCase on the server hot path by anonrig · Pull Request #66120 · nodejs/node

http: avoid toLowerCase on the server hot path #66120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
nodejs-github-bot merged 2 commits into nodejs:main from anonrig:cursor/http-perf-a3fb
Sep 25, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

http: avoid toLowerCase on the server hot path #66120

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit Hold shift + click to select a range
9b786ff
http: avoid toLowerCase on the server hot path
anonrig Sep 19, 2026
534f13d
http: do not intern arbitrary parser header names
anonrig Sep 19, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

50 changes: 44 additions & 6 deletions 50 lib/_http_incoming.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,15 @@ function IncomingMessage(socket) {
return deprecateInstantiation(IncomingMessage, 'DEP0195', socket);
}

let streamOptions;
Readable.call(this);

if (socket) {
streamOptions = {
highWaterMark: socket.readableHighWaterMark,
};
const hwm = socket.readableHighWaterMark;
if (this._readableState.highWaterMark !== hwm) {
this._readableState.highWaterMark = hwm;
}
}

Readable.call(this, streamOptions);

this._readableState.readingMore = true;

this.socket = socket;
Expand Down Expand Up @@ -530,6 +529,43 @@ IncomingMessage.prototype._dump = function _dump() {
}
};

// Case-insensitive ASCII compare against an already-lowercased name.
// Avoids allocating a lowercased copy of every header name.
function asciiEqualIgnoreCase(a, lower) {
const len = lower.length;
if (a.length !== len)
return false;
if (a === lower)
return true;
for (let i = 0; i < len; i++) {
let c = a.charCodeAt(i);
if (c >= 65 && c <= 90)
c += 32;
if (c !== lower.charCodeAt(i))
return false;
}
return true;
}

function getRawHeader(msg, lowerName, joinDuplicates) {
const rawHeaders = msg.rawHeaders;
const count = msg[kHeadersCount];
let result;
for (let i = 0; i < count; i += 2) {
if (!asciiEqualIgnoreCase(rawHeaders[i], lowerName))
continue;
const value = rawHeaders[i + 1];
if (result === undefined) {
result = value;
if (!joinDuplicates)
return result;
} else {
result += ', ' + value;
}
}
return result;
}

function onError(self, error, cb) {
// This is to keep backward compatible behavior.
// An error is emitted only if there are listeners attached to the event.
Expand All @@ -544,6 +580,8 @@ module.exports = {
IncomingMessage,
kDetachAbortSignal,
kHeadersCount,
asciiEqualIgnoreCase,
getRawHeader,
readStart,
readStop,
};
30 changes: 29 additions & 1 deletion 30 lib/_http_outgoing.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -659,10 +659,38 @@ function storeHeader(self, state, key, value, validate, lenient) {
matchHeader(self, state, key, value);
}

function lowerOutgoingHeaderName(field) {
switch (field) {
case 'Connection':
case 'connection':
return 'connection';
case 'Content-Length':
case 'content-length':
return 'content-length';
case 'Transfer-Encoding':
case 'transfer-encoding':
return 'transfer-encoding';
case 'Date':
case 'date':
return 'date';
case 'Expect':
case 'expect':
return 'expect';
case 'Trailer':
case 'trailer':
return 'trailer';
case 'Keep-Alive':
case 'keep-alive':
return 'keep-alive';
default:
return field.toLowerCase();
}
}

function matchHeader(self, state, field, value) {
if (field.length < 4 || field.length > 17)
return;
field = field.toLowerCase();
field = lowerOutgoingHeaderName(field);
switch (field) {
case 'connection':
state.connection = true;
Expand Down
52 changes: 29 additions & 23 deletions 52 lib/_http_server.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ const {
IncomingMessage,
kDetachAbortSignal,
kHeadersCount,
asciiEqualIgnoreCase,
getRawHeader,
} = require('_http_incoming');
const {
ConnResetException,
Expand Down Expand Up @@ -225,7 +227,8 @@ function ServerResponse(req, options) {
this._expect_continue = false;

if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) {
this.useChunkedEncodingByDefault = chunkExpression.test(req.headers.te);
this.useChunkedEncodingByDefault =
chunkExpression.test(getRawHeader(req, 'te', true));
this.shouldKeepAlive = false;
}

Expand Down Expand Up @@ -1289,10 +1292,8 @@ function hasRequestHeader(req, length, lowerName) {
const count = req[kHeadersCount];
for (let i = 0; i < count; i += 2) {
const key = rawHeaders[i];
if (key.length === length &&
(key === lowerName || key.toLowerCase() === lowerName)) {
if (key.length === length && asciiEqualIgnoreCase(key, lowerName))
return true;
}
}
return false;
}
Expand All @@ -1301,12 +1302,14 @@ function hasBodyHeaders(req) {
const rawHeaders = req.rawHeaders;
const count = req[kHeadersCount];
for (let i = 0; i < count; i += 2) {
const length = rawHeaders[i].length;
if (length === 14 || length === 17) {
const key = rawHeaders[i].toLowerCase();
if (key === 'content-length' || key === 'transfer-encoding') {
const key = rawHeaders[i];
const length = key.length;
if (length === 14) {
if (asciiEqualIgnoreCase(key, 'content-length'))
return true;
} else if (length === 17) {
if (asciiEqualIgnoreCase(key, 'transfer-encoding'))
return true;
}
}
}
return false;
Expand Down Expand Up @@ -1441,22 +1444,25 @@ function parserOnIncoming(server, socket, state, req, keepAlive) {
server.emit('dropRequest', req, socket);
res.writeHead(503);
res.end();
} else if (hasRequestHeader(req, 6, 'expect')) {
handled = true;

if (continueExpression.test(req.headers.expect)) {
res._expect_continue = true;
if (server.listenerCount('checkContinue') > 0) {
server.emit('checkContinue', req, res);
} else {
const expect = getRawHeader(req, 'expect', true);
if (expect !== undefined) {
handled = true;

if (continueExpression.test(expect)) {
res._expect_continue = true;
if (server.listenerCount('checkContinue') > 0) {
server.emit('checkContinue', req, res);
} else {
res.writeContinue();
server.emit('request', req, res);
}
} else if (server.listenerCount('checkExpectation') > 0) {
server.emit('checkExpectation', req, res);
} else {
res.writeContinue();
server.emit('request', req, res);
res.writeHead(417);
res.end();
}
} else if (server.listenerCount('checkExpectation') > 0) {
server.emit('checkExpectation', req, res);
} else {
res.writeHead(417);
res.end();
}
}
}
Expand Down
11 changes: 10 additions & 1 deletion 11 src/node_http_parser.cc
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,15 @@ struct StringPtr {
return String::Empty(env->isolate());
}

// Header names are short, repeated HTTP tokens. Interning them lets V8
// reuse one string per distinct name and makes JS identity comparisons
// in IncomingMessage.matchKnownFields cheaper.
Local<String> ToHeaderNameString(Environment* env) const {
if (size_ == 0) return String::Empty(env->isolate());
return OneByteString(
env->isolate(), str_, size_, v8::NewStringType::kInternalized);
}

Comment thread Outdated

@ronag ronag Sep 19, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Can't this cause a vulnerability? While header names are usually short and a limited set. An attacker could create lots of random fields over many requests causing a huge amount if internalized strings?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@ronag ronag Sep 19, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

@mcollina

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@anonrig anonrig Sep 19, 2026

Copy link
Copy Markdown
Member Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Yes. Unique attacker-controlled names would stay in V8's interned string table for the isolate lifetime.

Dropped it in 534f13d. Header names are ordinary strings again; the leftover is the JS rawHeaders scan / lazy Expect-TE path.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@jasnell jasnell Sep 22, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

FWIW, interned strings can be GC'd, just ... slowly. They can be reclaimed during major GC if nothing is using them.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
// Strip trailing OWS (SPC or HTAB) from string.
Local<String> ToTrimmedString(Environment* env) {
while (size_ > 0 && IsOWS(str_[size_ - 1])) {
Expand Down Expand Up @@ -940,7 +949,7 @@ class Parser : public AsyncWrap, public StreamListener {
Local<Value> headers_v[kMaxHeaderFieldsCount * 2];

for (size_t i = 0; i < num_values_; ++i) {
headers_v[i * 2] = fields_[i].ToString(env());
headers_v[i * 2] = fields_[i].ToHeaderNameString(env());
headers_v[i * 2 + 1] = values_[i].ToTrimmedString(env());
}

Expand Down
63 changes: 63 additions & 0 deletions 63 test/parallel/test-http-server-raw-header-lookup.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
'use strict';

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

const server = http.createServer({
optimizeEmptyRequests: true,
}, common.mustCall((req, res) => {
// Host / Expect lookups must not force materialization of req.headers.
// Accessing headers afterwards still works, including unusual casing.
assert.strictEqual(req.headers.host, 'example.test');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
}, 3));

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

function request(headers) {
return new Promise((resolve, reject) => {
const socket = net.connect(port, '127.0.0.1', () => {
socket.write(headers);
});
let data = '';
socket.setEncoding('utf8');
socket.on('data', (chunk) => { data += chunk; });
socket.on('end', () => resolve(data));
socket.on('error', reject);
});
}

(async () => {
// Mixed-case Host must satisfy requireHostHeader.
const mixedHost = await request(
'GET / HTTP/1.1\r\nHOST: example.test\r\nConnection: close\r\n\r\n',
);
assert.match(mixedHost, /^HTTP\/1\.1 200 /);

// Unusual Host casing.
const oddHost = await request(
'GET / HTTP/1.1\r\nhOsT: example.test\r\nConnection: close\r\n\r\n',
);
assert.match(oddHost, /^HTTP\/1\.1 200 /);

// Mixed-case Expect: 100-continue still triggers the continue path.
const expectContinue = await request(
'POST / HTTP/1.1\r\nHost: example.test\r\n' +
'EXPECT: 100-continue\r\nContent-Length: 0\r\nConnection: close\r\n\r\n',
);
assert.match(expectContinue, /^HTTP\/1\.1 100 Continue\r\n/);
assert.match(expectContinue, /HTTP\/1\.1 200 /);

// Missing Host is still rejected.
const missingHost = await request(
'GET / HTTP/1.1\r\nConnection: close\r\n\r\n',
);
assert.match(missingHost, /^HTTP\/1\.1 400 /);

server.close();
})().then(common.mustCall());
}));
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.