Skip to main content

kmip_protocol/net/server/
builder.rs

1use std::{mem::MaybeUninit, sync::Arc};
2
3#[cfg(feature = "tokio")]
4use tokio::sync::Mutex;
5
6#[cfg(not(feature = "tokio"))]
7use std::sync::Mutex;
8
9use crate::{
10    net::server::Server,
11    types::{
12        request::{Authentication, CredentialValue, Password, Username},
13        traits::ReadWrite,
14    },
15};
16
17/// Use this builder to construct a [Server] struct.
18#[derive(Debug)]
19pub struct ServerBuilder<T: ReadWrite> {
20    stream: T,
21    auth: Option<Authentication>,
22    max_messagesize: i32,
23}
24
25impl<T: ReadWrite> ServerBuilder<T> {
26    /// Build a [Server] struct that will read/write from/to the given stream.
27    ///
28    /// Creates a [ServerBuilder] which can be used to create a [Server] which
29    /// will read/write from/to the given stream. The stream is expected to be
30    /// a type which can read from and write to an established TCP connection
31    /// to the KMIP server. In production the stream should also perform TLS
32    /// de/encryption on the data read from/written to the stream.
33    ///
34    /// The `stream` argument must implement the read and write traits which
35    /// the [Server] will use to read/write from/to the stream.
36    pub fn new(stream: T) -> Self {
37        Self {
38            stream,
39            auth: None,
40            max_messagesize: i32::MAX,
41        }
42    }
43
44    /// Configure the [Server] to include username/password authentication
45    /// credentials in KMIP requests, or the server to require requests to
46    /// be authenticated with the given credentials.
47    pub fn with_credentials(mut self, username: String, password: Option<String>) -> Self {
48        self.auth = Some(Authentication::build(CredentialValue::UsernameAndPassword(
49            Username(username),
50            password.map(Password),
51        )));
52        self
53    }
54
55    /// Configure the [Server] or server to reject messages above a certain size.
56    pub fn with_max_message_size(mut self, max: i32) -> Self {
57        self.max_messagesize = max;
58        self
59    }
60
61    /// Build the configured [Server] struct instance.
62    pub fn build(self) -> Server<T> {
63        let auth = self.auth;
64        let stream = Arc::new(Mutex::new(self.stream));
65        let max_message_size = self.max_messagesize;
66        let read_buf = vec![0u8; 8192];
67        let write_buf = vec![MaybeUninit::uninit(); 8192];
68        let connection_error_count = Default::default();
69
70        Server {
71            auth,
72            max_message_size,
73            stream,
74            read_buf,
75            write_buf,
76            connection_error_count,
77        }
78    }
79}