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!("Writing {} response bytes to the server", response_bytes.len());
96                stream.write_all(response_bytes).await?;
97                return Ok(());
98            } else if len >= self.max_message_size {
99                // Buffer is already at the maximum possible size.
100                return Err(NetError::SerializeError(format!(
101                    "Message too large: {len} > {}",
102                    self.max_message_size
103                )));
104            } else {
105                // Retry with a larger buffer.
106                len = i32::max(self.max_message_size, len.saturating_mul(2));
107                self.write_buf.resize(len as usize, MaybeUninit::uninit());
108            }
109        }
110    }
111
112    #[maybe_async::maybe_async]
113    pub async fn send_response_payload(
114        &mut self,
115        result_status: ResultStatus,
116        result_reason: Option<ResultReason>,
117        result_message: Option<String>,
118        payload: Option<ResponsePayload>,
119    ) -> NetResult<()> {
120        self.send_response(payload_to_response(
121            result_status,
122            result_reason,
123            result_message,
124            payload,
125        )?)
126        .await
127    }
128
129    #[maybe_async::maybe_async]
130    pub async fn send_response_batch(&mut self, batch_items: Vec<response::BatchItem>) -> NetResult<()> {
131        self.send_response(batch_items_to_response(batch_items)?).await
132    }
133}
134
135//------------ Internals -----------------------------------------------------
136
137impl<T: ReadWrite> Server<T> {
138    #[cfg(feature = "tokio")]
139    async fn get_mut_stream(stream: &Mutex<T>) -> NetResult<impl DerefMut<Target = T> + '_> {
140        Ok(stream.lock().await)
141    }
142
143    #[cfg(not(feature = "tokio"))]
144    fn get_mut_stream(stream: &Mutex<T>) -> NetResult<impl DerefMut<Target = T> + '_> {
145        Ok(stream.lock()?)
146    }
147
148    #[maybe_async::maybe_async]
149    async fn read_message_from_stream<F, R>(
150        stream: &mut T,
151        read_buf: &mut Vec<u8>,
152        limit: i32,
153        op: F,
154        connection_error_count: Arc<AtomicUsize>,
155    ) -> NetResult<R>
156    where
157        F: Fn(&mut FastScanner) -> std::result::Result<R, FastScanError>,
158    {
159        trace!("Awaiting KMIP client request");
160        read_buf.clear();
161        loop {
162            // Try reading from the buffer.
163            let available = read_buf.len();
164            let available_rounded = read_buf.len() - available % 8;
165            let ttlv_bytes = &read_buf[..available_rounded];
166            let mut scanner = FastScanner::new(ttlv_bytes).expect("the provided buffer has a multiple of 8 bytes");
167            match scanner.have_next() {
168                Ok(()) => {
169                    trace!(
170                        "Received {available_rounded} bytes from the client: {}",
171                        hex::encode_upper(ttlv_bytes)
172                    );
173                    // A complete TTLV element is available. Try to parse it.
174                    return op(&mut scanner).map_err(|err| NetError::DeserializeError {
175                        err: err.to_string(),
176                        req: Default::default(), // do_requests() will populate this
177                        res: read_buf.clone().into(),
178                    });
179                }
180                Err(Some(n)) => {
181                    // n more bytes are needed to complete the current message
182                    // in the buffer.
183                    Self::enlarge_read_buffer_if_needed(read_buf, n as usize, limit)?;
184                }
185                Err(None) => {
186                    // More bytes are needed to complete the current message
187                    // in the buffer but we don't know how many so fetch at
188                    // least 8 bytes (as TTLV messages are always a multiple
189                    // of 8 bytes and thus FastScanner only accepts multiples
190                    // of 8 bytes).
191                    Self::enlarge_read_buffer_if_needed(read_buf, 8, limit)?;
192                }
193            }
194
195            // The buffer did not contain enough data, try to read more.
196
197            let write_start_idx = available;
198            let updated_buffer_len = read_buf.len();
199            let bytes_to_write_into = &mut read_buf[write_start_idx..updated_buffer_len];
200            let read_byte_count =
201                Self::read_from_stream(stream, bytes_to_write_into, connection_error_count.clone()).await?;
202
203            // Don't pass any extra zeroes in the buffer to the TTLV parser,
204            // only give it bytes that we actually read.
205            read_buf.truncate(write_start_idx + read_byte_count);
206        }
207    }
208
209    fn enlarge_read_buffer_if_needed(read_buf: &mut Vec<u8>, extra_bytes_needed: usize, limit: i32) -> NetResult<()> {
210        // If the buffer is too small, try to expand it.
211        let wanted_buf_size = read_buf.len() + extra_bytes_needed;
212        if wanted_buf_size > read_buf.capacity() && wanted_buf_size > limit as usize {
213            return Err(std::io::Error::new(
214                std::io::ErrorKind::FileTooLarge,
215                format!("Response too large: {wanted_buf_size} bytes > {limit} bytes"),
216            )
217            .into());
218        }
219        read_buf.resize(wanted_buf_size, 0);
220        Ok(())
221    }
222
223    #[maybe_async::maybe_async]
224    async fn read_from_stream(
225        stream: &mut T,
226        buffer: &mut [u8],
227        connection_error_count: Arc<AtomicUsize>,
228    ) -> NetResult<usize> {
229        trace!("Reading upto {} bytes from the KMIP server", buffer.len());
230        match stream.read(buffer).await {
231            // The client has closed the connection.
232            Ok(0) => Err(NetError::IoError(std::io::ErrorKind::ConnectionAborted.into())),
233
234            // Some data was received successfully.
235            Ok(amt) => {
236                trace!("Read {amt} bytes from the KMIP server");
237                Ok(amt)
238            }
239
240            Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {
241                // This is a recoverable error.
242                trace!("KMIP server connection interrupted, continuing.");
243                Ok(0)
244            }
245
246            // An unexpected error has occurred.
247            Err(err) => {
248                let _ = connection_error_count.fetch_add(1, Ordering::SeqCst);
249                // TODO: Categorize the various std::io::ErrorKinds into fatal and
250                // non-fatal variants and only abort on fatal errors.
251                Err(NetError::IoError(err))
252            }
253        }
254    }
255}
256
257impl<T: ReadWrite> Clone for Server<T> {
258    fn clone(&self) -> Self {
259        Self {
260            auth: self.auth.clone(),
261            max_message_size: self.max_message_size,
262            stream: self.stream.clone(),
263            connection_error_count: self.connection_error_count.clone(),
264            read_buf: vec![0u8; 8192],
265            write_buf: vec![MaybeUninit::uninit(); 8192],
266        }
267    }
268}
269
270impl<T: ReadWrite> Server<T> {
271    /// Get the count of connection errors experienced by this Client.
272    pub fn connection_error_count(&self) -> usize {
273        self.connection_error_count.load(Ordering::SeqCst)
274    }
275}