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    read_any_document_with_query_limits(reader, limits, None)
280}
281
282/// Checked workspaces bound framing and decoding before constructing the AST.
283/// The original public transport API retains its configured limits.
284pub(crate) fn read_any_document_with_query_limits(
285    reader: &mut dyn BufRead,
286    limits: &ProtocolLimits,
287    query_limits: Option<crate::query_options::QueryLimits>,
288) -> ProtocolResult<Option<(LinoDocument, MessageFormat)>> {
289    let mut limits = *limits;
290    if let Some(query) = query_limits {
291        limits.max_text_bytes = limits.max_text_bytes.min(query.max_bytes);
292        limits.binary.max_depth = limits.binary.max_depth.min(query.max_depth);
293        limits.binary.max_nodes = limits.binary.max_nodes.min(query.max_nodes);
294        limits.binary.max_string_bytes = limits.binary.max_string_bytes.min(query.max_bytes);
295        let max_nodes = u64::try_from(query.max_nodes).unwrap_or(u64::MAX);
296        limits.binary.max_links = limits.binary.max_links.min(max_nodes);
297        limits.binary.max_references = limits.binary.max_references.min(max_nodes);
298    }
299    let Some(&first) = reader.fill_buf()?.first() else {
300        return Ok(None);
301    };
302    if !is_binary_start(first) {
303        let text = TextLinoProtocol {
304            max_text_bytes: limits.max_text_bytes,
305        };
306        return Ok(text
307            .read_text(reader)?
308            .map(|text| match query_limits {
309                Some(query) => super::server::parse_document_with_limits(&text, query),
310                None => parse_document(&text).map_err(ProtocolError::from),
311            })
312            .transpose()?
313            .map(|document| (document, MessageFormat::Text)));
314    }
315    LinksPacket::read_from(reader, &limits.binary)?
316        .map(|packet| {
317            let document = decode_document(&packet, &limits.binary)?;
318            Ok((
319                document,
320                MessageFormat::Binary(BinaryLinoOptions::of_packet(&packet)),
321            ))
322        })
323        .transpose()
324}
325
326/// A byte stream decorated with a [`LinoProtocol`].
327#[derive(Debug)]
328pub struct LinoConnection<S: Read + Write, P: LinoProtocol> {
329    stream: BufReader<S>,
330    protocol: P,
331}
332
333impl<S: Read + Write, P: LinoProtocol> LinoConnection<S, P> {
334    /// Wraps `stream`.
335    pub fn new(stream: S, protocol: P) -> Self {
336        Self {
337            stream: BufReader::new(stream),
338            protocol,
339        }
340    }
341
342    /// The protocol in use.
343    pub fn protocol(&self) -> &P {
344        &self.protocol
345    }
346
347    /// Sends one document.
348    pub fn send(&mut self, document: &[LiNo<String>]) -> ProtocolResult<()> {
349        let mut buffer = Vec::new();
350        self.protocol.write_document(&mut buffer, document)?;
351        let stream = self.stream.get_mut();
352        stream.write_all(&buffer)?;
353        stream.flush()?;
354        Ok(())
355    }
356
357    /// Receives one document; `Ok(None)` when the peer closed the stream.
358    pub fn receive(&mut self) -> ProtocolResult<Option<LinoDocument>> {
359        self.protocol.read_document(&mut self.stream)
360    }
361
362    /// Sends `document` and waits for the reply.
363    pub fn request(&mut self, document: &[LiNo<String>]) -> ProtocolResult<LinoDocument> {
364        self.send(document)?;
365        self.receive()?
366            .ok_or_else(|| ProtocolError::malformed("connection closed before the reply"))
367    }
368
369    /// Unwraps the underlying stream.
370    pub fn into_inner(self) -> S {
371        self.stream.into_inner()
372    }
373}
374
375impl<P: LinoProtocol> LinoConnection<TcpStream, P> {
376    /// Waits up to `timeout` for the next message to start arriving; false
377    /// when none did in time. True as well when the peer closed the stream,
378    /// which the next [`receive`](Self::receive) reports.
379    pub fn wait_for_message(&mut self, timeout: Duration) -> ProtocolResult<bool> {
380        if !self.stream.buffer().is_empty() {
381            return Ok(true);
382        }
383        let stream = self.stream.get_ref();
384        let previous = stream.read_timeout()?;
385        // A zero timeout is refused by the socket; the shortest one waits 1 ms.
386        stream.set_read_timeout(Some(timeout.max(Duration::from_millis(1))))?;
387        let arrived = self.stream.fill_buf().map(|_| ());
388        self.stream.get_ref().set_read_timeout(previous)?;
389        match arrived {
390            Ok(()) => Ok(true),
391            Err(error)
392                if matches!(
393                    error.kind(),
394                    io::ErrorKind::WouldBlock
395                        | io::ErrorKind::TimedOut
396                        | io::ErrorKind::Interrupted
397                ) =>
398            {
399                Ok(false)
400            }
401            Err(error) => Err(error.into()),
402        }
403    }
404}