tokio_util/codec/lines_codec.rs
1use crate::codec::decoder::Decoder;
2use crate::codec::encoder::Encoder;
3
4use bytes::{Buf, BufMut, BytesMut};
5use std::{cmp, fmt, io, str};
6
7/// A simple [`Decoder`] and [`Encoder`] implementation that splits up data into lines.
8///
9/// This uses the `\n` character as the line ending on all platforms.
10///
11/// [`Decoder`]: crate::codec::Decoder
12/// [`Encoder`]: crate::codec::Encoder
13#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
14pub struct LinesCodec {
15 // Stored index of the next index to examine for a `\n` character.
16 // This is used to optimize searching.
17 // For example, if `decode` was called with `abc`, it would hold `3`,
18 // because that is the next index to examine.
19 // The next time `decode` is called with `abcde\n`, the method will
20 // only look at `de\n` before returning.
21 next_index: usize,
22
23 /// The maximum length for a given line. If `usize::MAX`, lines will be
24 /// read until a `\n` character is reached.
25 max_length: usize,
26
27 /// Are we currently discarding the remainder of a line which was over
28 /// the length limit?
29 is_discarding: bool,
30}
31
32impl LinesCodec {
33 /// Returns a `LinesCodec` for splitting up data into lines.
34 ///
35 /// # Note
36 ///
37 /// The returned `LinesCodec` will not have an upper bound on the length
38 /// of a buffered line. See the documentation for [`new_with_max_length`]
39 /// for information on why this could be a potential security risk.
40 ///
41 /// [`new_with_max_length`]: crate::codec::LinesCodec::new_with_max_length()
42 pub fn new() -> LinesCodec {
43 LinesCodec {
44 next_index: 0,
45 max_length: usize::MAX,
46 is_discarding: false,
47 }
48 }
49
50 /// Returns a `LinesCodec` with a maximum line length limit.
51 ///
52 /// If this is set, calls to `LinesCodec::decode` will return a
53 /// [`LinesCodecError`] when a line exceeds the length limit. Subsequent calls
54 /// will discard up to `limit` bytes from that line until a newline
55 /// character is reached, returning `None` until the line over the limit
56 /// has been fully discarded. After that point, calls to `decode` will
57 /// function as normal.
58 ///
59 /// # Note
60 ///
61 /// Setting a length limit is highly recommended for any `LinesCodec` which
62 /// will be exposed to untrusted input. Otherwise, the size of the buffer
63 /// that holds the line currently being read is unbounded. An attacker could
64 /// exploit this unbounded buffer by sending an unbounded amount of input
65 /// without any `\n` characters, causing unbounded memory consumption.
66 ///
67 /// [`LinesCodecError`]: crate::codec::LinesCodecError
68 pub fn new_with_max_length(max_length: usize) -> Self {
69 LinesCodec {
70 max_length,
71 ..LinesCodec::new()
72 }
73 }
74
75 /// Returns the maximum line length when decoding.
76 ///
77 /// ```
78 /// use tokio_util::codec::LinesCodec;
79 ///
80 /// let codec = LinesCodec::new();
81 /// assert_eq!(codec.max_length(), usize::MAX);
82 /// ```
83 /// ```
84 /// use tokio_util::codec::LinesCodec;
85 ///
86 /// let codec = LinesCodec::new_with_max_length(256);
87 /// assert_eq!(codec.max_length(), 256);
88 /// ```
89 pub fn max_length(&self) -> usize {
90 self.max_length
91 }
92}
93
94fn utf8(buf: &[u8]) -> Result<&str, io::Error> {
95 str::from_utf8(buf)
96 .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Unable to decode input as UTF8"))
97}
98
99fn without_carriage_return(s: &[u8]) -> &[u8] {
100 if let Some(&b'\r') = s.last() {
101 &s[..s.len() - 1]
102 } else {
103 s
104 }
105}
106
107impl Decoder for LinesCodec {
108 type Item = String;
109 type Error = LinesCodecError;
110
111 fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<String>, LinesCodecError> {
112 loop {
113 // Determine how far into the buffer we'll search for a newline. If
114 // there's no max_length set, we'll read to the end of the buffer.
115 let read_to = cmp::min(self.max_length.saturating_add(1), buf.len());
116
117 let newline_offset = crate::util::memchr::memchr(b'\n', &buf[self.next_index..read_to]);
118
119 match (self.is_discarding, newline_offset) {
120 (true, Some(offset)) => {
121 // If we found a newline, discard up to that offset and
122 // then stop discarding. On the next iteration, we'll try
123 // to read a line normally.
124 buf.advance(offset + self.next_index + 1);
125 self.is_discarding = false;
126 self.next_index = 0;
127 }
128 (true, None) => {
129 // Otherwise, we didn't find a newline, so we'll discard
130 // everything we read. On the next iteration, we'll continue
131 // discarding up to max_len bytes unless we find a newline.
132 buf.advance(read_to);
133 self.next_index = 0;
134 if buf.is_empty() {
135 return Ok(None);
136 }
137 }
138 (false, Some(offset)) => {
139 // Found a line!
140 let newline_index = offset + self.next_index;
141 self.next_index = 0;
142 let line = buf.split_to(newline_index + 1);
143 let line = &line[..line.len() - 1];
144 let line = without_carriage_return(line);
145 let line = utf8(line)?;
146 return Ok(Some(line.to_string()));
147 }
148 (false, None) if buf.len() > self.max_length => {
149 // Reached the maximum length without finding a
150 // newline, return an error and start discarding on the
151 // next call.
152 self.is_discarding = true;
153 return Err(LinesCodecError::MaxLineLengthExceeded);
154 }
155 (false, None) => {
156 // We didn't find a line or reach the length limit, so the next
157 // call will resume searching at the current offset.
158 self.next_index = read_to;
159 return Ok(None);
160 }
161 }
162 }
163 }
164
165 fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<String>, LinesCodecError> {
166 Ok(match self.decode(buf)? {
167 Some(frame) => Some(frame),
168 None => {
169 self.next_index = 0;
170 // No terminating newline - return remaining data, if any
171 if buf.is_empty() || buf == &b"\r"[..] {
172 None
173 } else {
174 let line = buf.split_to(buf.len());
175 let line = without_carriage_return(&line);
176 let line = utf8(line)?;
177 Some(line.to_string())
178 }
179 }
180 })
181 }
182}
183
184impl<T> Encoder<T> for LinesCodec
185where
186 T: AsRef<str>,
187{
188 type Error = LinesCodecError;
189
190 fn encode(&mut self, line: T, buf: &mut BytesMut) -> Result<(), LinesCodecError> {
191 let line = line.as_ref();
192 buf.reserve(line.len() + 1);
193 buf.put(line.as_bytes());
194 buf.put_u8(b'\n');
195 Ok(())
196 }
197}
198
199impl Default for LinesCodec {
200 fn default() -> Self {
201 Self::new()
202 }
203}
204
205/// An error occurred while encoding or decoding a line.
206#[derive(Debug)]
207pub enum LinesCodecError {
208 /// The maximum line length was exceeded.
209 MaxLineLengthExceeded,
210 /// An IO error occurred.
211 Io(io::Error),
212}
213
214impl fmt::Display for LinesCodecError {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 match self {
217 LinesCodecError::MaxLineLengthExceeded => write!(f, "max line length exceeded"),
218 LinesCodecError::Io(e) => write!(f, "{e}"),
219 }
220 }
221}
222
223impl From<io::Error> for LinesCodecError {
224 fn from(e: io::Error) -> LinesCodecError {
225 LinesCodecError::Io(e)
226 }
227}
228
229impl std::error::Error for LinesCodecError {}