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
//!
//! IPP client
//!
use std::{borrow::Cow, fs, io, path::PathBuf, time::Duration};

use futures::{future::IntoFuture, Future, Stream};
use log::debug;
use num_traits::FromPrimitive;
use reqwest::{
    r#async::{Chunk, Client},
    Certificate,
};
use url::Url;

use ipp_proto::{
    attribute::{PRINTER_STATE, PRINTER_STATE_REASONS},
    ipp::{self, DelimiterTag, PrinterState},
    operation::IppOperation,
    request::IppRequestResponse,
    AsyncIppParser, IppAttributes, IppOperationBuilder,
};

use crate::IppError;

const ERROR_STATES: &[&str] = &[
    "media-jam",
    "toner-empty",
    "spool-area-full",
    "cover-open",
    "door-open",
    "input-tray-missing",
    "output-tray-missing",
    "marker-supply-empty",
    "paused",
    "shutdown",
];

fn parse_uri(uri: String) -> impl Future<Item = Url, Error = IppError> {
    futures::lazy(move || match Url::parse(&uri) {
        Ok(mut url) => {
            match url.scheme() {
                "ipp" => {
                    url.set_scheme("http").unwrap();
                    if url.port().is_none() {
                        url.set_port(Some(631)).unwrap();
                    }
                }
                "ipps" => {
                    url.set_scheme("https").unwrap();
                    if url.port().is_none() {
                        url.set_port(Some(443)).unwrap();
                    }
                }
                _ => {}
            }
            Ok(url)
        }
        Err(e) => Err(IppError::ParamError(e.to_string())),
    })
}

fn to_device_uri(uri: &str) -> Cow<str> {
    match Url::parse(&uri) {
        Ok(ref mut url) if !url.username().is_empty() => {
            let _ = url.set_username("");
            let _ = url.set_password(None);
            Cow::Owned(url.to_string())
        }
        _ => Cow::Borrowed(uri),
    }
}

fn parse_certs(certs: Vec<PathBuf>) -> impl Future<Item = Vec<Certificate>, Error = IppError> {
    futures::lazy(move || {
        let mut result = Vec::new();

        for cert_file in certs {
            let buf = match fs::read(&cert_file) {
                Ok(buf) => buf,
                Err(e) => return Err(IppError::from(e)),
            };
            let ca_cert = match Certificate::from_der(&buf).or_else(|_| Certificate::from_pem(&buf)) {
                Ok(ca_cert) => ca_cert,
                Err(e) => return Err(IppError::from(e)),
            };
            result.push(ca_cert);
        }
        Ok(result)
    })
}

/// IPP client.
///
/// IPP client is responsible for sending requests to IPP server.
pub struct IppClient {
    pub(crate) uri: String,
    pub(crate) ca_certs: Vec<PathBuf>,
    pub(crate) verify_hostname: bool,
    pub(crate) verify_certificate: bool,
    pub(crate) timeout: u64,
}

impl IppClient {
    /// Check printer ready status
    pub fn check_ready(&self) -> impl Future<Item = (), Error = IppError> {
        debug!("Checking printer status");
        let operation = IppOperationBuilder::get_printer_attributes()
            .attributes(&[PRINTER_STATE, PRINTER_STATE_REASONS])
            .build();

        self.send(operation).and_then(|attrs| {
            let state = attrs
                .groups_of(DelimiterTag::PrinterAttributes)
                .get(0)
                .and_then(|g| g.attributes().get(PRINTER_STATE))
                .and_then(|attr| attr.value().as_enum())
                .and_then(|v| PrinterState::from_i32(*v));

            if let Some(PrinterState::Stopped) = state {
                debug!("Printer is stopped");
                return Err(IppError::PrinterStopped);
            }

            if let Some(reasons) = attrs
                .groups_of(DelimiterTag::PrinterAttributes)
                .get(0)
                .and_then(|g| g.attributes().get(PRINTER_STATE_REASONS))
            {
                let keywords = reasons
                    .value()
                    .into_iter()
                    .filter_map(|e| e.as_keyword())
                    .map(ToOwned::to_owned)
                    .collect::<Vec<_>>();

                if keywords.iter().any(|k| ERROR_STATES.contains(&&k[..])) {
                    debug!("Printer is in error state: {:?}", keywords);
                    return Err(IppError::PrinterStateError(keywords.clone()));
                }
            }
            Ok(())
        })
    }

    /// send IPP operation
    pub fn send<T>(&self, operation: T) -> impl Future<Item = IppAttributes, Error = IppError>
    where
        T: IppOperation,
    {
        debug!("Sending IPP operation");
        self.send_request(operation.into_ipp_request(&to_device_uri(&self.uri)))
            .and_then(|resp| {
                if resp.header().operation_status > 2 {
                    // IPP error
                    Err(IppError::StatusError(
                        ipp::StatusCode::from_u16(resp.header().operation_status)
                            .unwrap_or(ipp::StatusCode::ServerErrorInternalError),
                    ))
                } else {
                    Ok(resp.attributes().clone())
                }
            })
    }

    /// Send request and return response
    pub fn send_request(
        &self,
        request: IppRequestResponse,
    ) -> impl Future<Item = IppRequestResponse, Error = IppError> + Send {
        // Some printers don't support gzip
        let mut builder = Client::builder().gzip(false).connect_timeout(Duration::from_secs(10));

        if !self.verify_hostname {
            debug!("Disabling hostname verification!");
            builder = builder.danger_accept_invalid_hostnames(true);
        }

        if !self.verify_certificate {
            debug!("Disabling certificate verification!");
            builder = builder.danger_accept_invalid_certs(true);
        }

        if self.timeout > 0 {
            debug!("Setting timeout to {}", self.timeout);
            builder = builder.timeout(Duration::from_secs(self.timeout));
        }

        let uri = self.uri.clone();
        let ca_certs = self.ca_certs.clone();

        parse_uri(uri).and_then(|url| {
            parse_certs(ca_certs).and_then(|certs| {
                builder = certs
                    .into_iter()
                    .fold(builder, |builder, ca_cert| builder.add_root_certificate(ca_cert));

                builder
                    .build()
                    .into_future()
                    .and_then(move |client| {
                        let mut builder = client
                            .post(url.clone())
                            .header("Content-Type", "application/ipp")
                            .body(request.into_stream());

                        if !url.username().is_empty() {
                            debug!("Setting basic auth: {} ****", url.username());
                            builder = builder.basic_auth(
                                url.username(),
                                url.password()
                                    .map(|p| percent_encoding::percent_decode(p.as_bytes()).decode_utf8().unwrap()),
                            );
                        }

                        builder.send()
                    })
                    .and_then(|response| response.error_for_status())
                    .map_err(IppError::HttpError)
                    .and_then(|response| {
                        let stream: Box<dyn Stream<Item = Chunk, Error = io::Error> + Send> = Box::new(
                            response
                                .into_body()
                                .map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string())),
                        );

                        AsyncIppParser::from(stream)
                            .map_err(IppError::from)
                            .map(IppRequestResponse::from_parse_result)
                    })
            })
        })
    }
}