1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
//!
//! IPP client
//!
use std::{collections::BTreeMap, marker::PhantomData, time::Duration};

use base64::Engine;
use http::Uri;

const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

fn ipp_uri_to_string(uri: &Uri) -> String {
    let (scheme, default_port) = match uri.scheme_str() {
        Some("ipps") => ("https", 443),
        Some("ipp") => ("http", 631),
        _ => return uri.to_string(),
    };

    let authority = match uri.authority() {
        Some(authority) => {
            if authority.port_u16().is_some() {
                authority.to_string()
            } else {
                format!("{}:{}", authority, default_port)
            }
        }
        None => return uri.to_string(),
    };

    let path_and_query = uri.path_and_query().map(|p| p.as_str()).unwrap_or_default();

    format!("{}://{}{}", scheme, authority, path_and_query)
}

/// Builder to create IPP client
pub struct IppClientBuilder<T> {
    uri: Uri,
    ignore_tls_errors: bool,
    request_timeout: Option<Duration>,
    headers: BTreeMap<String, String>,
    ca_certs: Vec<Vec<u8>>,
    _phantom_data: PhantomData<T>,
}

impl<T> IppClientBuilder<T> {
    fn new(uri: Uri) -> Self {
        IppClientBuilder {
            uri,
            ignore_tls_errors: false,
            request_timeout: None,
            headers: BTreeMap::new(),
            ca_certs: Vec::new(),
            _phantom_data: PhantomData,
        }
    }

    /// Enable or disable ignoring of TLS handshake errors. Default is false.
    pub fn ignore_tls_errors(mut self, flag: bool) -> Self {
        self.ignore_tls_errors = flag;
        self
    }

    /// Add custom root certificate in PEM or DER format.
    pub fn ca_cert<D: AsRef<[u8]>>(mut self, data: D) -> Self {
        self.ca_certs.push(data.as_ref().to_owned());
        self
    }

    /// Set network request timeout. Default is no timeout.
    pub fn request_timeout(mut self, duration: Duration) -> Self {
        self.request_timeout = Some(duration);
        self
    }

    /// Add custom HTTP header
    pub fn http_header<K, V>(mut self, key: K, value: V) -> Self
    where
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.headers.insert(key.as_ref().to_owned(), value.as_ref().to_owned());
        self
    }

    /// Add basic auth header (RFC 7617)
    pub fn basic_auth<U, P>(mut self, username: U, password: P) -> Self
    where
        U: AsRef<str>,
        P: AsRef<str>,
    {
        let authz =
            base64::engine::general_purpose::STANDARD.encode(format!("{}:{}", username.as_ref(), password.as_ref()));
        self.headers
            .insert("authorization".to_owned(), format!("Basic {authz}"));
        self
    }
}

#[cfg(feature = "async-client")]
impl IppClientBuilder<non_blocking::AsyncIppClient> {
    /// Build the async client
    pub fn build(self) -> non_blocking::AsyncIppClient {
        non_blocking::AsyncIppClient(self)
    }
}

#[cfg(feature = "client")]
impl IppClientBuilder<blocking::IppClient> {
    /// Build the blocking client
    pub fn build(self) -> blocking::IppClient {
        blocking::IppClient(self)
    }
}

#[cfg(feature = "async-client")]
pub mod non_blocking {
    use std::io;

    use futures_util::{io::BufReader, stream::TryStreamExt};
    use http::Uri;
    use reqwest::{Body, ClientBuilder};
    use tokio_util::compat::FuturesAsyncReadCompatExt;

    use crate::{error::IppError, parser::AsyncIppParser, request::IppRequestResponse};

    use super::{ipp_uri_to_string, IppClientBuilder, CONNECT_TIMEOUT};

    const USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"), ";reqwest");

    /// Asynchronous IPP client.
    ///
    /// IPP client is responsible for sending requests to IPP server.
    pub struct AsyncIppClient(pub(super) IppClientBuilder<Self>);

    impl AsyncIppClient {
        /// Create IPP client with default options
        pub fn new(uri: Uri) -> Self {
            AsyncIppClient(AsyncIppClient::builder(uri))
        }

        /// Create IPP client builder for setting extra options
        pub fn builder(uri: Uri) -> IppClientBuilder<Self> {
            IppClientBuilder::new(uri)
        }

        /// Return client URI
        pub fn uri(&self) -> &Uri {
            &self.0.uri
        }

        /// Send IPP request to the server
        pub async fn send<R>(&self, request: R) -> Result<IppRequestResponse, IppError>
        where
            R: Into<IppRequestResponse>,
        {
            let mut builder = ClientBuilder::new().connect_timeout(CONNECT_TIMEOUT);

            if let Some(timeout) = self.0.request_timeout {
                builder = builder.timeout(timeout);
            }

            #[cfg(feature = "async-client-tls")]
            {
                if self.0.ignore_tls_errors {
                    builder = builder
                        .danger_accept_invalid_hostnames(true)
                        .danger_accept_invalid_certs(true);
                }
                for data in &self.0.ca_certs {
                    let cert =
                        reqwest::Certificate::from_pem(data).or_else(|_| reqwest::Certificate::from_der(data))?;
                    builder = builder.add_root_certificate(cert);
                }
            }

            let mut req_builder = builder
                .user_agent(USER_AGENT)
                .build()?
                .post(ipp_uri_to_string(&self.0.uri));

            for (k, v) in &self.0.headers {
                req_builder = req_builder.header(k, v);
            }

            let response = req_builder
                .header("content-type", "application/ipp")
                .body(Body::wrap_stream(tokio_util::io::ReaderStream::new(
                    request.into().into_async_read().compat(),
                )))
                .send()
                .await?;

            if response.status().is_success() {
                let parser = AsyncIppParser::new(BufReader::new(
                    response
                        .bytes_stream()
                        .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
                        .into_async_read(),
                ));
                parser.parse().await.map_err(IppError::from)
            } else {
                Err(IppError::RequestError(response.status().as_u16()))
            }
        }
    }
}

#[cfg(feature = "client")]
pub mod blocking {
    use http::Uri;
    use ureq::AgentBuilder;

    use crate::{error::IppError, parser::IppParser, reader::IppReader, request::IppRequestResponse};

    use super::{ipp_uri_to_string, IppClientBuilder, CONNECT_TIMEOUT};

    const USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"), ";ureq");

    /// Blocking IPP client.
    ///
    /// IPP client is responsible for sending requests to IPP server.
    pub struct IppClient(pub(super) IppClientBuilder<Self>);

    impl IppClient {
        /// Create IPP client with default options
        pub fn new(uri: Uri) -> Self {
            IppClient(IppClient::builder(uri))
        }

        /// Create IPP client builder for setting extra options
        pub fn builder(uri: Uri) -> IppClientBuilder<Self> {
            IppClientBuilder::new(uri)
        }

        /// Return client URI
        pub fn uri(&self) -> &Uri {
            &self.0.uri
        }

        /// Send IPP request to the server
        pub fn send<R>(&self, request: R) -> Result<IppRequestResponse, IppError>
        where
            R: Into<IppRequestResponse>,
        {
            let mut builder = AgentBuilder::new().timeout_connect(CONNECT_TIMEOUT);

            if let Some(timeout) = self.0.request_timeout {
                builder = builder.timeout(timeout);
            }

            #[cfg(feature = "client-tls")]
            {
                let mut tls_builder = native_tls::TlsConnector::builder();

                tls_builder
                    .danger_accept_invalid_hostnames(self.0.ignore_tls_errors)
                    .danger_accept_invalid_certs(self.0.ignore_tls_errors);

                for data in &self.0.ca_certs {
                    let cert =
                        native_tls::Certificate::from_pem(data).or_else(|_| native_tls::Certificate::from_der(data))?;
                    tls_builder.add_root_certificate(cert);
                }

                let tls_connector = tls_builder.build()?;
                builder = builder.tls_connector(std::sync::Arc::new(tls_connector));
            }

            let agent = builder.user_agent(USER_AGENT).build();

            let mut req = agent
                .post(&ipp_uri_to_string(&self.0.uri))
                .set("content-type", "application/ipp");

            for (k, v) in &self.0.headers {
                req = req.set(k, v);
            }

            let response = req.send(request.into().into_read())?;
            let reader = response.into_reader();
            let parser = IppParser::new(IppReader::new(reader));

            parser.parse().map_err(IppError::from)
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::client::ipp_uri_to_string;
    use http::Uri;

    #[test]
    fn test_ipp_uri_no_port() {
        let uri = "ipp://user:pass@host/path?query=1234".parse::<Uri>().unwrap();
        let http_uri = ipp_uri_to_string(&uri);
        assert_eq!(http_uri, "http://user:pass@host:631/path?query=1234");
    }

    #[test]
    fn test_ipp_uri_with_port() {
        let uri = "ipp://user:pass@host:1000".parse::<Uri>().unwrap();
        let http_uri = ipp_uri_to_string(&uri);
        assert_eq!(http_uri, "http://user:pass@host:1000/");
    }

    #[test]
    fn test_ipps_uri_no_port() {
        let uri = "ipps://host".parse::<Uri>().unwrap();
        let http_uri = ipp_uri_to_string(&uri);
        assert_eq!(http_uri, "https://host:443/");
    }

    #[test]
    fn test_ipps_uri_with_port() {
        let uri = "ipps://host:8443".parse::<Uri>().unwrap();
        let http_uri = ipp_uri_to_string(&uri);
        assert_eq!(http_uri, "https://host:8443/");
    }

    #[test]
    fn test_http_uri_no_change() {
        let uri = "http://somehost".parse::<Uri>().unwrap();
        let http_uri = ipp_uri_to_string(&uri);
        assert_eq!(http_uri, uri.to_string());
    }
}