Skip to main content

product_os_print_server/
lib.rs

1//! # Product OS Print Server
2//!
3//! A complete IPP (Internet Printing Protocol) 1.1 server implementation for Rust.
4//!
5//! This crate provides a full-featured IPP print server that can handle print jobs,
6//! manage printer attributes, and integrate with the Product OS ecosystem through
7//! the capabilities framework.
8//!
9//! ## Features
10//!
11//! - **IPP 1.1 Protocol Support**: Complete implementation of the IPP 1.1 specification
12//! - **Bonjour/Zeroconf Discovery**: Automatic printer discovery on the network
13//! - **Async/Await Support**: Built on tokio for high-performance async I/O
14//! - **Flexible Job Processing**: Pluggable processor trait for custom print handling
15//! - **Product OS Integration**: Seamless integration with Product OS capabilities
16//!
17//! ## Quick Start
18//!
19//! ```rust,no_run
20//! use product_os_print_server::{ProductOSIPPServer, ProductOSIPPProcessor};
21//! use std::sync::Arc;
22//! use async_trait::async_trait;
23//! use product_os_utilities::ProductOSError;
24//!
25//! // Implement a custom print processor
26//! struct MyProcessor;
27//!
28//! #[async_trait]
29//! impl ProductOSIPPProcessor for MyProcessor {
30//!     async fn process(&self, id: usize, data: Vec<u8>) -> Result<(), ProductOSError> {
31//!         // Handle print job data
32//!         println!("Processing job {} with {} bytes", id, data.len());
33//!         Ok(())
34//!     }
35//!
36//!     async fn cancel(&self, id: usize) -> Result<(), ProductOSError> {
37//!         println!("Cancelling job {}", id);
38//!         Ok(())
39//!     }
40//! }
41//!
42//! // Create and configure the print server
43//! let processor = Arc::new(MyProcessor);
44//! let server = ProductOSIPPServer::new(
45//!     "My Printer".to_string(),
46//!     "ipp://localhost:631/printers/my-printer".to_string(),
47//!     631,
48//!     false,
49//!     processor
50//! );
51//! ```
52//!
53//! ## Architecture
54//!
55//! The print server is built around several key components:
56//!
57//! - **ProductOSIPPServer**: The main server struct that manages the printer and handles requests
58//! - **ProductOSIPPProcessor**: A trait for implementing custom print job processing
59//! - **Encoder/Decoder**: Handles IPP protocol encoding and decoding
60//! - **Printer Management**: Manages printer state, attributes, and job queue
61//!
62//! ## IPP Operations Supported
63//!
64//! - Print-Job
65//! - Validate-Job
66//! - Get-Printer-Attributes
67//! - Get-Jobs
68//! - Cancel-Job
69//! - Get-Job-Attributes
70//!
71//! ## Cargo Features
72//!
73//! | Feature | Default | Description |
74//! |---------|---------|-------------|
75//! | `std` | Yes | Standard library support (`serde/std`, `serde_json/std`) |
76//! | `compression` | Yes | IPP data compression/decompression via `flate2` |
77//! | `discovery` | Yes | Bonjour/Zeroconf network printer discovery |
78//! | `logging` | Yes | Structured logging via `tracing` |
79//! | `minimal` | No | Minimal build with no optional dependencies |
80//! | `serde-support` | No | **Deprecated** -- no-op |
81//! | `job-naming` | No | **Deprecated** -- no-op |
82//!
83//! ## Security
84//!
85//! The server supports both IPP (insecure) and IPPS (secure over TLS) modes.
86//! Set the `is_secure` parameter when creating the server to enable TLS.
87
88#[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
120/// The main IPP print server.
121///
122/// `ProductOSIPPServer` manages an IPP 1.1 compliant print server that can handle
123/// print jobs, manage printer attributes, and provide network discovery via Bonjour.
124///
125/// # Examples
126///
127/// ```rust,no_run
128/// use product_os_print_server::{ProductOSIPPServer, ProductOSIPPProcessor};
129/// use std::sync::Arc;
130/// # use async_trait::async_trait;
131/// # use product_os_utilities::ProductOSError;
132/// # struct MyProcessor;
133/// # #[async_trait]
134/// # impl ProductOSIPPProcessor for MyProcessor {
135/// #     async fn process(&self, _id: usize, _data: Vec<u8>) -> Result<(), ProductOSError> { Ok(()) }
136/// #     async fn cancel(&self, _id: usize) -> Result<(), ProductOSError> { Ok(()) }
137/// # }
138///
139/// let processor = Arc::new(MyProcessor);
140/// let server = ProductOSIPPServer::new(
141///     "Office Printer".to_string(),
142///     "ipp://localhost:631/printers/office".to_string(),
143///     631,
144///     false, // not secure
145///     processor
146/// );
147/// ```
148///
149/// # Thread Safety
150///
151/// `ProductOSIPPServer` implements `Send` and `Sync`, making it safe to share
152/// across threads when wrapped in an `Arc<Mutex<_>>`.
153pub struct ProductOSIPPServer {
154    printer: ProductOSIPPPrinter,
155    is_secure: bool,
156    processor: Arc<dyn ProductOSIPPProcessor>
157}
158
159impl ProductOSIPPServer {
160    /// Creates a new IPP print server.
161    ///
162    /// # Arguments
163    ///
164    /// * `name` - The human-readable name of the printer (e.g., "Office Printer")
165    /// * `uri` - The IPP URI where the printer will be accessible (e.g., "ipp://localhost:631/printers/office")
166    /// * `port` - The port number the server will listen on (typically 631 for IPP)
167    /// * `is_secure` - Whether to use IPPS (IPP over TLS). If true, uses "ipps://" protocol
168    /// * `processor` - An `Arc` to a processor implementing `ProductOSIPPProcessor` for handling print jobs
169    ///
170    /// # Returns
171    ///
172    /// A new `ProductOSIPPServer` instance ready to handle IPP requests.
173    ///
174    /// # Panics
175    ///
176    /// Panics if the `uri` parameter is empty or malformed.
177    ///
178    /// # Examples
179    ///
180    /// ```rust,no_run
181    /// # use product_os_print_server::{ProductOSIPPServer, ProductOSIPPProcessor};
182    /// # use std::sync::Arc;
183    /// # use async_trait::async_trait;
184    /// # use product_os_utilities::ProductOSError;
185    /// # struct MyProcessor;
186    /// # #[async_trait]
187    /// # impl ProductOSIPPProcessor for MyProcessor {
188    /// #     async fn process(&self, _id: usize, _data: Vec<u8>) -> Result<(), ProductOSError> { Ok(()) }
189    /// #     async fn cancel(&self, _id: usize) -> Result<(), ProductOSError> { Ok(()) }
190    /// # }
191    /// let processor = Arc::new(MyProcessor);
192    ///
193    /// // Create an insecure IPP server
194    /// let server = ProductOSIPPServer::new(
195    ///     "My Printer".to_string(),
196    ///     "ipp://192.168.1.100:631/printers/main".to_string(),
197    ///     631,
198    ///     false,
199    ///     processor.clone()
200    /// );
201    ///
202    /// // Create a secure IPPS server
203    /// let secure_server = ProductOSIPPServer::new(
204    ///     "Secure Printer".to_string(),
205    ///     "ipps://192.168.1.100:631/printers/secure".to_string(),
206    ///     631,
207    ///     true,
208    ///     processor
209    /// );
210    /// ```
211    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    /// Enables Bonjour/Zeroconf network discovery for this printer.
220    ///
221    /// This spawns a background task that advertises the printer on the local network
222    /// using mDNS/Bonjour, allowing clients to automatically discover the printer.
223    ///
224    /// Requires the `discovery` feature to be enabled. When disabled, this is a no-op.
225    ///
226    /// # Protocol
227    ///
228    /// - If `is_secure` is `true`, advertises as `_ipps._tcp`
229    /// - If `is_secure` is `false`, advertises as `_ipp._tcp`
230    #[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        // Discovery disabled at compile time
254    }
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        // Clone self into a new Arc<Mutex<ProductOSIPPServer>> to pass to the handler
419        // This way we have the concrete type, not dyn Feature
420        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        // browser_handler::browser_request_process(request, Value::Object(serde_json::Map::new()), &mut self).await.into_response()
447        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}