-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathwebtransport_session.rs
More file actions
299 lines (271 loc) · 9.88 KB
/
Copy pathwebtransport_session.rs
File metadata and controls
299 lines (271 loc) · 9.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::{
collections::HashSet,
fmt::{self, Display, Formatter},
mem,
time::Instant,
};
use neqo_common::{Bytes, Encoder, Header, Role, qtrace};
use neqo_transport::{Connection, Error as TransportError, StreamId};
use sfv::{BareItem, Item, Parser};
use crate::{
Error, Http3StreamInfo, Http3StreamType, RecvStream, Res, SendStream,
features::extended_connect::{
CloseReason, ExtendedConnectEvents, ExtendedConnectType,
session::{DgramContextIdError, Protocol, State},
},
frames::{FrameReader, StreamReaderRecvStreamWrapper, WebTransportFrame},
};
#[derive(Debug)]
pub struct Session {
frame_reader: FrameReader,
id: StreamId,
send_streams: HashSet<StreamId>,
recv_streams: HashSet<StreamId>,
role: Role,
/// Remote initiated streams received before session confirmation.
///
/// [`HashSet`] size limited by QUIC connection stream limit.
pending_streams: HashSet<StreamId>,
/// The negotiated protocol from server response headers.
negotiated_protocol: Option<String>,
}
impl Display for Session {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "WebTransportSession")
}
}
impl Session {
#[must_use]
pub(crate) fn new(session_id: StreamId, role: Role) -> Self {
Self {
id: session_id,
frame_reader: FrameReader::new(),
send_streams: HashSet::default(),
recv_streams: HashSet::default(),
role,
pending_streams: HashSet::default(),
negotiated_protocol: None,
}
}
}
impl Protocol for Session {
fn connect_type(&self) -> ExtendedConnectType {
ExtendedConnectType::WebTransport
}
fn session_start(&mut self, events: &mut Box<dyn ExtendedConnectEvents>) -> Res<()> {
// > WebTransport endpoints SHOULD buffer streams and
// > datagrams until they can be associated with an
// > established session.
//
// <https://www.ietf.org/archive/id/draft-ietf-webtrans-http3-13.html#section-4.5>
#[expect(clippy::iter_over_hash_type, reason = "no defined order necessary")]
for stream_id in self.pending_streams.drain() {
events.extended_connect_new_stream(
Http3StreamInfo::new(stream_id, Http3StreamType::WebTransport(self.id)),
// Explicitly emit a stream readable event. Such
// event was previously suppressed as the
// session was still negotiating.
true,
)?;
}
Ok(())
}
fn close_frame(&self, error: u32, message: &str) -> Option<Vec<u8>> {
let close_frame = WebTransportFrame::CloseSession {
error,
message: message.to_string(),
};
let mut encoder = Encoder::default();
close_frame.encode(&mut encoder);
Some(encoder.into())
}
fn read_control_stream(
&mut self,
conn: &mut Connection,
events: &mut Box<dyn ExtendedConnectEvents>,
control_stream_recv: &mut Box<dyn RecvStream>,
now: Instant,
) -> Res<Option<State>> {
let (f, fin) = self
.frame_reader
.receive::<WebTransportFrame>(
&mut StreamReaderRecvStreamWrapper::new(conn, control_stream_recv),
now,
)
.map_err(|_| Error::HttpGeneralProtocolStream)?;
qtrace!("[{self}] Received frame: {f:?} fin={fin}");
if let Some(WebTransportFrame::CloseSession { error, message }) = f {
events.session_end(
ExtendedConnectType::WebTransport,
self.id,
CloseReason::Clean { error, message },
None,
);
if fin {
Ok(Some(State::Done))
} else {
Ok(Some(State::FinPending))
}
} else if fin {
events.session_end(
ExtendedConnectType::WebTransport,
self.id,
CloseReason::Clean {
error: 0,
message: String::new(),
},
None,
);
Ok(Some(State::Done))
} else {
Ok(None)
}
}
fn add_stream(
&mut self,
stream_id: StreamId,
events: &mut Box<dyn ExtendedConnectEvents>,
state: State,
) -> Res<()> {
match state {
State::Negotiating | State::Active => {}
State::FinPending | State::Done => return Ok(()),
}
if stream_id.is_bidi() {
self.send_streams.insert(stream_id);
self.recv_streams.insert(stream_id);
} else if stream_id.is_self_initiated(self.role) {
self.send_streams.insert(stream_id);
} else {
self.recv_streams.insert(stream_id);
}
match state {
State::FinPending | State::Done => {
unreachable!("see match above");
}
State::Negotiating => {
// > a client may receive a server-initiated stream or a datagram
// > before receiving the CONNECT response headers from the
// > server.
// >
// > To handle this case, WebTransport endpoints SHOULD buffer
// > streams and datagrams until they can be associated with an
// > established session.
//
// <https://www.ietf.org/archive/id/draft-ietf-webtrans-http3-13.html#section-4.5>
self.pending_streams.insert(stream_id);
}
State::Active => {
if !stream_id.is_self_initiated(self.role) {
events.extended_connect_new_stream(
Http3StreamInfo::new(stream_id, Http3StreamType::WebTransport(self.id)),
// Don't emit an additional stream readable event. Given
// that the session is already active, this event will
// be emitted through the WebTransport stream itself.
false,
)?;
}
}
}
Ok(())
}
fn remove_recv_stream(&mut self, stream_id: StreamId) {
self.recv_streams.remove(&stream_id);
}
fn remove_send_stream(&mut self, stream_id: StreamId) {
self.send_streams.remove(&stream_id);
}
fn take_sub_streams(&mut self) -> (HashSet<StreamId>, HashSet<StreamId>) {
(
mem::take(&mut self.recv_streams),
mem::take(&mut self.send_streams),
)
}
fn process_response_headers(&mut self, headers: &[Header]) {
self.negotiated_protocol = headers
.iter()
.find(|h| h.name().eq_ignore_ascii_case("wt-protocol"))
.and_then(|h| Parser::new(h.value()).parse::<Item>().ok())
.and_then(|item| {
if let BareItem::String(s) = item.bare_item {
Some(s.into())
} else {
None
}
});
}
fn protocol(&self) -> Option<&str> {
self.negotiated_protocol.as_deref()
}
fn write_datagram_prefix(&self, _encoder: &mut Encoder) {
// WebTransport does not add prefix (i.e. context ID).
}
fn dgram_context_id(&self, datagram: Bytes) -> Result<Bytes, DgramContextIdError> {
// WebTransport does not use a prefix (i.e. context ID).
Ok(datagram)
}
fn datagram_capsule_support(&self) -> bool {
// HTTP/3 WebTransport requires QUIC datagram support. In other words,
// HTTP/3 WebTransport never falls back to HTTP datagram capsules.
//
// > WebTransport over HTTP/3 also requires support for QUIC datagrams.
// > To indicate support, both the client and the server send a
// > max_datagram_frame_size transport parameter with a value greater than
// > 0 (see Section 3 of [QUIC-DATAGRAM]).
//
// <https://www.ietf.org/archive/id/draft-ietf-webtrans-http3-14.html#section-3.1>
false
}
fn write_datagram_capsule(
&self,
_control_stream_send: &mut Box<dyn SendStream>,
_conn: &mut Connection,
_buf: &[u8],
_now: Instant,
) -> Res<()> {
debug_assert!(
false,
"[{self}] WebTransport does not support datagram capsules."
);
Ok(())
}
}
pub trait WebTransportExportKeyingMaterial {
fn webtransport_export_keying_material(
&self,
session_id: StreamId,
label: &[u8],
context: &[u8],
out: &mut [u8],
) -> Res<()>;
}
impl WebTransportExportKeyingMaterial for Connection {
fn webtransport_export_keying_material(
&self,
session_id: StreamId,
label: &[u8],
context: &[u8],
out: &mut [u8],
) -> Res<()> {
// encode_vec(1, …) uses a 1-byte length prefix, so max 255 bytes.
if out.is_empty() || label.len() > 255 || context.len() > 255 {
return Err(Error::InvalidInput);
}
let mut wt_context = Encoder::with_capacity(
Encoder::varint_len(session_id.as_u64()) + 1 + label.len() + 1 + context.len(),
);
wt_context.encode_varint(session_id.as_u64());
wt_context.encode_vec(1, label);
wt_context.encode_vec(1, context);
self.export_keying_material("EXPORTER-WebTransport", wt_context.as_ref(), out)
.map_err(|e| match e {
TransportError::InvalidInput => Error::InvalidInput,
other => Error::Transport(other),
})
}
}