Skip to main content

link_cli/protocol/
protocols.rs

1//! Interchangeable message protocols for LiNo documents.
2//!
3//! Both [`TextLinoProtocol`] and [`BinaryLinoProtocol`] implement
4//! [`LinoProtocol`], so code written against the trait switches between them
5//! by swapping one value. [`LinoConnection`] decorates any byte stream (a
6//! `TcpStream`, a pipe, an in-memory buffer) with a protocol.
7
8use super::error::{ProtocolError, ProtocolResult};
9use links_notation::binary::packet::BINARY_VERSION_1;
10use links_notation::binary::{
11    decode_document, encode_document_with_limits, format_document, parse_document,
12    BinaryLinoOptions, DecodeLimits, LinksPacket, LinoDocument,
13};
14use links_notation::LiNo;
15use std::fmt::Debug;
16use std::io::{self, BufRead, BufReader, Read, Write};
17use std::net::TcpStream;
18use std::time::Duration;
19
20/// Reads and writes whole LiNo documents on a byte stream.
21pub trait LinoProtocol: Debug + Send + Sync {
22    /// Writes one message carrying `document`.
23    fn write_document(
24        &self,
25        writer: &mut dyn Write,
26        document: &[LiNo<String>],
27    ) -> ProtocolResult<()>;
28
29    /// Reads one message; `Ok(None)` when the stream ended cleanly.
30    fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>>;
31}
32
33impl<P: LinoProtocol + ?Sized> LinoProtocol for Box<P> {
34    fn write_document(
35        &self,
36        writer: &mut dyn Write,
37        document: &[LiNo<String>],
38    ) -> ProtocolResult<()> {
39        (**self).write_document(writer, document)
40    }
41
42    fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
43        (**self).read_document(reader)
44    }
45}
46
47/// The default limit of a text message: 64 MiB.
48pub const DEFAULT_MAX_TEXT_BYTES: usize = 64 << 20;
49
50/// Limits applied to incoming messages of either protocol.
51///
52/// The binary limits belong to links-notation; the text limit is link-cli's
53/// own, because framing text messages is part of the transport, not of the
54/// notation.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub struct ProtocolLimits {
57    /// Limits of [`BinaryLinoProtocol`] messages.
58    pub binary: DecodeLimits,
59    /// Maximum size of a [`TextLinoProtocol`] message in bytes.
60    pub max_text_bytes: usize,
61}
62
63impl Default for ProtocolLimits {
64    fn default() -> Self {
65        Self {
66            binary: DecodeLimits::default(),
67            max_text_bytes: DEFAULT_MAX_TEXT_BYTES,
68        }
69    }
70}
71
72impl ProtocolLimits {
73    /// Limits for trusted input: only the address space bounds a message.
74    pub fn unlimited() -> Self {
75        Self {
76            binary: DecodeLimits::unlimited(),
77            max_text_bytes: usize::MAX,
78        }
79    }
80}
81
82/// UTF-8 LiNo text, one message per block of lines ended by a line holding
83/// only `.`. Lines starting with `.` get one extra `.` (SMTP dot-stuffing).
84///
85/// Lines may end with `\n` or `\r\n`; a carriage return right before a line
86/// feed is dropped in legacy quoted input. The formatter uses lossless `~1{hex}`
87/// literals for control characters, preserving `\r\n` inside references.
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub struct TextLinoProtocol {
90    /// Maximum size of a message read, in bytes.
91    pub max_text_bytes: usize,
92}
93
94impl Default for TextLinoProtocol {
95    fn default() -> Self {
96        Self {
97            max_text_bytes: DEFAULT_MAX_TEXT_BYTES,
98        }
99    }
100}
101
102impl TextLinoProtocol {
103    /// A text protocol with default limits.
104    pub fn new() -> Self {
105        Self::default()
106    }
107
108    /// Frames already formatted LiNo text as one message.
109    pub fn write_text(writer: &mut dyn Write, text: &str) -> ProtocolResult<()> {
110        let mut out = String::with_capacity(text.len() + 4);
111        if !text.is_empty() {
112            for line in text.split('\n') {
113                if line.starts_with('.') {
114                    out.push('.');
115                }
116                out.push_str(line);
117                out.push('\n');
118            }
119        }
120        out.push_str(".\n");
121        writer.write_all(out.as_bytes())?;
122        writer.flush()?;
123        Ok(())
124    }
125
126    /// Reads one framed message as raw text, without parsing it.
127    pub fn read_text(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<String>> {
128        let mut text = Vec::new();
129        let mut line = Vec::new();
130        let mut first = true;
131        loop {
132            line.clear();
133            let budget = self.max_text_bytes.saturating_sub(text.len()) as u64 + 2;
134            let read = reader.take(budget).read_until(b'\n', &mut line)?;
135            if read == 0 {
136                if first {
137                    return Ok(None);
138                }
139                return Err(ProtocolError::malformed(
140                    "stream ended before the '.' terminator line",
141                ));
142            }
143            if line.last() != Some(&b'\n') {
144                if read as u64 >= budget {
145                    return Err(ProtocolError::LimitExceeded(format!(
146                        "text message longer than {} bytes",
147                        self.max_text_bytes
148                    )));
149                }
150                return Err(ProtocolError::malformed(
151                    "stream ended before the '.' terminator line",
152                ));
153            }
154            line.pop();
155            // CRLF line endings (telnet, netcat on Windows) are accepted.
156            if line.last() == Some(&b'\r') {
157                line.pop();
158            }
159            if line == b"." {
160                break;
161            }
162            if !first {
163                text.push(b'\n');
164            }
165            first = false;
166            let content = line.strip_prefix(b".").unwrap_or(&line);
167            text.extend_from_slice(content);
168        }
169        String::from_utf8(text)
170            .map(Some)
171            .map_err(|_| ProtocolError::malformed("text message is not valid UTF-8"))
172    }
173}
174
175impl LinoProtocol for TextLinoProtocol {
176    fn write_document(
177        &self,
178        writer: &mut dyn Write,
179        document: &[LiNo<String>],
180    ) -> ProtocolResult<()> {
181        Self::write_text(writer, &format_document(document))
182    }
183
184    fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
185        self.read_text(reader)?
186            .map(|text| parse_document(&text).map_err(ProtocolError::from))
187            .transpose()
188    }
189}
190
191/// Binary links packets of [`links_notation::binary`]; every message is
192/// self-delimiting, so no extra framing is needed.
193#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
194pub struct BinaryLinoProtocol {
195    /// Optional features used when writing.
196    pub options: BinaryLinoOptions,
197    /// Limits applied when reading, and checked when writing.
198    pub limits: DecodeLimits,
199}
200
201impl BinaryLinoProtocol {
202    /// A binary protocol with every optional feature off.
203    pub fn new() -> Self {
204        Self::default()
205    }
206
207    /// A binary protocol with the given optional features.
208    pub fn with_options(options: BinaryLinoOptions) -> Self {
209        Self {
210            options,
211            ..Self::default()
212        }
213    }
214
215    /// Encodes a document into packet bytes.
216    pub fn encode(&self, document: &[LiNo<String>]) -> ProtocolResult<Vec<u8>> {
217        Ok(encode_document_with_limits(document, self.options, &self.limits)?.to_bytes()?)
218    }
219
220    /// Decodes packet bytes into a document.
221    pub fn decode(&self, bytes: &[u8]) -> ProtocolResult<LinoDocument> {
222        let packet = LinksPacket::from_bytes(bytes, &self.limits)?;
223        Ok(decode_document(&packet, &self.limits)?)
224    }
225}
226
227impl LinoProtocol for BinaryLinoProtocol {
228    fn write_document(
229        &self,
230        writer: &mut dyn Write,
231        document: &[LiNo<String>],
232    ) -> ProtocolResult<()> {
233        writer.write_all(&self.encode(document)?)?;
234        writer.flush()?;
235        Ok(())
236    }
237
238    fn read_document(&self, reader: &mut dyn BufRead) -> ProtocolResult<Option<LinoDocument>> {
239        LinksPacket::read_from(reader, &self.limits)?
240            .map(|packet| Ok(decode_document(&packet, &self.limits)?))
241            .transpose()
242    }
243}
244
245/// The wire format a message arrived in, so a reply can use the same one.
246#[derive(Clone, Copy, Debug, PartialEq, Eq)]
247pub enum MessageFormat {
248    /// [`TextLinoProtocol`].
249    Text,
250    /// [`BinaryLinoProtocol`] with the options read from the packet header.
251    Binary(BinaryLinoOptions),
252}
253
254impl MessageFormat {
255    /// A protocol that writes messages in this format.
256    pub fn protocol(self, limits: ProtocolLimits) -> Box<dyn LinoProtocol> {
257        match self {
258            MessageFormat::Text => Box::new(TextLinoProtocol {
259                max_text_bytes: limits.max_text_bytes,
260            }),
261            MessageFormat::Binary(options) => Box::new(BinaryLinoProtocol {
262                options,
263                limits: limits.binary,
264            }),
265        }
266    }
267}
268
269/// True when `byte` starts a binary message rather than a text one.
270pub fn is_binary_start(byte: u8) -> bool {
271    byte & 0xF0 == BINARY_VERSION_1
272}
273
274/// Reads one message in whichever protocol the peer used.
275pub fn read_any_document(
276    reader: &mut dyn BufRead,
277    limits: &ProtocolLimits,
278) -> ProtocolResult<Option<(LinoDocument, MessageFormat)>> {
279    let Some(&first) = reader.fill_buf()?.first() else {
280        return Ok(None);
281    };
282    if !is_binary_start(first) {
283        let text = TextLinoProtocol {
284            max_text_bytes: limits.max_text_bytes,
285        };
286        return Ok(text
287            .read_document(reader)?
288            .map(|document| (document, MessageFormat::Text)));
289    }
290    LinksPacket::read_from(reader, &limits.binary)?
291        .map(|packet| {
292            let document = decode_document(&packet, &limits.binary)?;
293            Ok((
294                document,
295                MessageFormat::Binary(BinaryLinoOptions::of_packet(&packet)),
296            ))
297        })
298        .transpose()
299}
300
301/// A byte stream decorated with a [`LinoProtocol`].
302#[derive(Debug)]
303pub struct LinoConnection<S: Read + Write, P: LinoProtocol> {
304    stream: BufReader<S>,
305    protocol: P,
306}
307
308impl<S: Read + Write, P: LinoProtocol> LinoConnection<S, P> {
309    /// Wraps `stream`.
310    pub fn new(stream: S, protocol: P) -> Self {
311        Self {
312            stream: BufReader::new(stream),
313            protocol,
314        }
315    }
316
317    /// The protocol in use.
318    pub fn protocol(&self) -> &P {
319        &self.protocol
320    }
321
322    /// Sends one document.
323    pub fn send(&mut self, document: &[LiNo<String>]) -> ProtocolResult<()> {
324        let mut buffer = Vec::new();
325        self.protocol.write_document(&mut buffer, document)?;
326        let stream = self.stream.get_mut();
327        stream.write_all(&buffer)?;
328        stream.flush()?;
329        Ok(())
330    }
331
332    /// Receives one document; `Ok(None)` when the peer closed the stream.
333    pub fn receive(&mut self) -> ProtocolResult<Option<LinoDocument>> {
334        self.protocol.read_document(&mut self.stream)
335    }
336
337    /// Sends `document` and waits for the reply.
338    pub fn request(&mut self, document: &[LiNo<String>]) -> ProtocolResult<LinoDocument> {
339        self.send(document)?;
340        self.receive()?
341            .ok_or_else(|| ProtocolError::malformed("connection closed before the reply"))
342    }
343
344    /// Unwraps the underlying stream.
345    pub fn into_inner(self) -> S {
346        self.stream.into_inner()
347    }
348}
349
350impl<P: LinoProtocol> LinoConnection<TcpStream, P> {
351    /// Waits up to `timeout` for the next message to start arriving; false
352    /// when none did in time. True as well when the peer closed the stream,
353    /// which the next [`receive`](Self::receive) reports.
354    pub fn wait_for_message(&mut self, timeout: Duration) -> ProtocolResult<bool> {
355        if !self.stream.buffer().is_empty() {
356            return Ok(true);
357        }
358        let stream = self.stream.get_ref();
359        let previous = stream.read_timeout()?;
360        // A zero timeout is refused by the socket; the shortest one waits 1 ms.
361        stream.set_read_timeout(Some(timeout.max(Duration::from_millis(1))))?;
362        let arrived = self.stream.fill_buf().map(|_| ());
363        self.stream.get_ref().set_read_timeout(previous)?;
364        match arrived {
365            Ok(()) => Ok(true),
366            Err(error)
367                if matches!(
368                    error.kind(),
369                    io::ErrorKind::WouldBlock
370                        | io::ErrorKind::TimedOut
371                        | io::ErrorKind::Interrupted
372                ) =>
373            {
374                Ok(false)
375            }
376            Err(error) => Err(error.into()),
377        }
378    }
379}