1#[cfg(feature = "compression")]
89use std::io::Read;
90use std::sync::Arc;
91use async_trait::async_trait;
92use parking_lot::Mutex;
93use product_os_capabilities::{Feature, RegistryFeature, RegistryService, Service};
94use product_os_request::{Request, Response};
95use product_os_router::{IntoResponse, Body};
96use product_os_utilities::ProductOSError;
97use serde_json::Value;
98#[cfg(feature = "discovery")]
99use zeroconf::prelude::{TEventLoop, TMdnsService};
100#[cfg(feature = "discovery")]
101use zeroconf::ServiceType;
102use crate::constants::*;
103use crate::encoder::{ProductOSIPPGroup, ProductOSIPPObject};
104use crate::groups::IPPGroups;
105use crate::printer::ProductOSIPPPrinter;
106pub use crate::processor::ProductOSIPPProcessor;
107use crate::status_codes::StatusCode;
108use crate::util::IPPUtils;
109
110mod constants;
111mod encoder;
112mod status_codes;
113mod util;
114mod printer;
115mod job;
116mod groups;
117mod printer_handler;
118mod processor;
119
120pub struct ProductOSIPPServer {
154 printer: ProductOSIPPPrinter,
155 is_secure: bool,
156 processor: Arc<dyn ProductOSIPPProcessor>
157}
158
159impl ProductOSIPPServer {
160 pub fn new(name: String, uri: String, port: u16, is_secure: bool, processor: Arc<dyn ProductOSIPPProcessor>) -> Self {
212 Self {
213 printer: ProductOSIPPPrinter::new(name, uri, port),
214 is_secure,
215 processor
216 }
217 }
218
219 #[cfg(feature = "discovery")]
231 pub async fn enable_discovery(&self) {
232 let protocol_name = if self.is_secure { "ipps" } else { "ipp" };
233 let protocol_method = "tcp";
234 let name = self.printer.get_name().to_string();
235 let port = self.printer.get_port();
236
237 tokio::spawn(async move {
238 let service_type = ServiceType::new(protocol_name, protocol_method).unwrap();
239 let mut service = zeroconf::MdnsService::new(service_type, port);
240
241 service.set_name(&name);
242
243 let event_loop = service.register().unwrap();
244
245 loop {
246 event_loop.poll(std::time::Duration::from_secs(30)).unwrap();
247 }
248 });
249 }
250
251 #[cfg(not(feature = "discovery"))]
252 pub async fn enable_discovery(&self) {
253 }
255
256 pub async fn ipp_object_from_request(request: Request<Body>) -> Result<ProductOSIPPObject, ProductOSError> {
257 let request_bytes = match IPPUtils::request_to_bytes(request).await {
258 Ok(bytes) => bytes,
259 Err(e) => return Err(e)
260 };
261
262 let mut ipp_object = match IPPUtils::bytes_to_ipp_object(request_bytes.as_slice()) {
263 Ok(object) => object,
264 Err(e) => return Err(e)
265 };
266
267 match ipp_object.groups.first() {
268 None => Ok(ipp_object),
269 Some(group) => {
270 let compression_value = IPPUtils::get_first_value_for_name(&group.attributes, "compression");
271 let compression = match &compression_value {
272 None => "none",
273 Some(Value::String(s)) => s.as_str(),
274 Some(_) => return Err(ProductOSError::GenericError(String::from("Format problem for compression"))),
275 };
276
277 let data_bytes_decompressed = match compression {
278 "none" => {
279 #[cfg(feature = "logging")]
280 tracing::info!("No decompression of data required");
281 ipp_object.data
282 }
283 #[cfg(feature = "compression")]
284 "deflate" => {
285 #[cfg(feature = "logging")]
286 tracing::info!("Decompression deflate data");
287 let mut decoder = flate2::read::DeflateDecoder::new(ipp_object.data.as_slice());
288 let mut contents = Vec::new();
289 match decoder.read_to_end(&mut contents) {
290 Ok(_content_length) => {
291 contents
292 }
293 Err(error) => {
294 #[cfg(feature = "logging")]
295 tracing::error!("Failed to decompress using Deflate - error: {:?} - {}", error.kind(), error);
296 return Err(ProductOSError::GenericError(format!("Failed to decompress using Deflate - error: {:?}", error)))
297 }
298 }
299 }
300 #[cfg(feature = "compression")]
301 "gzip" => {
302 #[cfg(feature = "logging")]
303 tracing::info!("Decompression gzip data");
304 let mut decoder = flate2::read::GzDecoder::new(ipp_object.data.as_slice());
305 let mut contents = Vec::new();
306 match decoder.read_to_end(&mut contents) {
307 Ok(_content_length) => {
308 contents
309 }
310 Err(error) => {
311 #[cfg(feature = "logging")]
312 tracing::error!("Failed to decompress using Gzip - error: {:?} - {}", error.kind(), error);
313 return Err(ProductOSError::GenericError(format!("Failed to decompress using Gzip - error: {:?}", error)))
314 }
315 }
316 }
317 _ => {
318 return Err(ProductOSError::GenericError(String::from("Compression not supported")));
319 }
320 };
321
322 ipp_object.data = data_bytes_decompressed;
323
324 Ok(ipp_object)
325 }
326 }
327 }
328
329 pub fn send_groups(mut groups: Vec<ProductOSIPPGroup>, status: StatusCode, request_id: Option<u32>) -> Response<Body> {
330 let request_id = request_id.unwrap_or(1);
331
332 let mut response_groups = Vec::with_capacity(groups.len() + 1);
333 response_groups.push(IPPGroups::operation_attributes_tag(status, None));
334
335 for group in &mut groups {
336 if group.tag == OPERATION_ATTRIBUTES_TAG {
337 response_groups[0].attributes.append(&mut group.attributes);
338 }
339 else {
340 response_groups.push(group.clone());
341 }
342 }
343
344 let status_u16 = status as u16;
345
346 let mut response = Vec::new();
347 let response_object = ProductOSIPPObject {
348 version_major: 1,
349 version_minor: 1,
350 operation_id_or_status_code: status_u16,
351 request_id,
352 groups: response_groups,
353 data: Vec::new(),
354 };
355
356 #[cfg(feature = "logging")]
357 tracing::debug!("Sending response: {:?}", response_object);
358
359 match ProductOSIPPObject::encode(response_object, &mut response, None) {
360 Ok(_) => {
361 #[cfg(feature = "logging")]
362 tracing::trace!("Response send success: {:?}", response);
363 Response::builder()
364 .status(product_os_request::StatusCode::OK)
365 .header("content-type", "application/ipp")
366 .header("content-length", response.len())
367 .body(Body::from(response))
368 .unwrap()
369 }
370 Err(e) => {
371 #[cfg(feature = "logging")]
372 tracing::error!("Response send failure: {:?}", e);
373 ProductOSIPPServer::send_error(e, StatusCode::ServerErrorInternalError, Some(request_id))
374 }
375 }
376 }
377
378 pub fn send_error(error: ProductOSError, status: StatusCode, request_id: Option<u32>) -> Response<Body> {
379 let request_id = request_id.unwrap_or(1);
380
381 let response_groups = vec![IPPGroups::operation_attributes_tag(status, Some(error))];
382
383 let status_u16 = status as u16;
384
385 let mut error_response = Vec::new();
386 let response_object = ProductOSIPPObject {
387 version_major: 1,
388 version_minor: 1,
389 operation_id_or_status_code: status_u16,
390 request_id,
391 groups: response_groups,
392 data: Vec::new(),
393 };
394
395 #[cfg(feature = "logging")]
396 tracing::error!("Sending error response: {:?}", response_object);
397
398 ProductOSIPPObject::encode(response_object, &mut error_response, None).unwrap();
399
400 #[cfg(feature = "logging")]
401 tracing::trace!("Response send error: {:?}", error_response);
402 Response::builder()
403 .status(product_os_request::StatusCode::OK)
404 .header("content-type", "application/ipp")
405 .header("content-length", error_response.len())
406 .body(Body::from(error_response))
407 .unwrap()
408 }
409}
410
411#[async_trait]
412impl Feature for ProductOSIPPServer {
413 async fn register(&self, _feature: Arc<dyn Feature>, _base_path: String, _router: &mut product_os_router::ProductOSRouter) -> RegistryFeature {
414 panic!("Immutable IPP Print Server not allowed to be registered")
415 }
416
417 async fn register_mut(&self, _feature: Arc<Mutex<dyn Feature>>, base_path: String, router: &mut product_os_router::ProductOSRouter) -> RegistryFeature {
418 let server_clone = Arc::new(Mutex::new(ProductOSIPPServer {
421 printer: self.printer.clone(),
422 is_secure: self.is_secure,
423 processor: self.processor.clone()
424 }));
425
426 printer_handler::printer_handler_concrete(router, server_clone);
427
428 let path_string = match base_path.as_str() {
429 "" => "/*fallback_path".to_string(),
430 _ => base_path.clone()
431 };
432
433 RegistryFeature {
434 identifier: "IPPServer".to_string(),
435 paths: vec!(path_string),
436 feature: None,
437 feature_mut: Some(_feature)
438 }
439 }
440
441 fn identifier(&self) -> String {
442 "IPPServer".to_string()
443 }
444
445 async fn request(&self, _action: &product_os_capabilities::What, _input: &Option<serde_json::Value>, _semver: &str) -> product_os_router::Response<Body> {
446 Response::builder()
448 .status(product_os_request::StatusCode::SERVICE_UNAVAILABLE)
449 .body(Body::from("{}"))
450 .unwrap().into_response()
451 }
452
453 async fn request_mut(&mut self, _action: &product_os_capabilities::What, _input: &Option<serde_json::Value>, _semver: &str) -> product_os_router::Response<Body> {
454 self.request(_action, _input, _semver).await
455 }
456
457 async fn init_feature(&self) -> Result<(), ()> {
458 panic!("Immutable IPP Print Server not allowed to be init")
459 }
460
461 async fn init_feature_mut(&mut self) -> Result<(), ()> {
462 Ok(())
463 }
464}
465
466
467#[async_trait]
468impl Service for ProductOSIPPServer {
469 async fn register(&self, _service: Arc<dyn Service>) -> RegistryService {
470 panic!("Not allowed to register immutable printer service")
471 }
472
473 async fn register_mut(&self, service: Arc<Mutex<dyn Service>>) -> RegistryService {
474 RegistryService {
475 identifier: "IPPServer".to_string(),
476 key: String::new(),
477 kind: "IPPServer".to_string(),
478 active: false,
479 enabled: false,
480 created_at: Default::default(),
481 updated_at: Default::default(),
482 service: None,
483 service_mut: Some(service),
484 }
485 }
486
487 fn identifier(&self) -> String {
488 "IPPServer".to_string()
489 }
490
491 fn key(&self) -> String {
492 String::new()
493 }
494
495 fn is_enabled(&self) -> bool {
496 true
497 }
498
499 fn is_active(&self) -> bool {
500 true
501 }
502
503 async fn status(&self) -> Result<(), ()> {
504 Ok(())
505 }
506
507 async fn start(&self) -> Result<(), ()> {
508 todo!()
509 }
510
511 async fn stop(&self) -> Result<(), ()> {
512 todo!()
513 }
514
515 async fn restart(&self) -> Result<(), ()> {
516 todo!()
517 }
518
519 async fn start_mut(&mut self) -> Result<(), ()> {
520 self.printer.start();
521 self.enable_discovery().await;
522 Ok(())
523 }
524
525 async fn stop_mut(&mut self) -> Result<(), ()> {
526 todo!()
527 }
528
529 async fn restart_mut(&mut self) -> Result<(), ()> {
530 todo!()
531 }
532}