|
1 | 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
2 | 2 | // SPDX-License-Identifier: Apache-2.0 |
3 | 3 |
|
| 4 | +use crate::{packet::secret_control, path::secret::Map}; |
| 5 | +use s2n_codec::DecoderBufferMut; |
| 6 | +use std::{net::SocketAddr, sync::Arc}; |
| 7 | + |
| 8 | +pub struct Control { |
| 9 | + socket: Arc<std::net::UdpSocket>, |
| 10 | + port: u16, |
| 11 | +} |
| 12 | + |
| 13 | +impl 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().unwrap().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 | + |
4 | 47 | pub trait Controller { |
5 | 48 | /// Returns the source port to which control/reset messages should be sent |
6 | 49 | fn source_port(&self) -> u16; |
|
0 commit comments