Skip to main content

s2n_quic_dc/
control.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::{packet::secret_control, path::secret::Map};
5use s2n_codec::DecoderBufferMut;
6use std::{net::SocketAddr, sync::Arc};
7
8pub struct Control {
9    socket: Arc<std::net::UdpSocket>,
10    port: u16,
11}
12
13impl Control {
14    pub fn new(address: SocketAddr, map: Map) -> std::io::Result<Self> {
15        let socket = Arc::new(std::net::UdpSocket::bind(address)?);
16        let port = socket.local_addr()?.port();
17
18        {
19            let socket = socket.clone();
20            std::thread::spawn(move || loop {
21                let mut buffer = vec![0; 10_000];
22                let (src, packet) = match socket.recv_from(&mut buffer) {
23                    Ok((length, src)) => (src, DecoderBufferMut::new(&mut buffer[..length])),
24                    Err(_) => continue,
25                };
26                let packet = secret_control::Packet::decode(packet);
27                match packet {
28                    Ok((packet, _remaining)) => map.handle_control_packet(&packet, &src),
29                    Err(_) => continue,
30                }
31            });
32        }
33
34        Ok(Control { socket, port })
35    }
36
37    pub fn send_to(&self, dest: SocketAddr, packet: &[u8]) {
38        // Our callers can't usefully handle errors either, so we just swallow them for now.
39        let _ = self.socket.send_to(packet, dest);
40    }
41
42    pub fn port(&self) -> u16 {
43        self.port
44    }
45}
46
47pub trait Controller {
48    /// Returns the source port to which control/reset messages should be sent
49    fn source_port(&self) -> u16;
50}
51
52impl Controller for u16 {
53    #[inline]
54    fn source_port(&self) -> u16 {
55        *self
56    }
57}