Skip to content

Commit 9ad7a9a

Browse files
jasnellMylesBorins
authored andcommitted
http2: add altsvc support
Add support for sending and receiving ALTSVC frames. Backport-PR-URL: #18050 PR-URL: #17917 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent e7a727e commit 9ad7a9a

File tree

8 files changed

+380
-0
lines changed

8 files changed

+380
-0
lines changed

doc/api/errors.md

+10
Original file line numberDiff line numberDiff line change
@@ -763,6 +763,16 @@ that.
763763

764764
Occurs with multiple attempts to shutdown an HTTP/2 session.
765765

766+
<a id="ERR_HTTP2_ALTSVC_INVALID_ORIGIN"></a>
767+
### ERR_HTTP2_ALTSVC_INVALID_ORIGIN
768+
769+
HTTP/2 ALTSVC frames require a valid origin.
770+
771+
<a id="ERR_HTTP2_ALTSVC_LENGTH"></a>
772+
### ERR_HTTP2_ALTSVC_LENGTH
773+
774+
HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.
775+
766776
<a id="ERR_HTTP2_CONNECT_AUTHORITY"></a>
767777
### ERR_HTTP2_CONNECT_AUTHORITY
768778

doc/api/http2.md

+94
Original file line numberDiff line numberDiff line change
@@ -558,11 +558,103 @@ added: REPLACEME
558558
Calls [`unref()`][`net.Socket.prototype.unref`] on this `Http2Session`
559559
instance's underlying [`net.Socket`].
560560

561+
### Class: ServerHttp2Session
562+
<!-- YAML
563+
added: v8.4.0
564+
-->
565+
566+
#### serverhttp2session.altsvc(alt, originOrStream)
567+
<!-- YAML
568+
added: REPLACEME
569+
-->
570+
571+
* `alt` {string} A description of the alternative service configuration as
572+
defined by [RFC 7838][].
573+
* `originOrStream` {number|string|URL|Object} Either a URL string specifying
574+
the origin (or an Object with an `origin` property) or the numeric identifier
575+
of an active `Http2Stream` as given by the `http2stream.id` property.
576+
577+
Submits an `ALTSVC` frame (as defined by [RFC 7838][]) to the connected client.
578+
579+
```js
580+
const http2 = require('http2');
581+
582+
const server = http2.createServer();
583+
server.on('session', (session) => {
584+
// Set altsvc for origin https://example.org:80
585+
session.altsvc('h2=":8000"', 'https://example.org:80');
586+
});
587+
588+
server.on('stream', (stream) => {
589+
// Set altsvc for a specific stream
590+
stream.session.altsvc('h2=":8000"', stream.id);
591+
});
592+
```
593+
594+
Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate
595+
service is associated with the origin of the given `Http2Stream`.
596+
597+
The `alt` and origin string *must* contain only ASCII bytes and are
598+
strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`
599+
may be passed to clear any previously set alternative service for a given
600+
domain.
601+
602+
When a string is passed for the `originOrStream` argument, it will be parsed as
603+
a URL and the origin will be derived. For insetance, the origin for the
604+
HTTP URL `'https://example.org/foo/bar'` is the ASCII string
605+
`'https://example.org'`. An error will be thrown if either the given string
606+
cannot be parsed as a URL or if a valid origin cannot be derived.
607+
608+
A `URL` object, or any object with an `origin` property, may be passed as
609+
`originOrStream`, in which case the value of the `origin` property will be
610+
used. The value of the `origin` property *must* be a properly serialized
611+
ASCII origin.
612+
613+
#### Specifying alternative services
614+
615+
The format of the `alt` parameter is strictly defined by [RFC 7838][] as an
616+
ASCII string containing a comma-delimited list of "alternative" protocols
617+
associated with a specific host and port.
618+
619+
For example, the value `'h2="example.org:81"'` indicates that the HTTP/2
620+
protocol is available on the host `'example.org'` on TCP/IP port 81. The
621+
host and port *must* be contained within the quote (`"`) characters.
622+
623+
Multiple alternatives may be specified, for instance: `'h2="example.org:81",
624+
h2=":82"'`
625+
626+
The protocol identifier (`'h2'` in the examples) may be any valid
627+
[ALPN Protocol ID][].
628+
629+
The syntax of these values is not validated by the Node.js implementation and
630+
are passed through as provided by the user or received from the peer.
631+
561632
### Class: ClientHttp2Session
562633
<!-- YAML
563634
added: v8.4.0
564635
-->
565636

637+
#### Event: 'altsvc'
638+
<!-- YAML
639+
added: REPLACEME
640+
-->
641+
642+
The `'altsvc'` event is emitted whenever an `ALTSVC` frame is received by
643+
the client. The event is emitted with the `ALTSVC` value, origin, and stream
644+
ID, if any. If no `origin` is provided in the `ALTSVC` frame, `origin` will
645+
be an empty string.
646+
647+
```js
648+
const http2 = require('http2');
649+
const client = http2.connect('https://example.org');
650+
651+
client.on('altsvc', (alt, origin, stream) => {
652+
console.log(alt);
653+
console.log(origin);
654+
console.log(stream);
655+
});
656+
```
657+
566658
#### clienthttp2session.request(headers[, options])
567659
<!-- YAML
568660
added: v8.4.0
@@ -2850,6 +2942,7 @@ following additional properties:
28502942

28512943

28522944
[ALPN negotiation]: #http2_alpn_negotiation
2945+
[ALPN Protocol ID]: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids
28532946
[Compatibility API]: #http2_compatibility_api
28542947
[HTTP/1]: http.html
28552948
[HTTP/2]: https://tools.ietf.org/html/rfc7540
@@ -2858,6 +2951,7 @@ following additional properties:
28582951
[Http2Session and Sockets]: #http2_http2session_and_sockets
28592952
[Performance Observer]: perf_hooks.html
28602953
[Readable Stream]: stream.html#stream_class_stream_readable
2954+
[RFC 7838]: https://tools.ietf.org/html/rfc7838
28612955
[Settings Object]: #http2_settings_object
28622956
[Using options.selectPadding]: #http2_using_options_selectpadding
28632957
[Writable Stream]: stream.html#stream_writable_streams

lib/internal/errors.js

+4
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,10 @@ E('ERR_ENCODING_NOT_SUPPORTED', 'The "%s" encoding is not supported');
184184
E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value');
185185
E('ERR_HTTP2_ALREADY_SHUTDOWN',
186186
'Http2Session is already shutdown or destroyed');
187+
E('ERR_HTTP2_ALTSVC_INVALID_ORIGIN',
188+
'HTTP/2 ALTSVC frames require a valid origin');
189+
E('ERR_HTTP2_ALTSVC_LENGTH',
190+
'HTTP/2 ALTSVC frames are limited to 16382 bytes');
187191
E('ERR_HTTP2_CONNECT_AUTHORITY',
188192
':authority header is required for CONNECT requests');
189193
E('ERR_HTTP2_CONNECT_PATH',

lib/internal/http2/core.js

+62
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ const kMaxFrameSize = (2 ** 24) - 1;
3232
const kMaxInt = (2 ** 32) - 1;
3333
const kMaxStreams = (2 ** 31) - 1;
3434

35+
// eslint-disable-next-line no-control-regex
36+
const kQuotedString = /^[\x09\x20-\x5b\x5d-\x7e\x80-\xff]*$/;
37+
3538
const {
3639
assertIsObject,
3740
assertValidPseudoHeaderResponse,
@@ -362,6 +365,16 @@ function onFrameError(id, type, code) {
362365
process.nextTick(emit, emitter, 'frameError', type, code, id);
363366
}
364367

368+
function onAltSvc(stream, origin, alt) {
369+
const session = this[kOwner];
370+
if (session.destroyed)
371+
return;
372+
debug(`Http2Session ${sessionName(session[kType])}: altsvc received: ` +
373+
`stream: ${stream}, origin: ${origin}, alt: ${alt}`);
374+
session[kUpdateTimer]();
375+
process.nextTick(emit, session, 'altsvc', alt, origin, stream);
376+
}
377+
365378
// Receiving a GOAWAY frame from the connected peer is a signal that no
366379
// new streams should be created. If the code === NGHTTP2_NO_ERROR, we
367380
// are going to send our close, but allow existing frames to close
@@ -704,6 +717,7 @@ function setupHandle(socket, type, options) {
704717
handle.onheaders = onSessionHeaders;
705718
handle.onframeerror = onFrameError;
706719
handle.ongoawaydata = onGoawayData;
720+
handle.onaltsvc = onAltSvc;
707721

708722
if (typeof options.selectPadding === 'function')
709723
handle.ongetpadding = onSelectPadding(options.selectPadding);
@@ -1150,6 +1164,54 @@ class ServerHttp2Session extends Http2Session {
11501164
get server() {
11511165
return this[kServer];
11521166
}
1167+
1168+
// Submits an altsvc frame to be sent to the client. `stream` is a
1169+
// numeric Stream ID. origin is a URL string that will be used to get
1170+
// the origin. alt is a string containing the altsvc details. No fancy
1171+
// API is provided for that.
1172+
altsvc(alt, originOrStream) {
1173+
if (this.destroyed)
1174+
throw new errors.Error('ERR_HTTP2_INVALID_SESSION');
1175+
1176+
let stream = 0;
1177+
let origin;
1178+
1179+
if (typeof originOrStream === 'string') {
1180+
origin = (new URL(originOrStream)).origin;
1181+
if (origin === 'null')
1182+
throw new errors.TypeError('ERR_HTTP2_ALTSVC_INVALID_ORIGIN');
1183+
} else if (typeof originOrStream === 'number') {
1184+
if (originOrStream >>> 0 !== originOrStream || originOrStream === 0)
1185+
throw new errors.RangeError('ERR_OUT_OF_RANGE', 'originOrStream');
1186+
stream = originOrStream;
1187+
} else if (originOrStream !== undefined) {
1188+
// Allow origin to be passed a URL or object with origin property
1189+
if (originOrStream !== null && typeof originOrStream === 'object')
1190+
origin = originOrStream.origin;
1191+
// Note: if originOrStream is an object with an origin property other
1192+
// than a URL, then it is possible that origin will be malformed.
1193+
// We do not verify that here. Users who go that route need to
1194+
// ensure they are doing the right thing or the payload data will
1195+
// be invalid.
1196+
if (typeof origin !== 'string') {
1197+
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'originOrStream',
1198+
['string', 'number', 'URL', 'object']);
1199+
} else if (origin === 'null' || origin.length === 0) {
1200+
throw new errors.TypeError('ERR_HTTP2_ALTSVC_INVALID_ORIGIN');
1201+
}
1202+
}
1203+
1204+
if (typeof alt !== 'string')
1205+
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'alt', 'string');
1206+
if (!kQuotedString.test(alt))
1207+
throw new errors.TypeError('ERR_INVALID_CHAR', 'alt');
1208+
1209+
// Max length permitted for ALTSVC
1210+
if ((alt.length + (origin !== undefined ? origin.length : 0)) > 16382)
1211+
throw new errors.TypeError('ERR_HTTP2_ALTSVC_LENGTH');
1212+
1213+
this[kHandle].altsvc(stream, origin || '', alt);
1214+
}
11531215
}
11541216

11551217
// ClientHttp2Session instances have to wait for the socket to connect after

src/env.h

+1
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@ class ModuleWrap;
180180
V(netmask_string, "netmask") \
181181
V(nsname_string, "nsname") \
182182
V(ocsp_request_string, "OCSPRequest") \
183+
V(onaltsvc_string, "onaltsvc") \
183184
V(onchange_string, "onchange") \
184185
V(onclienthello_string, "onclienthello") \
185186
V(oncomplete_string, "oncomplete") \

src/node_http2.cc

+76
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,11 @@ Http2Options::Http2Options(Environment* env) {
103103
// are required to buffer.
104104
nghttp2_option_set_no_auto_window_update(options_, 1);
105105

106+
// Enable built in support for ALTSVC frames. Once we add support for
107+
// other non-built in extension frames, this will need to be handled
108+
// a bit differently. For now, let's let nghttp2 take care of it.
109+
nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ALTSVC);
110+
106111
AliasedBuffer<uint32_t, v8::Uint32Array>& buffer =
107112
env->http2_state()->options_buffer;
108113
uint32_t flags = buffer[IDX_OPTIONS_FLAGS];
@@ -847,6 +852,10 @@ inline int Http2Session::OnFrameReceive(nghttp2_session* handle,
847852
break;
848853
case NGHTTP2_PING:
849854
session->HandlePingFrame(frame);
855+
break;
856+
case NGHTTP2_ALTSVC:
857+
session->HandleAltSvcFrame(frame);
858+
break;
850859
default:
851860
break;
852861
}
@@ -1185,6 +1194,34 @@ inline void Http2Session::HandleGoawayFrame(const nghttp2_frame* frame) {
11851194
MakeCallback(env()->ongoawaydata_string(), arraysize(argv), argv);
11861195
}
11871196

1197+
// Called by OnFrameReceived when a complete ALTSVC frame has been received.
1198+
inline void Http2Session::HandleAltSvcFrame(const nghttp2_frame* frame) {
1199+
Isolate* isolate = env()->isolate();
1200+
HandleScope scope(isolate);
1201+
Local<Context> context = env()->context();
1202+
Context::Scope context_scope(context);
1203+
1204+
int32_t id = GetFrameID(frame);
1205+
1206+
nghttp2_extension ext = frame->ext;
1207+
nghttp2_ext_altsvc* altsvc = static_cast<nghttp2_ext_altsvc*>(ext.payload);
1208+
DEBUG_HTTP2SESSION(this, "handling altsvc frame");
1209+
1210+
Local<Value> argv[3] = {
1211+
Integer::New(isolate, id),
1212+
String::NewFromOneByte(isolate,
1213+
altsvc->origin,
1214+
v8::NewStringType::kNormal,
1215+
altsvc->origin_len).ToLocalChecked(),
1216+
String::NewFromOneByte(isolate,
1217+
altsvc->field_value,
1218+
v8::NewStringType::kNormal,
1219+
altsvc->field_value_len).ToLocalChecked(),
1220+
};
1221+
1222+
MakeCallback(env()->onaltsvc_string(), arraysize(argv), argv);
1223+
}
1224+
11881225
// Called by OnFrameReceived when a complete PING frame has been received.
11891226
inline void Http2Session::HandlePingFrame(const nghttp2_frame* frame) {
11901227
bool ack = frame->hd.flags & NGHTTP2_FLAG_ACK;
@@ -2494,6 +2531,44 @@ void Http2Stream::RefreshState(const FunctionCallbackInfo<Value>& args) {
24942531
}
24952532
}
24962533

2534+
void Http2Session::AltSvc(int32_t id,
2535+
uint8_t* origin,
2536+
size_t origin_len,
2537+
uint8_t* value,
2538+
size_t value_len) {
2539+
Http2Scope h2scope(this);
2540+
CHECK_EQ(nghttp2_submit_altsvc(session_, NGHTTP2_FLAG_NONE, id,
2541+
origin, origin_len, value, value_len), 0);
2542+
}
2543+
2544+
// Submits an AltSvc frame to the sent to the connected peer.
2545+
void Http2Session::AltSvc(const FunctionCallbackInfo<Value>& args) {
2546+
Environment* env = Environment::GetCurrent(args);
2547+
Http2Session* session;
2548+
ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder());
2549+
2550+
int32_t id = args[0]->Int32Value(env->context()).ToChecked();
2551+
2552+
// origin and value are both required to be ASCII, handle them as such.
2553+
Local<String> origin_str = args[1]->ToString(env->context()).ToLocalChecked();
2554+
Local<String> value_str = args[2]->ToString(env->context()).ToLocalChecked();
2555+
2556+
size_t origin_len = origin_str->Length();
2557+
size_t value_len = value_str->Length();
2558+
2559+
CHECK_LE(origin_len + value_len, 16382); // Max permitted for ALTSVC
2560+
// Verify that origin len != 0 if stream id == 0, or
2561+
// that origin len == 0 if stream id != 0
2562+
CHECK((origin_len != 0 && id == 0) || (origin_len == 0 && id != 0));
2563+
2564+
MaybeStackBuffer<uint8_t> origin(origin_len);
2565+
MaybeStackBuffer<uint8_t> value(value_len);
2566+
origin_str->WriteOneByte(*origin);
2567+
value_str->WriteOneByte(*value);
2568+
2569+
session->AltSvc(id, *origin, origin_len, *value, value_len);
2570+
}
2571+
24972572
// Submits a PING frame to be sent to the connected peer.
24982573
void Http2Session::Ping(const FunctionCallbackInfo<Value>& args) {
24992574
Environment* env = Environment::GetCurrent(args);
@@ -2711,6 +2786,7 @@ void Initialize(Local<Object> target,
27112786
session->SetClassName(http2SessionClassName);
27122787
session->InstanceTemplate()->SetInternalFieldCount(1);
27132788
AsyncWrap::AddWrapMethods(env, session);
2789+
env->SetProtoMethod(session, "altsvc", Http2Session::AltSvc);
27142790
env->SetProtoMethod(session, "ping", Http2Session::Ping);
27152791
env->SetProtoMethod(session, "consume", Http2Session::Consume);
27162792
env->SetProtoMethod(session, "destroy", Http2Session::Destroy);

src/node_http2.h

+7
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,11 @@ class Http2Session : public AsyncWrap {
800800
void Consume(Local<External> external);
801801
void Unconsume();
802802
void Goaway(uint32_t code, int32_t lastStreamID, uint8_t* data, size_t len);
803+
void AltSvc(int32_t id,
804+
uint8_t* origin,
805+
size_t origin_len,
806+
uint8_t* value,
807+
size_t value_len);
803808

804809
bool Ping(v8::Local<v8::Function> function);
805810

@@ -879,6 +884,7 @@ class Http2Session : public AsyncWrap {
879884
static void UpdateChunksSent(const FunctionCallbackInfo<Value>& args);
880885
static void RefreshState(const FunctionCallbackInfo<Value>& args);
881886
static void Ping(const FunctionCallbackInfo<Value>& args);
887+
static void AltSvc(const FunctionCallbackInfo<Value>& args);
882888

883889
template <get_setting fn>
884890
static void RefreshSettings(const FunctionCallbackInfo<Value>& args);
@@ -923,6 +929,7 @@ class Http2Session : public AsyncWrap {
923929
inline void HandlePriorityFrame(const nghttp2_frame* frame);
924930
inline void HandleSettingsFrame(const nghttp2_frame* frame);
925931
inline void HandlePingFrame(const nghttp2_frame* frame);
932+
inline void HandleAltSvcFrame(const nghttp2_frame* frame);
926933

927934
// nghttp2 callbacks
928935
static inline int OnBeginHeadersCallback(

0 commit comments

Comments
 (0)