Skip to main content

kmip_protocol/net/server/
mod.rs

1pub mod builder;
2pub mod tests;
3pub mod util;
4
5use std::{
6    mem::MaybeUninit,
7    ops::DerefMut,
8    sync::{
9        Arc,
10        atomic::{AtomicUsize, Ordering},
11    },
12};
13
14#[cfg(feature = "tokio")]
15use tokio::sync::Mutex;
16
17#[cfg(not(feature = "tokio"))]
18use std::sync::Mutex;
19
20use crate::{
21    net::{NetError, NetResult, batch_items_to_response, payload_to_response},
22    ttlv::{FastScanError, FastScanner},
23    types::{
24        request::{Authentication, RequestMessage},
25        response::{self, ResponseMessage, ResponsePayload, ResultReason, ResultStatus},
26        traits::ReadWrite,
27    },
28};
29
30use tracing::trace;
31
32/// A server for deserializing KMIP requests and serializing KMIP responses
33/// from/to an established read/write stream.
34///
35/// Use the [crate::net::ServerBuilder] to build a [Server] instance to work
36/// with.
37#[derive(Debug)]
38pub struct Server<T: ReadWrite> {
39    auth: Option<Authentication>,
40    max_message_size: i32,
41    stream: Arc<Mutex<T>>,
42    read_buf: Vec<u8>,
43    write_buf: Vec<MaybeUninit<u8>>,
44    connection_error_count: Arc<AtomicUsize>,
45}
46
47//--- Low level server interface
48//
49// For receiving requests and sending responses.
50
51impl<T: ReadWrite> Server<T> {
52    /// Receive a KMIP request from the network.
53    ///
54    /// Unlike do_request() and do_requests() this function only performs the
55    /// receiving half of the message exchange as the caller has to inspect the
56    /// received message and determinate an appropriate response.
57    #[maybe_async::maybe_async]
58    pub async fn receive_request(&mut self) -> NetResult<RequestMessage> {
59        trace!("Acquiring stream lock");
60        let mut lock = Self::get_mut_stream(&self.stream).await?;
61        let stream = lock.deref_mut();
62
63        trace!("Waiting for a request from the client");
64        let req = Self::read_message_from_stream(
65            stream,
66            &mut self.read_buf,
67            self.max_message_size,
68            RequestMessage::fast_scan,
69            self.connection_error_count.clone(),
70        )
71        .await?;
72        drop(lock);
73
74        // Check that the request is correctly authenticated.
75        if self.auth.is_some() && req.header().authentication() != self.auth.as_ref() {
76            return Err(NetError::AuthenticationError);
77        }
78
79        Ok(req)
80    }
81
82    #[maybe_async::maybe_async]
83    pub async fn send_response(&mut self, response: ResponseMessage) -> NetResult<()> {
84        trace!("Serializing response to KMIP wire bytes");
85        let len = self.write_buf.len();
86        assert!(len <= i32::MAX as usize);
87        let mut len = len as i32;
88
89        // TODO: Enforce a timeout on sending the response?
90        loop {
91            let mut formatter = crate::ttlv::Formatter::new(&mut self.write_buf);
92            if response.format(&mut formatter).is_ok() {
93                let response_bytes = formatter.filled().as_flattened();
94                let mut stream = Self::get_mut_stream(&self.stream).await?;
95                trace!(
96                    "Writing {} response bytes to the client: {}",
97                    response_bytes.len(),
98                    hex::encode_upper(response_bytes)
99                );
100                stream.write_all(response_bytes).await?;
101                return Ok(());
102            } else if len >= self.max_message_size {
103                // Buffer is already at the maximum possible size.
104                return Err(NetError::SerializeError(format!(
105                    "Message too large: {len} > {}",
106                    self.max_message_size
107                )));
108            } else {
109                // Retry with a larger buffer.
110                len = i32::max(self.max_message_size, len.saturating_mul(2));
111                self.write_buf.resize(len as usize, MaybeUninit::uninit());
112            }
113        }
114    }
115
116    #[maybe_async::maybe_async]
117    pub async fn send_response_payload(
118        &mut self,
119        result_status: ResultStatus,
120        result_reason: Option<ResultReason>,
121        result_message: Option<String>,
122        payload: Option<ResponsePayload>,
123    ) -> NetResult<()> {
124        self.send_response(payload_to_response(
125            result_status,
126            result_reason,
127            result_message,
128            payload,
129        )?)
130        .await
131    }
132
133    #[maybe_async::maybe_async]
134    pub async fn send_response_batch(&mut self, batch_items: Vec<response::BatchItem>) -> NetResult<()> {
135        self.send_response(batch_items_to_response(batch_items)?).await
136    }
137}
138
139//------------ Internals -----------------------------------------------------
140
141impl<T: ReadWrite> Server<T> {
142    #[cfg(feature = "tokio")]
143    async fn get_mut_stream(stream: &Mutex<T>) -> NetResult<impl DerefMut<Target = T> + '_> {
144        Ok(stream.lock().await)
145    }
146
147    #[cfg(not(feature = "tokio"))]
148    fn get_mut_stream(stream: &Mutex<T>) -> NetResult<impl DerefMut<Target = T> + '_> {
149        Ok(stream.lock()?)
150    }
151
152    #[maybe_async::maybe_async]
153    async fn read_message_from_stream<F, R>(
154        stream: &mut T,
155        read_buf: &mut Vec<u8>,
156        limit: i32,
157        op: F,
158        connection_error_count: Arc<AtomicUsize>,
159    ) -> NetResult<R>
160    where
161        F: Fn(&mut FastScanner) -> std::result::Result<R, FastScanError>,
162    {
163        trace!("Awaiting KMIP client request");
164        read_buf.clear();
165        loop {
166            // Try reading from the buffer.
167            let available = read_buf.len();
168            let available_rounded = read_buf.len() - available % 8;
169            let ttlv_bytes = &read_buf[..available_rounded];
170            let mut scanner = FastScanner::new(ttlv_bytes).expect("the provided buffer has a multiple of 8 bytes");
171            match scanner.have_next() {
172                Ok(()) => {
173                    trace!(
174                        "Received {available_rounded} bytes from the client: {}",
175                        hex::encode_upper(ttlv_bytes)
176                    );
177                    // A complete TTLV element is available. Try to parse it.
178                    return op(&mut scanner).map_err(|err| NetError::DeserializeError {
179                        err: err.to_string(),
180                        req: Default::default(), // do_requests() will populate this
181                        res: read_buf.clone().into(),
182                    });
183                }
184                Err(Some(n)) => {
185                    // n more bytes are needed to complete the current message
186                    // in the buffer.
187                    Self::enlarge_read_buffer_if_needed(read_buf, n as usize, limit)?;
188                }
189                Err(None) => {
190                    // More bytes are needed to complete the current message
191                    // in the buffer but we don't know how many so fetch at
192                    // least 8 bytes (as TTLV messages are always a multiple
193                    // of 8 bytes and thus FastScanner only accepts multiples
194                    // of 8 bytes).
195                    Self::enlarge_read_buffer_if_needed(read_buf, 8, limit)?;
196                }
197            }
198
199            // The buffer did not contain enough data, try to read more.
200
201            let write_start_idx = available;
202            let updated_buffer_len = read_buf.len();
203            let bytes_to_write_into = &mut read_buf[write_start_idx..updated_buffer_len];
204            let read_byte_count =
205                Self::read_from_stream(stream, bytes_to_write_into, connection_error_count.clone()).await?;
206
207            // Don't pass any extra zeroes in the buffer to the TTLV parser,
208            // only give it bytes that we actually read.
209            read_buf.truncate(write_start_idx + read_byte_count);
210        }
211    }
212
213    fn enlarge_read_buffer_if_needed(read_buf: &mut Vec<u8>, extra_bytes_needed: usize, limit: i32) -> NetResult<()> {
214        // If the buffer is too small, try to expand it.
215        let wanted_buf_size = read_buf.len() + extra_bytes_needed;
216        if wanted_buf_size > read_buf.capacity() && wanted_buf_size > limit as usize {
217            return Err(std::io::Error::new(
218                std::io::ErrorKind::FileTooLarge,
219                format!("Response too large: {wanted_buf_size} bytes > {limit} bytes"),
220            )
221            .into());
222        }
223        read_buf.resize(wanted_buf_size, 0);
224        Ok(())
225    }
226
227    #[maybe_async::maybe_async]
228    async fn read_from_stream(
229        stream: &mut T,
230        buffer: &mut [u8],
231        connection_error_count: Arc<AtomicUsize>,
232    ) -> NetResult<usize> {
233        trace!("Reading upto {} bytes from the KMIP server", buffer.len());
234        match stream.read(buffer).await {
235            // The client has closed the connection.
236            Ok(0) => Err(NetError::IoError(std::io::ErrorKind::ConnectionAborted.into())),
237
238            // Some data was received successfully.
239            Ok(amt) => {
240                trace!("Read {amt} bytes from the KMIP server");
241                Ok(amt)
242            }
243
244            Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {
245                // This is a recoverable error.
246                trace!("KMIP server connection interrupted, continuing.");
247                Ok(0)
248            }
249
250            // An unexpected error has occurred.
251            Err(err) => {
252                let _ = connection_error_count.fetch_add(1, Ordering::SeqCst);
253                // TODO: Categorize the various std::io::ErrorKinds into fatal and
254                // non-fatal variants and only abort on fatal errors.
255                Err(NetError::IoError(err))
256            }
257        }
258    }
259}
260
261impl<T: ReadWrite> Clone for Server<T> {
262    fn clone(&self) -> Self {
263        Self {
264            auth: self.auth.clone(),
265            max_message_size: self.max_message_size,
266            stream: self.stream.clone(),
267            connection_error_count: self.connection_error_count.clone(),
268            read_buf: vec![0u8; 8192],
269            write_buf: vec![MaybeUninit::uninit(); 8192],
270        }
271    }
272}
273
274impl<T: ReadWrite> Server<T> {
275    /// Get the count of connection errors experienced by this Client.
276    pub fn connection_error_count(&self) -> usize {
277        self.connection_error_count.load(Ordering::SeqCst)
278    }
279}