mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
Merge pull request #10656 from dotCooCoo/fix/print-paper-null-and-socket-ppd
Print: file.print refuses a null paper, and only the local scheduler's sockets read its PPDs
This commit is contained in:
5 files changed
+117
-38
No files matched your search
@@ -177,9 +177,10 @@ mod system {
|
||||
return Vec::new();
|
||||
}
|
||||
let named = cups_server();
|
||||
let sockets = local_sockets();
|
||||
// A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue,
|
||||
// so its sizes come from the server.
|
||||
if scheduler_is_local(named.as_deref()) {
|
||||
if scheduler_is_local(named.as_deref(), &sockets, real_path) {
|
||||
const PPD_CAP: u64 = 16 << 20;
|
||||
let mut bytes = Vec::new();
|
||||
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
|
||||
@@ -199,7 +200,7 @@ mod system {
|
||||
}
|
||||
// A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses.
|
||||
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
|
||||
let server = ipp_server(named, |s| std::path::Path::new(s).exists());
|
||||
let server = ipp_server(named, |s| std::path::Path::new(s).exists(), real_path);
|
||||
let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers };
|
||||
use std::io::Write as _;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
@@ -234,17 +235,52 @@ mod system {
|
||||
/// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`.
|
||||
#[cfg(not(windows))]
|
||||
const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"];
|
||||
/// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server
|
||||
/// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default
|
||||
/// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local
|
||||
/// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job
|
||||
/// does not go to.
|
||||
/// The real path of a socket path, through symbolic links (`/var/run/cupsd` is `/private/var/run/cupsd` on macOS).
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn real_path(path: &str) -> Option<String> {
|
||||
std::fs::canonicalize(path).ok().map(|p| p.to_string_lossy().into_owned())
|
||||
}
|
||||
/// The domain sockets of the local scheduler: CUPS's own, and those the `Listen` lines of `/etc/cups/cupsd.conf` add.
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn local_sockets() -> Vec<String> {
|
||||
use std::io::Read as _;
|
||||
let mut text = String::new();
|
||||
let read = std::fs::File::open("/etc/cups/cupsd.conf").and_then(|f| f.take(1 << 20).read_to_string(&mut text));
|
||||
cupsd_listen_sockets(if read.is_ok() { &text } else { "" })
|
||||
}
|
||||
/// CUPS's own domain sockets and the socket paths of the `Listen` lines of a `cupsd.conf`.
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn cupsd_listen_sockets(text: &str) -> Vec<String> {
|
||||
let listed = text.lines().filter_map(|line| {
|
||||
let line = cups_conf_line(line);
|
||||
let (key, value) = line.trim().split_once(char::is_whitespace)?;
|
||||
let value = value.trim();
|
||||
(key.eq_ignore_ascii_case("Listen") && value.starts_with('/')).then(|| value.to_string())
|
||||
});
|
||||
CUPS_SOCKETS.iter().map(|s| (*s).to_string()).chain(listed).collect()
|
||||
}
|
||||
/// Whether the socket path `path` is one of the local scheduler's `sockets`, as written or as `resolve` gives the
|
||||
/// real paths of both.
|
||||
#[cfg(not(windows))]
|
||||
fn is_local_socket(path: &str, sockets: &[impl AsRef<str>], resolve: impl Fn(&str) -> Option<String>) -> bool {
|
||||
let path = path.trim();
|
||||
let real = resolve(path);
|
||||
sockets.iter().any(|s| {
|
||||
let s = s.as_ref();
|
||||
s == path || real.as_ref().is_some_and(|real| real == s || resolve(s).as_ref() == Some(real))
|
||||
})
|
||||
}
|
||||
/// The server for the IPP lookup, given the one `cups_server` names, whether a path exists and a socket path's real path.
|
||||
/// With no server named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost`
|
||||
/// on the IPP default port), and `localhost` on `IPP_PORT` otherwise. A
|
||||
/// named socket in `CUPS_SOCKETS`, or a link to one, also returns `None`. Any other socket path stays as named,
|
||||
/// and the lookup is skipped.
|
||||
///
|
||||
/// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn ipp_server(named: Option<String>, exists: impl Fn(&str) -> bool) -> Option<String> {
|
||||
pub(super) fn ipp_server(named: Option<String>, exists: impl Fn(&str) -> bool, resolve: impl Fn(&str) -> Option<String>) -> Option<String> {
|
||||
match named {
|
||||
Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None,
|
||||
Some(server) if server.trim().starts_with('/') && is_local_socket(&server, &CUPS_SOCKETS, resolve) => None,
|
||||
Some(server) => Some(server),
|
||||
None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()),
|
||||
}
|
||||
@@ -268,14 +304,15 @@ mod system {
|
||||
client_conf_server_name(&text)
|
||||
})
|
||||
}
|
||||
/// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path,
|
||||
/// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback
|
||||
/// name on another port is a second scheduler, whose queues the local PPD folder does not describe.
|
||||
/// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain
|
||||
/// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix.
|
||||
/// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder
|
||||
/// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket.
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn scheduler_is_local(server: Option<&str>) -> bool {
|
||||
pub(super) fn scheduler_is_local(server: Option<&str>, sockets: &[String], resolve: impl Fn(&str) -> Option<String>) -> bool {
|
||||
let Some(server) = server.map(str::trim) else { return true };
|
||||
if server.starts_with('/') {
|
||||
return true;
|
||||
return is_local_socket(server, sockets, resolve);
|
||||
}
|
||||
// A network name may end in `/version=1.1`.
|
||||
let server = server.split_once('/').map_or(server, |(server, _)| server);
|
||||
@@ -289,17 +326,22 @@ mod system {
|
||||
let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1";
|
||||
loopback && port.is_none_or(|port| port.trim() == "631")
|
||||
}
|
||||
/// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a
|
||||
/// A line of a CUPS configuration file without its comment. CUPS (`cupsFileGetConf`) looks only at the first `#` on a
|
||||
/// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is
|
||||
/// dropped and the rest of the line is kept as written.
|
||||
#[cfg(not(windows))]
|
||||
fn cups_conf_line(line: &str) -> String {
|
||||
match line.find('#') {
|
||||
Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]),
|
||||
Some(at) => line[..at].to_string(),
|
||||
None => line.to_string(),
|
||||
}
|
||||
}
|
||||
/// The last `ServerName` in a `client.conf`.
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn client_conf_server_name(text: &str) -> Option<String> {
|
||||
text.lines().rev().find_map(|line| {
|
||||
let kept = match line.find('#') {
|
||||
Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]),
|
||||
Some(at) => line[..at].to_string(),
|
||||
None => line.to_string(),
|
||||
};
|
||||
let kept = cups_conf_line(line);
|
||||
let (key, value) = kept.trim().split_once(char::is_whitespace)?;
|
||||
(key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string())
|
||||
})
|
||||
@@ -604,18 +646,47 @@ mod turn_tests {
|
||||
|
||||
#[cfg(all(test, not(windows)))]
|
||||
mod client_conf_tests {
|
||||
use super::system::{client_conf_server_name, ipp_server, scheduler_is_local};
|
||||
use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, scheduler_is_local};
|
||||
|
||||
#[test]
|
||||
fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() {
|
||||
let none = |_: &str| false;
|
||||
let socket = |s: &str| s == "/run/cups/cups.sock";
|
||||
assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631");
|
||||
assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None);
|
||||
assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked");
|
||||
assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631"));
|
||||
assert_eq!(ipp_server(None, socket), None);
|
||||
assert_eq!(ipp_server(None, none).as_deref(), Some("localhost"));
|
||||
let real = |_: &str| None;
|
||||
assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none, real), None, "CUPS's socket is asked as localhost:631");
|
||||
assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none, real), None);
|
||||
assert_eq!(ipp_server(Some("/var/run/cupsd".into()), none, linked), None, "a link to CUPS's socket is that socket");
|
||||
let other = ipp_server(Some("/tmp/other.sock".into()), socket, linked);
|
||||
assert_eq!(other.as_deref(), Some("/tmp/other.sock"), "another socket is not asked");
|
||||
assert_eq!(ipp_server(Some("localhost:8631".into()), socket, real).as_deref(), Some("localhost:8631"));
|
||||
assert_eq!(ipp_server(None, socket, real), None);
|
||||
assert_eq!(ipp_server(None, none, real).as_deref(), Some("localhost"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_socket_the_local_cupsd_listens_on_counts_as_local() {
|
||||
let real = |_: &str| None;
|
||||
let sockets = cupsd_listen_sockets(
|
||||
"Listen localhost:631\nListen /srv/cups/print.sock # office\n# Listen /tmp/off.sock\nListen /run/cups/office\\#2.sock\n",
|
||||
);
|
||||
assert!(scheduler_is_local(Some("/srv/cups/print.sock"), &sockets, real), "its PPD folder describes the queue");
|
||||
assert!(!scheduler_is_local(Some("/tmp/off.sock"), &sockets, real), "a commented-out Listen line adds nothing");
|
||||
assert!(sockets.iter().any(|s| s == "/run/cups/office#2.sock"));
|
||||
assert_eq!(ipp_server(Some("/srv/cups/print.sock".into()), |_| false, real).as_deref(), Some("/srv/cups/print.sock"));
|
||||
}
|
||||
|
||||
/// The real path of a socket path on a macOS-like system, where `/var` is a link to `/private/var`.
|
||||
fn linked(path: &str) -> Option<String> {
|
||||
path.strip_prefix("/var/").map(|rest| format!("/private/var/{rest}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_socket_path_counts_as_local_only_when_it_is_cups_own() {
|
||||
let real = |_: &str| None;
|
||||
let own = cupsd_listen_sockets("");
|
||||
assert!(scheduler_is_local(Some("/var/run/cupsd"), &own, linked), "a link to CUPS's socket reads the local PPD folder");
|
||||
assert!(!scheduler_is_local(Some("/var/run/cupsd"), &own, real), "an unresolved unknown path is another scheduler");
|
||||
assert!(!scheduler_is_local(Some("/var/run/other.sock"), &own, linked));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -623,6 +694,8 @@ mod client_conf_tests {
|
||||
for local in [
|
||||
None,
|
||||
Some("/run/cups/cups.sock"),
|
||||
Some(" /var/run/cups/cups.sock "),
|
||||
Some("/private/var/run/cupsd"),
|
||||
Some("localhost"),
|
||||
Some("LocalHost:631"),
|
||||
Some("localhost:631"),
|
||||
@@ -633,7 +706,7 @@ mod client_conf_tests {
|
||||
Some("localhost/version=1.1"),
|
||||
Some("localhost:631/version=1.1"),
|
||||
] {
|
||||
assert!(scheduler_is_local(local), "{local:?}");
|
||||
assert!(scheduler_is_local(local, &cupsd_listen_sockets(""), |_| None), "{local:?}");
|
||||
}
|
||||
for remote in [
|
||||
"print.example.com",
|
||||
@@ -647,8 +720,10 @@ mod client_conf_tests {
|
||||
"127.0.0.1:8631",
|
||||
"[::1]:8631",
|
||||
"localhost:8631/version=1.1",
|
||||
"/tmp/other.sock",
|
||||
"/home/me/.cups/second.sock",
|
||||
] {
|
||||
assert!(!scheduler_is_local(Some(remote)), "{remote}");
|
||||
assert!(!scheduler_is_local(Some(remote), &cupsd_listen_sockets(""), linked), "{remote}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -871,8 +871,11 @@ fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &st
|
||||
app.run("print.setup", json!({ "settings": settings }))?;
|
||||
match answer.finish {
|
||||
PrintFinish::Print => {
|
||||
let paper = if applies_paper { driver_paper_key(&answer.fields, &open.papers.1) } else { None };
|
||||
let job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf, "paper": paper });
|
||||
let mut job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf });
|
||||
// `paper` is left out when there is none: `file.print` refuses a null one.
|
||||
if applies_paper && let Some(paper) = driver_paper_key(&answer.fields, &open.papers.1) {
|
||||
job["paper"] = json!(paper);
|
||||
}
|
||||
crate::print::run(app, &job).map(|_| ())
|
||||
}
|
||||
// Done only keeps the settings.
|
||||
|
||||
@@ -814,7 +814,7 @@ fn the_job_asks_the_queue_for_the_driver_paper_chosen() {
|
||||
// Without the dialog, the keyword is given as `paper`, and anything else is refused before printing.
|
||||
app.run("file.print", json!({"printer": "Card", "paper": "iso_a4_210x297mm"})).unwrap();
|
||||
assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), Some("iso_a4_210x297mm"));
|
||||
for bad in [json!("US Letter"), json!(""), json!("a=b"), json!("Letter,Tray1"), json!("Let'ter"), json!("Let\\ter"), json!(4)] {
|
||||
for bad in [json!("US Letter"), json!(""), json!("a=b"), json!("Letter,Tray1"), json!("Let'ter"), json!("Let\\ter"), json!(4), json!(null)] {
|
||||
assert!(app.run("file.print", json!({"printer": "Card", "paper": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert!(app.run("file.print", json!({"toFile": true, "paper": "Letter"})).is_err());
|
||||
|
||||
@@ -411,11 +411,11 @@ fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result<String, String>, jo
|
||||
Ok(notes)
|
||||
}
|
||||
|
||||
/// `file.print`'s `paper`: the printer driver's keyword for the paper (absent or null: none). Anything but printable
|
||||
/// ASCII without spaces, `,`, `/`, `:`, `=`, `"`, `'` or `\`, up to 64 characters, is an error.
|
||||
/// `file.print`'s `paper`: the printer driver's keyword for the paper (absent: none). Anything but printable
|
||||
/// ASCII without spaces, `,`, `/`, `:`, `=`, `"`, `'` or `\`, up to 64 characters, null included, is an error.
|
||||
fn paper_param(p: &Value) -> Result<Option<String>, String> {
|
||||
match p.get("paper") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
None => Ok(None),
|
||||
Some(Value::String(k)) if is_paper_keyword(k) => Ok(Some(k.clone())),
|
||||
Some(v) => Err(format!("paper must be a printer driver's paper keyword, such as `Letter` or `CR80`, not {v}")),
|
||||
}
|
||||
|
||||
+4
-3
@@ -13709,12 +13709,13 @@ default printer) or, with `toFile`, a `path` or no printing available, saves the
|
||||
driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its
|
||||
`media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is
|
||||
not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or
|
||||
remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket,
|
||||
remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than CUPS's own domain socket, a socket a `Listen` line of `/etc/cups/cupsd.conf` names (or a link to either),
|
||||
`localhost`, `127.0.0.1` or `::1` (each with no port or port 631), lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes
|
||||
of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux,
|
||||
`client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is
|
||||
asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. CUPS's own domain socket named as the
|
||||
server is asked as `localhost` on port 631; another socket path is not asked.
|
||||
asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. When CUPS's own domain socket
|
||||
or a link to one is named as the server, the lookup asks `localhost` on port 631. Other socket paths, including those added only by
|
||||
`cupsd.conf` `Listen` lines, are not asked.
|
||||
In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has
|
||||
applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once.
|
||||
The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available.
|
||||
|
||||
Reference in new issue
Block a user