tokio_util/udp/frame.rs
1use crate::codec::{Decoder, Encoder};
2
3use futures_core::Stream;
4use tokio::{io::ReadBuf, net::UdpSocket};
5
6use bytes::{BufMut, BytesMut};
7use futures_sink::Sink;
8use std::io;
9use std::pin::Pin;
10use std::task::{ready, Context, Poll};
11use std::{
12 borrow::Borrow,
13 net::{Ipv4Addr, SocketAddr, SocketAddrV4},
14};
15
16/// A unified [`Stream`] and [`Sink`] interface to an underlying `UdpSocket`, using
17/// the `Encoder` and `Decoder` traits to encode and decode frames.
18///
19/// Raw UDP sockets work with datagrams, but higher-level code usually wants to
20/// batch these into meaningful chunks, called "frames". This method layers
21/// framing on top of this socket by using the `Encoder` and `Decoder` traits to
22/// handle encoding and decoding of messages frames. Note that the incoming and
23/// outgoing frame types may be distinct.
24///
25/// A single datagram may decode into multiple frames. `UdpFramed` will keep
26/// calling [`Decoder::decode_eof`] with the current datagram until it returns
27/// `Ok(None)`. If a decoder wants to discard a malformed datagram and continue
28/// receiving later datagrams, it should consume or clear the remaining bytes
29/// from the buffer before returning `Err`.
30///
31/// This function returns a *single* object that is both [`Stream`] and [`Sink`];
32/// grouping this into a single object is often useful for layering things which
33/// require both read and write access to the underlying object.
34///
35/// If you want to work more directly with the streams and sink, consider
36/// calling [`split`] on the `UdpFramed` returned by this method, which will break
37/// them into separate objects, allowing them to interact more easily.
38///
39/// [`Stream`]: futures_core::Stream
40/// [`Sink`]: futures_sink::Sink
41/// [`split`]: https://docs.rs/futures/0.3/futures/stream/trait.StreamExt.html#method.split
42#[must_use = "sinks do nothing unless polled"]
43#[derive(Debug)]
44pub struct UdpFramed<C, T = UdpSocket> {
45 socket: T,
46 codec: C,
47 rd: BytesMut,
48 wr: BytesMut,
49 out_addr: SocketAddr,
50 flushed: bool,
51 is_readable: bool,
52 current_addr: Option<SocketAddr>,
53}
54
55const INITIAL_RD_CAPACITY: usize = 64 * 1024;
56const INITIAL_WR_CAPACITY: usize = 8 * 1024;
57
58impl<C, T> Unpin for UdpFramed<C, T> {}
59
60impl<C, T> Stream for UdpFramed<C, T>
61where
62 T: Borrow<UdpSocket>,
63 C: Decoder,
64{
65 type Item = Result<(C::Item, SocketAddr), C::Error>;
66
67 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
68 let pin = self.get_mut();
69
70 pin.rd.reserve(INITIAL_RD_CAPACITY);
71
72 loop {
73 // Are there still bytes left in the read buffer to decode?
74 if pin.is_readable {
75 if let Some(frame) = pin.codec.decode_eof(&mut pin.rd)? {
76 let current_addr = pin
77 .current_addr
78 .expect("will always be set before this line is called");
79
80 return Poll::Ready(Some(Ok((frame, current_addr))));
81 }
82
83 // if this line has been reached then decode has returned `None`.
84 pin.is_readable = false;
85 pin.rd.clear();
86 }
87
88 // We're out of data. Try and fetch more data to decode
89 let addr = {
90 // Safety: `chunk_mut()` returns a `&mut UninitSlice`, and `UninitSlice` is a
91 // transparent wrapper around `[MaybeUninit<u8>]`.
92 let buf = unsafe { pin.rd.chunk_mut().as_uninit_slice_mut() };
93 let mut read = ReadBuf::uninit(buf);
94 let ptr = read.filled().as_ptr();
95 let res = ready!(pin.socket.borrow().poll_recv_from(cx, &mut read));
96
97 assert_eq!(ptr, read.filled().as_ptr());
98 let addr = res?;
99
100 let filled = read.filled().len();
101 // Safety: This is guaranteed to be the number of initialized (and read) bytes due
102 // to the invariants provided by `ReadBuf::filled`.
103 unsafe { pin.rd.advance_mut(filled) };
104
105 addr
106 };
107
108 pin.current_addr = Some(addr);
109 pin.is_readable = true;
110 }
111 }
112}
113
114impl<I, C, T> Sink<(I, SocketAddr)> for UdpFramed<C, T>
115where
116 T: Borrow<UdpSocket>,
117 C: Encoder<I>,
118{
119 type Error = C::Error;
120
121 fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
122 if !self.flushed {
123 match self.poll_flush(cx)? {
124 Poll::Ready(()) => {}
125 Poll::Pending => return Poll::Pending,
126 }
127 }
128
129 Poll::Ready(Ok(()))
130 }
131
132 fn start_send(self: Pin<&mut Self>, item: (I, SocketAddr)) -> Result<(), Self::Error> {
133 let (frame, out_addr) = item;
134
135 let pin = self.get_mut();
136
137 pin.codec.encode(frame, &mut pin.wr)?;
138 pin.out_addr = out_addr;
139 pin.flushed = false;
140
141 Ok(())
142 }
143
144 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
145 if self.flushed {
146 return Poll::Ready(Ok(()));
147 }
148
149 let Self {
150 ref socket,
151 ref mut out_addr,
152 ref mut wr,
153 ..
154 } = *self;
155
156 let n = ready!(socket.borrow().poll_send_to(cx, wr, *out_addr))?;
157
158 let wrote_all = n == self.wr.len();
159 self.wr.clear();
160 self.flushed = true;
161
162 let res = if wrote_all {
163 Ok(())
164 } else {
165 Err(io::Error::new(
166 io::ErrorKind::Other,
167 "failed to write entire datagram to socket",
168 )
169 .into())
170 };
171
172 Poll::Ready(res)
173 }
174
175 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
176 ready!(self.poll_flush(cx))?;
177 Poll::Ready(Ok(()))
178 }
179}
180
181impl<C, T> UdpFramed<C, T>
182where
183 T: Borrow<UdpSocket>,
184{
185 /// Create a new `UdpFramed` backed by the given socket and codec.
186 ///
187 /// See struct level documentation for more details.
188 pub fn new(socket: T, codec: C) -> UdpFramed<C, T> {
189 Self {
190 socket,
191 codec,
192 out_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0)),
193 rd: BytesMut::with_capacity(INITIAL_RD_CAPACITY),
194 wr: BytesMut::with_capacity(INITIAL_WR_CAPACITY),
195 flushed: true,
196 is_readable: false,
197 current_addr: None,
198 }
199 }
200
201 /// Returns a reference to the underlying I/O stream wrapped by `Framed`.
202 ///
203 /// # Note
204 ///
205 /// Care should be taken to not tamper with the underlying stream of data
206 /// coming in as it may corrupt the stream of frames otherwise being worked
207 /// with.
208 pub fn get_ref(&self) -> &T {
209 &self.socket
210 }
211
212 /// Returns a mutable reference to the underlying I/O stream wrapped by `Framed`.
213 ///
214 /// # Note
215 ///
216 /// Care should be taken to not tamper with the underlying stream of data
217 /// coming in as it may corrupt the stream of frames otherwise being worked
218 /// with.
219 pub fn get_mut(&mut self) -> &mut T {
220 &mut self.socket
221 }
222
223 /// Returns a reference to the underlying codec wrapped by
224 /// `Framed`.
225 ///
226 /// Note that care should be taken to not tamper with the underlying codec
227 /// as it may corrupt the stream of frames otherwise being worked with.
228 pub fn codec(&self) -> &C {
229 &self.codec
230 }
231
232 /// Returns a mutable reference to the underlying codec wrapped by
233 /// `UdpFramed`.
234 ///
235 /// Note that care should be taken to not tamper with the underlying codec
236 /// as it may corrupt the stream of frames otherwise being worked with.
237 pub fn codec_mut(&mut self) -> &mut C {
238 &mut self.codec
239 }
240
241 /// Returns a reference to the read buffer.
242 pub fn read_buffer(&self) -> &BytesMut {
243 &self.rd
244 }
245
246 /// Returns a mutable reference to the read buffer.
247 pub fn read_buffer_mut(&mut self) -> &mut BytesMut {
248 &mut self.rd
249 }
250
251 /// Consumes the `Framed`, returning its underlying I/O stream.
252 pub fn into_inner(self) -> T {
253 self.socket
254 }
255}