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