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