Debian Codegraph @

third_party/rust/neqo-transport/src/server.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 // This file implements a server that can handle multiple connections.
8
9 use std::{
10 cell::RefCell,
11 cmp::min,
12 collections::HashSet,
13 fmt::{self, Display, Formatter},
14 ops::{Deref, DerefMut},
15 path::PathBuf,
16 rc::Rc,
17 time::Instant,
18 };
19
20 use neqo_common::{
21 event::Provider as _, hex, qdebug, qerror, qinfo, qlog::NeqoQlog, qtrace, qwarn, Datagram,
22 IpTos, Role,
23 };
24 use neqo_crypto::{
25 encode_ech_config, AntiReplay, Cipher, PrivateKey, PublicKey, ZeroRttCheckResult,
26 ZeroRttChecker,
27 };
28
29 pub use crate::addr_valid::ValidateAddress;
30 use crate::{
31 addr_valid::{AddressValidation, AddressValidationResult},
32 cid::{ConnectionId, ConnectionIdGenerator, ConnectionIdRef},
33 connection::{Connection, Output, State},
34 packet::{PacketBuilder, PacketType, PublicPacket, MIN_INITIAL_PACKET_SIZE},
35 ConnectionParameters, Res, Version,
36 };
37
38 /// A `ServerZeroRttChecker` is a simple wrapper around a single checker.
39 /// It uses `RefCell` so that the wrapped checker can be shared between
40 /// multiple connections created by the server.
41 #[derive(Clone, Debug)]
42 struct ServerZeroRttChecker {
43 checker: Rc<RefCell<Box<dyn ZeroRttChecker>>>,
44 }
45
46 impl ServerZeroRttChecker {
47 pub fn new(checker: Box<dyn ZeroRttChecker>) -> Self {
48 Self {
49 checker: Rc::new(RefCell::new(checker)),
50 }
51 }
52 }
53
54 impl ZeroRttChecker for ServerZeroRttChecker {
55 fn check(&self, token: &[u8]) -> ZeroRttCheckResult {
56 self.checker.borrow().check(token)
57 }
58 }
59
60 /// `InitialDetails` holds important information for processing `Initial` packets.
61 struct InitialDetails {
62 src_cid: ConnectionId,
63 dst_cid: ConnectionId,
64 token: Vec<u8>,
65 version: Version,
66 }
67
68 impl InitialDetails {
69 fn new(packet: &PublicPacket) -> Self {
70 Self {
71 src_cid: ConnectionId::from(packet.scid()),
72 dst_cid: ConnectionId::from(packet.dcid()),
73 token: packet.token().to_vec(),
74 version: packet.version().expect("packet has version"),
75 }
76 }
77 }
78
79 struct EchConfig {
80 config: u8,
81 public_name: String,
82 sk: PrivateKey,
83 pk: PublicKey,
84 encoded: Vec<u8>,
85 }
86
87 impl EchConfig {
88 fn new(config: u8, public_name: &str, sk: &PrivateKey, pk: &PublicKey) -> Res<Self> {
89 let encoded = encode_ech_config(config, public_name, pk)?;
90 Ok(Self {
91 config,
92 public_name: String::from(public_name),
93 sk: sk.clone(),
94 pk: pk.clone(),
95 encoded,
96 })
97 }
98 }
99
100 pub struct Server {
101 /// The names of certificates.
102 certs: Vec<String>,
103 /// The ALPN values that the server supports.
104 protocols: Vec<String>,
105 /// The cipher suites that the server supports.
106 ciphers: Vec<Cipher>,
107 /// Anti-replay configuration for 0-RTT.
108 anti_replay: AntiReplay,
109 /// A function for determining if 0-RTT can be accepted.
110 zero_rtt_checker: ServerZeroRttChecker,
111 /// A connection ID generator.
112 cid_generator: Rc<RefCell<dyn ConnectionIdGenerator>>,
113 /// Connection parameters.
114 conn_params: ConnectionParameters,
115 /// All connections.
116 connections: Vec<Rc<RefCell<Connection>>>,
117 /// Address validation logic, which determines whether we send a Retry.
118 address_validation: Rc<RefCell<AddressValidation>>,
119 /// Directory to create qlog traces in
120 qlog_dir: Option<PathBuf>,
121 /// Encrypted client hello (ECH) configuration.
122 ech_config: Option<EchConfig>,
123 }
124
125 impl Server {
126 /// Construct a new server.
127 /// * `now` is the time that the server is instantiated.
128 /// * `certs` is a list of the certificates that should be configured.
129 /// * `protocols` is the preference list of ALPN values.
130 /// * `anti_replay` is an anti-replay context.
131 /// * `zero_rtt_checker` determines whether 0-RTT should be accepted. This will be passed the
132 /// value of the `extra` argument that was passed to `Connection::send_ticket` to see if it is
133 /// OK.
134 /// * `cid_generator` is responsible for generating connection IDs and parsing them; connection
135 /// IDs produced by the manager cannot be zero-length.
136 /// # Errors
137 /// When address validation state cannot be created.
138 pub fn new(
139 now: Instant,
140 certs: &[impl AsRef<str>],
141 protocols: &[impl AsRef<str>],
142 anti_replay: AntiReplay,
143 zero_rtt_checker: Box<dyn ZeroRttChecker>,
144 cid_generator: Rc<RefCell<dyn ConnectionIdGenerator>>,
145 conn_params: ConnectionParameters,
146 ) -> Res<Self> {
147 let validation = AddressValidation::new(now, ValidateAddress::Never)?;
148 Ok(Self {
149 certs: certs.iter().map(|x| String::from(x.as_ref())).collect(),
150 protocols: protocols.iter().map(|x| String::from(x.as_ref())).collect(),
151 ciphers: Vec::new(),
152 anti_replay,
153 zero_rtt_checker: ServerZeroRttChecker::new(zero_rtt_checker),
154 cid_generator,
155 conn_params,
156 connections: Vec::new(),
157 address_validation: Rc::new(RefCell::new(validation)),
158 qlog_dir: None,
159 ech_config: None,
160 })
161 }
162
163 /// Set or clear directory to create logs of connection events in QLOG format.
164 pub fn set_qlog_dir(&mut self, dir: Option<PathBuf>) {
165 self.qlog_dir = dir;
166 }
167
168 /// Set the policy for address validation.
169 pub fn set_validation(&self, v: ValidateAddress) {
170 self.address_validation.borrow_mut().set_validation(v);
171 }
172
173 /// Set the cipher suites that should be used. Set an empty value to use
174 /// default values.
175 pub fn set_ciphers(&mut self, ciphers: impl AsRef<[Cipher]>) {
176 self.ciphers = Vec::from(ciphers.as_ref());
177 }
178
179 /// # Errors
180 /// When the configuration is invalid.
181 pub fn enable_ech(
182 &mut self,
183 config: u8,
184 public_name: &str,
185 sk: &PrivateKey,
186 pk: &PublicKey,
187 ) -> Res<()> {
188 self.ech_config = Some(EchConfig::new(config, public_name, sk, pk)?);
189 Ok(())
190 }
191
192 #[must_use]
193 pub fn ech_config(&self) -> &[u8] {
194 self.ech_config.as_ref().map_or(&[], |cfg| &cfg.encoded)
195 }
196
197 fn handle_initial(
198 &mut self,
199 initial: InitialDetails,
200 dgram: Datagram<impl AsRef<[u8]> + AsMut<[u8]>>,
201 now: Instant,
202 ) -> Output {
203 qdebug!("[{self}] Handle initial");
204 let res = self
205 .address_validation
206 .borrow()
207 .validate(&initial.token, dgram.source(), now);
208 match res {
209 AddressValidationResult::Invalid => Output::None,
210 AddressValidationResult::Pass => self.accept_connection(initial, dgram, None, now),
211 AddressValidationResult::ValidRetry(orig_dcid) => {
212 self.accept_connection(initial, dgram, Some(orig_dcid), now)
213 }
214 AddressValidationResult::Validate => {
215 qinfo!("[{self}] Send retry for {:?}", initial.dst_cid);
216
217 let res = self.address_validation.borrow().generate_retry_token(
218 &initial.dst_cid,
219 dgram.source(),
220 now,
221 );
222 let Ok(token) = res else {
223 qerror!("[{self}] unable to generate token, dropping packet");
224 return Output::None;
225 };
226 if let Some(new_dcid) = self.cid_generator.borrow_mut().generate_cid() {
227 let packet = PacketBuilder::retry(
228 initial.version,
229 &initial.src_cid,
230 &new_dcid,
231 &token,
232 &initial.dst_cid,
233 );
234 packet.map_or_else(
235 |_| {
236 qerror!("[{self}] unable to encode retry, dropping packet");
237 Output::None
238 },
239 |p| {
240 qdebug!(
241 "[{self}] type={:?} path:{} {}->{} {:?} len {}",
242 PacketType::Retry,
243 initial.dst_cid,
244 dgram.destination(),
245 dgram.source(),
246 IpTos::default(),
247 p.len(),
248 );
249 Output::Datagram(Datagram::new(
250 dgram.destination(),
251 dgram.source(),
252 IpTos::default(),
253 p,
254 ))
255 },
256 )
257 } else {
258 qerror!("[{self}] no connection ID for retry, dropping packet");
259 Output::None
260 }
261 }
262 }
263 }
264
265 fn create_qlog_trace(&self, odcid: ConnectionIdRef<'_>) -> NeqoQlog {
266 self.qlog_dir
267 .as_ref()
268 .map_or_else(NeqoQlog::disabled, |qlog_dir| {
269 NeqoQlog::enabled_with_file(
270 qlog_dir.clone(),
271 Role::Server,
272 Some("Neqo server qlog".to_string()),
273 Some("Neqo server qlog".to_string()),
274 format!("server-{odcid}"),
275 )
276 .unwrap_or_else(|e| {
277 qerror!("failed to create NeqoQlog: {e}");
278 NeqoQlog::disabled()
279 })
280 })
281 }
282
283 fn setup_connection(
284 &self,
285 c: &mut Connection,
286 initial: InitialDetails,
287 orig_dcid: Option<ConnectionId>,
288 ) {
289 let zcheck = self.zero_rtt_checker.clone();
290 if c.server_enable_0rtt(&self.anti_replay, zcheck).is_err() {
291 qwarn!("[{self}] Unable to enable 0-RTT");
292 }
293 if let Some(odcid) = &orig_dcid {
294 // There was a retry, so set the connection IDs for.
295 c.set_retry_cids(odcid, initial.src_cid, &initial.dst_cid);
296 }
297 c.set_validation(&self.address_validation);
298 c.set_qlog(self.create_qlog_trace(orig_dcid.unwrap_or(initial.dst_cid).as_cid_ref()));
299 if let Some(cfg) = &self.ech_config {
300 if c.server_enable_ech(cfg.config, &cfg.public_name, &cfg.sk, &cfg.pk)
301 .is_err()
302 {
303 qwarn!("[{self}] Unable to enable ECH");
304 }
305 }
306 }
307
308 fn accept_connection(
309 &mut self,
310 initial: InitialDetails,
311 dgram: Datagram<impl AsRef<[u8]> + AsMut<[u8]>>,
312 orig_dcid: Option<ConnectionId>,
313 now: Instant,
314 ) -> Output {
315 qinfo!(
316 "[{self}] Accept connection {:?}",
317 orig_dcid.as_ref().unwrap_or(&initial.dst_cid)
318 );
319 // The internal connection ID manager that we use is not used directly.
320 // Instead, wrap it so that we can save connection IDs.
321
322 let mut params = self.conn_params.clone();
323 params.get_versions_mut().set_initial(initial.version);
324 let sconn = Connection::new_server(
325 &self.certs,
326 &self.protocols,
327 Rc::clone(&self.cid_generator),
328 params,
329 );
330
331 match sconn {
332 Ok(mut c) => {
333 self.setup_connection(&mut c, initial, orig_dcid);
334 let out = c.process(Some(dgram), now);
335 self.connections.push(Rc::new(RefCell::new(c)));
336 out
337 }
338 Err(e) => {
339 qwarn!("[{self}] Unable to create connection");
340 if e == crate::Error::VersionNegotiation {
341 crate::qlog::server_version_information_failed(
342 &self.create_qlog_trace(orig_dcid.unwrap_or(initial.dst_cid).as_cid_ref()),
343 self.conn_params.get_versions().all(),
344 initial.version.wire_version(),
345 now,
346 );
347 }
348 Output::None
349 }
350 }
351 }
352
353 fn process_input(
354 &mut self,
355 mut dgram: Datagram<impl AsRef<[u8]> + AsMut<[u8]>>,
356 now: Instant,
357 ) -> Output {
358 qtrace!("Process datagram: {}", hex(&dgram[..]));
359
360 // This is only looking at the first packet header in the datagram.
361 // All packets in the datagram are routed to the same connection.
362 let len = dgram.len();
363 let destination = dgram.destination();
364 let source = dgram.source();
365 let res = PublicPacket::decode(&mut dgram[..], self.cid_generator.borrow().as_decoder());
366 let Ok((packet, _remainder)) = res else {
367 qtrace!("[{self}] Discarding {dgram:?}");
368 return Output::None;
369 };
370
371 // Finding an existing connection. Should be the most common case.
372 if let Some(c) = self
373 .connections
374 .iter_mut()
375 .find(|c| c.borrow().is_valid_local_cid(packet.dcid()))
376 {
377 return c.borrow_mut().process(Some(dgram), now);
378 }
379
380 if packet.packet_type() == PacketType::Short {
381 // TODO send a stateless reset here.
382 qtrace!("[{self}] Short header packet for an unknown connection");
383 return Output::None;
384 }
385
386 if packet.packet_type() == PacketType::OtherVersion
387 || (packet.packet_type() == PacketType::Initial
388 && !self
389 .conn_params
390 .get_versions()
391 .all()
392 .contains(&packet.version().expect("packet has version")))
393 {
394 if len < MIN_INITIAL_PACKET_SIZE {
395 qdebug!("[{self}] Unsupported version: too short");
396 return Output::None;
397 }
398
399 qdebug!("[{self}] Unsupported version: {:x}", packet.wire_version());
400 let vn = PacketBuilder::version_negotiation(
401 &packet.scid()[..],
402 &packet.dcid()[..],
403 packet.wire_version(),
404 self.conn_params.get_versions().all(),
405 );
406 qdebug!(
407 "[{self}] type={:?} path:{} {}->{} {:?} len {}",
408 PacketType::VersionNegotiation,
409 packet.dcid(),
410 destination,
411 source,
412 IpTos::default(),
413 vn.len(),
414 );
415
416 crate::qlog::server_version_information_failed(
417 &self.create_qlog_trace(packet.dcid()),
418 self.conn_params.get_versions().all(),
419 packet.wire_version(),
420 now,
421 );
422
423 return Output::Datagram(Datagram::new(destination, source, IpTos::default(), vn));
424 }
425
426 match packet.packet_type() {
427 PacketType::Initial => {
428 if len < MIN_INITIAL_PACKET_SIZE {
429 qdebug!("[{self}] Drop initial: too short");
430 return Output::None;
431 }
432 // Copy values from `packet` because they are currently still borrowing from
433 // `dgram`.
434 let initial = InitialDetails::new(&packet);
435 self.handle_initial(initial, dgram, now)
436 }
437 PacketType::ZeroRtt => {
438 qdebug!(
439 "[{self}] Dropping 0-RTT for unknown connection {}",
440 ConnectionId::from(packet.dcid())
441 );
442 Output::None
443 }
444 PacketType::OtherVersion => unreachable!(),
445 _ => {
446 qtrace!("[{self}] Not an initial packet");
447 Output::None
448 }
449 }
450 }
451
452 /// Iterate through the pending connections looking for any that might want
453 /// to send a datagram. Stop at the first one that does.
454 fn process_next_output(&mut self, now: Instant) -> Output {
455 let mut callback = None;
456
457 for connection in &mut self.connections {
458 match connection.borrow_mut().process_output(now) {
459 Output::None => {}
460 d @ Output::Datagram(_) => return d,
461 Output::Callback(next) => match callback {
462 Some(previous) => callback = Some(min(previous, next)),
463 None => callback = Some(next),
464 },
465 }
466 }
467
468 callback.map_or(Output::None, Output::Callback)
469 }
470
471 /// Short-hand for [`Server::process`] without an input datagram.
472 #[must_use]
473 pub fn process_output(&mut self, now: Instant) -> Output {
474 self.process(None::<Datagram>, now)
475 }
476
477 #[must_use]
478 pub fn process(
479 &mut self,
480 dgram: Option<Datagram<impl AsRef<[u8]> + AsMut<[u8]>>>,
481 now: Instant,
482 ) -> Output {
483 let out = dgram
484 .map_or(Output::None, |d| self.process_input(d, now))
485 .or_else(|| self.process_next_output(now));
486
487 // Clean-up closed connections.
488 self.connections
489 .retain(|c| !matches!(c.borrow().state(), State::Closed(_)));
490
491 out
492 }
493
494 /// This lists the connections that have received new events
495 /// as a result of calling `process()`.
496 #[expect(
497 clippy::mutable_key_type,
498 reason = "ActiveConnectionRef::Hash doesn't access any of the interior mutable types."
499 )]
500 #[must_use]
501 pub fn active_connections(&self) -> HashSet<ConnectionRef> {
502 self.connections
503 .iter()
504 .filter(|c| c.borrow().has_events())
505 .map(|c| ConnectionRef { c: Rc::clone(c) })
506 .collect()
507 }
508
509 /// Whether any connections have received new events as a result of calling
510 /// `process()`.
511 #[must_use]
512 pub fn has_active_connections(&self) -> bool {
513 self.connections.iter().any(|c| c.borrow().has_events())
514 }
515 }
516
517 #[derive(Clone, Debug)]
518 pub struct ConnectionRef {
519 c: Rc<RefCell<Connection>>,
520 }
521
522 impl ConnectionRef {
523 #[must_use]
524 pub fn borrow(&self) -> impl Deref<Target = Connection> + '_ {
525 self.c.borrow()
526 }
527
528 #[must_use]
529 pub fn borrow_mut(&self) -> impl DerefMut<Target = Connection> + '_ {
530 self.c.borrow_mut()
531 }
532
533 #[must_use]
534 pub fn connection(&self) -> Rc<RefCell<Connection>> {
535 Rc::clone(&self.c)
536 }
537 }
538
539 impl std::hash::Hash for ConnectionRef {
540 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
541 let ptr: *const _ = self.c.as_ref();
542 ptr.hash(state);
543 }
544 }
545
546 impl PartialEq for ConnectionRef {
547 fn eq(&self, other: &Self) -> bool {
548 Rc::ptr_eq(&self.c, &other.c)
549 }
550 }
551
552 impl Eq for ConnectionRef {}
553
554 impl Display for Server {
555 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
556 write!(f, "Server")
557 }
558 }