printer-doctor 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +171 -2
- package/package.json +48 -4
- package/src/index.js +112 -0
- package/src/lib/cups.js +237 -0
- package/src/lib/diagnose.js +439 -0
- package/src/lib/gather.js +317 -0
- package/src/lib/ipp.js +283 -0
- package/src/lib/mdns.js +385 -0
- package/src/lib/net.js +236 -0
- package/src/lib/report.js +130 -0
- package/src/lib/run.js +52 -0
- package/src/lib/text.js +27 -0
- package/src/lib/windows.js +173 -0
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
// Collects the facts the diagnosis is built from. Everything here only looks: it asks this
|
|
2
|
+
// computer's print system, listens for printers announcing themselves, and asks the chosen
|
|
3
|
+
// printer for its own state. Only addresses inside a home network are ever contacted.
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
|
|
6
|
+
import { OP, encodeRequest, ippSend, groupsOf, one, many } from "./ipp.js";
|
|
7
|
+
import { browse } from "./mdns.js";
|
|
8
|
+
import { getCups, readMarkers } from "./cups.js";
|
|
9
|
+
import { getWindows } from "./windows.js";
|
|
10
|
+
import { getInterfaces, getRoutes, homeAddresses, isPrivateAddress, onSameNetwork, resolvePrivate, tcpConnect } from "./net.js";
|
|
11
|
+
import { cleanText, cleanOrNull, cleanKeywords } from "./text.js";
|
|
12
|
+
|
|
13
|
+
const now = () => performance.now();
|
|
14
|
+
|
|
15
|
+
const DEVICE_ATTRS = [
|
|
16
|
+
"printer-state",
|
|
17
|
+
"printer-state-reasons",
|
|
18
|
+
"printer-is-accepting-jobs",
|
|
19
|
+
"queued-job-count",
|
|
20
|
+
"printer-make-and-model",
|
|
21
|
+
"marker-names",
|
|
22
|
+
"marker-levels",
|
|
23
|
+
"marker-colors",
|
|
24
|
+
"marker-types",
|
|
25
|
+
"marker-low-levels",
|
|
26
|
+
"printer-alert-description",
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
// ---------- this computer's print system -------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
/** { system, available, serviceRunning, printers, defaultName } on any platform. */
|
|
32
|
+
export async function getSystem(opts = {}) {
|
|
33
|
+
if (opts.system) return opts.system;
|
|
34
|
+
if (process.platform === "win32") return getWindows();
|
|
35
|
+
if (process.platform === "darwin" || process.platform === "linux") return getCups(opts.cups);
|
|
36
|
+
return { system: "none", available: false, serviceRunning: false, printers: [], defaultName: null };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ---------- choosing the printer to look at ----------------------------------------------------
|
|
40
|
+
|
|
41
|
+
const squash = (s) =>
|
|
42
|
+
String(s || "")
|
|
43
|
+
.toLowerCase()
|
|
44
|
+
.replace(/[^a-z0-9]/g, "");
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Which printer the person means. Returns { printer, how } or { printer: null, problem, candidates }.
|
|
48
|
+
* Without a name: the default printer, or the only real one. Things that print to a file don't count.
|
|
49
|
+
*/
|
|
50
|
+
export function choosePrinter(system, asked) {
|
|
51
|
+
const all = system.printers || [];
|
|
52
|
+
const real = all.filter((p) => !p.virtual);
|
|
53
|
+
const names = real.map((p) => p.label || p.name);
|
|
54
|
+
const wanted = String(asked || "").trim();
|
|
55
|
+
if (wanted) {
|
|
56
|
+
const low = wanted.toLowerCase();
|
|
57
|
+
const exact = all.filter((p) => p.name.toLowerCase() === low || String(p.label || "").toLowerCase() === low);
|
|
58
|
+
if (exact.length === 1) return { printer: exact[0], how: "named" };
|
|
59
|
+
const key = squash(wanted);
|
|
60
|
+
const close = key.length >= 2 ? all.filter((p) => squash(p.name).includes(key) || squash(p.label).includes(key)) : [];
|
|
61
|
+
if (close.length === 1) return { printer: close[0], how: "named" };
|
|
62
|
+
if (close.length > 1) return { printer: null, problem: "choose", asked: wanted, candidates: close.map((p) => p.label || p.name) };
|
|
63
|
+
if (real.length) return { printer: null, problem: "not_found", asked: wanted, candidates: names };
|
|
64
|
+
}
|
|
65
|
+
if (!all.length) return { printer: null, problem: "no_printers", candidates: [] };
|
|
66
|
+
if (!real.length) return { printer: null, problem: "only_virtual", candidates: all.map((p) => p.label || p.name) };
|
|
67
|
+
const def = real.find((p) => p.isDefault);
|
|
68
|
+
if (def) return { printer: def, how: "default" };
|
|
69
|
+
if (real.length === 1) return { printer: real[0], how: "only" };
|
|
70
|
+
return { printer: null, problem: "choose", candidates: names };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---------- matching a queue to a printer on the network ---------------------------------------
|
|
74
|
+
|
|
75
|
+
const NOISE = /\b(series|printer|airprint|class driver|driverless|ipp everywhere|fax|pcl\s?\d*|ps|postscript|xl|usb)\b/gi;
|
|
76
|
+
const model = (s) => squash(String(s || "").replace(/[_-]+/g, " ").replace(NOISE, " "));
|
|
77
|
+
const bareHost = (h) =>
|
|
78
|
+
String(h || "")
|
|
79
|
+
.toLowerCase()
|
|
80
|
+
.replace(/\.$/, "")
|
|
81
|
+
.replace(/\.local$/, "");
|
|
82
|
+
|
|
83
|
+
/** The announced printer that is the same device as this queue, or null when that can't be told. */
|
|
84
|
+
export function matchAnnounced(printer, announced = []) {
|
|
85
|
+
if (!printer || !announced.length) return null;
|
|
86
|
+
if (printer.uuid) {
|
|
87
|
+
const m = announced.find((a) => a.uuid && a.uuid === printer.uuid);
|
|
88
|
+
if (m) return m;
|
|
89
|
+
}
|
|
90
|
+
if (printer.instance) {
|
|
91
|
+
const m = announced.find((a) => a.instance.toLowerCase() === printer.instance.toLowerCase());
|
|
92
|
+
if (m) return m;
|
|
93
|
+
}
|
|
94
|
+
if (printer.host) {
|
|
95
|
+
const m = net.isIP(printer.host) ? announced.find((a) => a.addresses.includes(printer.host)) : announced.find((a) => a.host && bareHost(a.host) === bareHost(printer.host));
|
|
96
|
+
if (m) return m;
|
|
97
|
+
}
|
|
98
|
+
// Last resort: the same model name, and only when exactly one printer on the network has it.
|
|
99
|
+
const mine = [printer.label, printer.name, printer.driver].map(model).filter((s) => s.length >= 6);
|
|
100
|
+
const alike = announced.filter((a) => {
|
|
101
|
+
const theirs = [a.instance, a.model].map(model).filter((s) => s.length >= 6);
|
|
102
|
+
return theirs.some((t) => mine.some((m) => m === t || m.includes(t) || t.includes(m)));
|
|
103
|
+
});
|
|
104
|
+
return alike.length === 1 ? alike[0] : null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---------- asking the printer itself ----------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
function readDevice(response) {
|
|
110
|
+
const a = groupsOf(response, 0x04)[0] || {};
|
|
111
|
+
return {
|
|
112
|
+
state: Number(one(a, "printer-state")) || null,
|
|
113
|
+
reasons: cleanKeywords(many(a, "printer-state-reasons")).filter((r) => r !== "none"),
|
|
114
|
+
accepting: one(a, "printer-is-accepting-jobs"),
|
|
115
|
+
queued: one(a, "queued-job-count"),
|
|
116
|
+
model: cleanOrNull(one(a, "printer-make-and-model"), 64),
|
|
117
|
+
markers: readMarkers(a),
|
|
118
|
+
// Short messages from the printer's own screen ("Sleep", "Toner Low").
|
|
119
|
+
alert: many(a, "printer-alert-description")
|
|
120
|
+
.map((x) => cleanText(x, 40))
|
|
121
|
+
.filter(Boolean)
|
|
122
|
+
.slice(0, 3),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Asks a printer for its own state with one read-only IPP question (a few tries at most, for the
|
|
128
|
+
* usual addresses a printer answers on). `tries` is a list of { port, secure, path }.
|
|
129
|
+
* Returns { asked, answered, ...state } and never throws.
|
|
130
|
+
*/
|
|
131
|
+
export async function askPrinter(ip, tries) {
|
|
132
|
+
if (!isPrivateAddress(ip)) return { asked: false, answered: false, error: "not-home-address" };
|
|
133
|
+
if (!tries.length) return { asked: false, answered: false, error: "no-ipp" };
|
|
134
|
+
const host = ip.includes(":") ? `[${ip}]` : ip;
|
|
135
|
+
const dead = new Set(); // ports where nothing listens: other paths there can't work either
|
|
136
|
+
const queue = [...tries];
|
|
137
|
+
let last = "no-answer";
|
|
138
|
+
let version = [1, 1];
|
|
139
|
+
let attempts = 0;
|
|
140
|
+
while (queue.length && attempts < 3) {
|
|
141
|
+
const t = queue.shift();
|
|
142
|
+
const id = `${t.port}/${t.secure ? "tls" : "plain"}`;
|
|
143
|
+
if (dead.has(id)) continue;
|
|
144
|
+
attempts += 1;
|
|
145
|
+
const target = { host: ip, port: t.port, path: t.path, secure: t.secure };
|
|
146
|
+
const request = () => encodeRequest({ op: OP.GET_PRINTER_ATTRIBUTES, uri: `${t.secure ? "ipps" : "ipp"}://${host}:${t.port}${t.path}`, requested: DEVICE_ATTRS, version });
|
|
147
|
+
let r = await ippSend(target, request(), { timeoutMs: 3000 });
|
|
148
|
+
if (r.response?.status === 0x0503 && version[0] === 1) {
|
|
149
|
+
// "Version not supported": a few printers only speak the newer version of the protocol.
|
|
150
|
+
version = [2, 0];
|
|
151
|
+
r = await ippSend(target, request(), { timeoutMs: 3000 });
|
|
152
|
+
}
|
|
153
|
+
if (r.ok) return { asked: true, answered: true, port: t.port, secure: Boolean(t.secure), ...readDevice(r.response) };
|
|
154
|
+
last = r.error || last;
|
|
155
|
+
if (r.error === "needs-password") break; // it is there, and will say the same on every path
|
|
156
|
+
if (r.error === "needs-tls" && !t.secure) queue.unshift({ ...t, secure: true });
|
|
157
|
+
else if (!["http", "ipp-status", "unreadable"].includes(r.error)) dead.add(id);
|
|
158
|
+
}
|
|
159
|
+
return { asked: true, answered: false, error: last };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The addresses worth trying on a printer, best first. */
|
|
163
|
+
export function ippTries(printer, announced) {
|
|
164
|
+
const out = [];
|
|
165
|
+
const add = (port, secure, path) => {
|
|
166
|
+
const p = path && path.startsWith("/") ? path : "/ipp/print";
|
|
167
|
+
if (!out.some((x) => x.port === port && x.secure === secure && x.path === p)) out.push({ port, secure, path: p });
|
|
168
|
+
};
|
|
169
|
+
if (printer?.scheme === "ipp" || printer?.scheme === "http") add(printer.port || 631, false, printer.path);
|
|
170
|
+
if (printer?.scheme === "ipps" || printer?.scheme === "https") add(printer.port || 631, true, printer.path);
|
|
171
|
+
for (const s of announced?.services || []) {
|
|
172
|
+
if (s.type === "ipp") add(s.port, false, s.path);
|
|
173
|
+
if (s.type === "ipps") add(s.port, true, s.path);
|
|
174
|
+
}
|
|
175
|
+
add(631, false, "/ipp/print");
|
|
176
|
+
add(631, false, "/");
|
|
177
|
+
// Plain IPP first: it needs no certificate and every network printer that speaks IPP offers it.
|
|
178
|
+
return out.sort((a, b) => Number(a.secure) - Number(b.secure));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ---------- finding and reaching a network printer ---------------------------------------------
|
|
182
|
+
|
|
183
|
+
// Ports that accept print data as soon as something connects (raw printing and LPD). They are
|
|
184
|
+
// never touched, so nothing can end up on paper by accident. A device that is switched on answers
|
|
185
|
+
// on the other ports anyway, even if only to refuse.
|
|
186
|
+
const PRINT_DATA_PORTS = (p) => p === 515 || (p >= 9100 && p <= 9109);
|
|
187
|
+
|
|
188
|
+
/** The ports to try on a printer: its IPP port(s), IPP's standard port, and its web page. */
|
|
189
|
+
export const knockPorts = (extra = []) => [...new Set([...extra, 631, 80, 443].filter((p) => Number.isInteger(p) && p > 0 && !PRINT_DATA_PORTS(p)))];
|
|
190
|
+
|
|
191
|
+
/** Short connection attempts to a printer, closed straight away: does anything answer there? */
|
|
192
|
+
export async function probe(ip, ports) {
|
|
193
|
+
const results = await Promise.all(ports.map((p) => tcpConnect(ip, p, 2000)));
|
|
194
|
+
return { ip, probes: results, answered: results.some((r) => r.answered) };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Where the printer is on the network and whether it answers:
|
|
199
|
+
* { queueAddress, hostIsName, nameFound, publicAddress, match, address, answered, probes,
|
|
200
|
+
* addressChanged, newAddress, nameStillUsed, sameNetwork }
|
|
201
|
+
*/
|
|
202
|
+
export async function locate(printer, announced, interfaces, opts = {}) {
|
|
203
|
+
const out = {
|
|
204
|
+
queueAddress: null,
|
|
205
|
+
hostIsName: false,
|
|
206
|
+
nameFound: null,
|
|
207
|
+
publicAddress: false,
|
|
208
|
+
match: null,
|
|
209
|
+
address: null,
|
|
210
|
+
answered: null,
|
|
211
|
+
probes: [],
|
|
212
|
+
addressChanged: false,
|
|
213
|
+
newAddress: null,
|
|
214
|
+
nameStillUsed: false,
|
|
215
|
+
sameNetwork: null,
|
|
216
|
+
};
|
|
217
|
+
const match = matchAnnounced(printer, announced);
|
|
218
|
+
out.match = match;
|
|
219
|
+
if (printer.host) {
|
|
220
|
+
if (net.isIP(printer.host)) {
|
|
221
|
+
if (isPrivateAddress(printer.host)) out.queueAddress = printer.host;
|
|
222
|
+
else out.publicAddress = true;
|
|
223
|
+
} else {
|
|
224
|
+
out.hostIsName = true;
|
|
225
|
+
const r = await (opts.resolve || resolvePrivate)(printer.host);
|
|
226
|
+
out.nameFound = r.addresses.length > 0;
|
|
227
|
+
out.publicAddress = r.publicOnly;
|
|
228
|
+
out.queueAddress = r.addresses[0] || null;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (out.publicAddress) return out; // an address on the internet is reported, never contacted
|
|
232
|
+
const check = opts.probe || probe;
|
|
233
|
+
if (out.queueAddress) {
|
|
234
|
+
const p = await check(out.queueAddress, knockPorts(/^(ipps?|https?)$/.test(printer.scheme || "") ? [printer.port] : []));
|
|
235
|
+
out.address = out.queueAddress;
|
|
236
|
+
out.probes = p.probes;
|
|
237
|
+
out.answered = p.answered;
|
|
238
|
+
}
|
|
239
|
+
if (!out.answered && match?.addresses.length && !match.addresses.includes(out.queueAddress)) {
|
|
240
|
+
// The queue's own address is silent (or it has none), but the printer is announcing itself.
|
|
241
|
+
const at = match.addresses[0];
|
|
242
|
+
const p = await check(at, knockPorts(match.services.filter((s) => s.type === "ipp" || s.type === "ipps").map((s) => s.port)));
|
|
243
|
+
const stale = Boolean(out.queueAddress) || (out.hostIsName && out.nameFound === false);
|
|
244
|
+
if (!stale || p.answered) {
|
|
245
|
+
out.addressChanged = stale && p.answered;
|
|
246
|
+
out.newAddress = out.addressChanged ? at : null;
|
|
247
|
+
// The printer still announces the very name this computer failed to look up.
|
|
248
|
+
out.nameStillUsed = out.addressChanged && out.hostIsName && Boolean(match.host) && bareHost(match.host) === bareHost(printer.host);
|
|
249
|
+
out.address = at;
|
|
250
|
+
out.probes = p.probes;
|
|
251
|
+
out.answered = p.answered;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (out.address) out.sameNetwork = onSameNetwork(out.address, interfaces);
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ---------- the two tools ----------------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
async function lookAround(opts) {
|
|
261
|
+
const interfaces = opts.interfaces || getInterfaces();
|
|
262
|
+
const routes = opts.routes || (await getRoutes(interfaces));
|
|
263
|
+
const [system, announced] = await Promise.all([
|
|
264
|
+
getSystem(opts),
|
|
265
|
+
opts.announced ? Promise.resolve(opts.announced) : browse({ localAddresses: homeAddresses(interfaces, routes.routerIface), ...(opts.mdns || {}) }),
|
|
266
|
+
]);
|
|
267
|
+
return { interfaces, routes, system, announced };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Everything find_printers reports. */
|
|
271
|
+
export async function gatherList(opts = {}) {
|
|
272
|
+
const started = now();
|
|
273
|
+
const { routes, system, announced } = await lookAround(opts);
|
|
274
|
+
const printers = system.printers.map((p) => ({ ...p, match: p.kind === "network" ? matchAnnounced(p, announced.printers) : null }));
|
|
275
|
+
const taken = new Set(printers.map((p) => p.match).filter(Boolean));
|
|
276
|
+
return {
|
|
277
|
+
platform: process.platform,
|
|
278
|
+
seconds: Math.round((now() - started) / 1000),
|
|
279
|
+
system: { ...system, printers },
|
|
280
|
+
notSetUp: announced.printers.filter((a) => !taken.has(a)),
|
|
281
|
+
announcedCount: announced.printers.length,
|
|
282
|
+
heard: announced.heard,
|
|
283
|
+
viaVpn: routes.viaVpn,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Everything check_printer reports on. */
|
|
288
|
+
export async function gatherCheck(printerName, opts = {}) {
|
|
289
|
+
const started = now();
|
|
290
|
+
const { interfaces, routes, system, announced } = await lookAround(opts);
|
|
291
|
+
const selection = system.available && system.serviceRunning !== false ? choosePrinter(system, printerName) : { printer: null, problem: "no_system" };
|
|
292
|
+
const target = selection.printer;
|
|
293
|
+
const facts = {
|
|
294
|
+
platform: process.platform,
|
|
295
|
+
seconds: 0,
|
|
296
|
+
system,
|
|
297
|
+
selection: { how: selection.how || null, problem: selection.problem || null, asked: selection.asked || null, candidates: selection.candidates || [] },
|
|
298
|
+
target,
|
|
299
|
+
network: { viaVpn: routes.viaVpn, vpnIfaces: routes.vpnIfaces, announced: announced.printers, heard: announced.heard },
|
|
300
|
+
location: null,
|
|
301
|
+
device: null,
|
|
302
|
+
};
|
|
303
|
+
if (target && target.kind === "network") {
|
|
304
|
+
facts.location = await locate(target, announced.printers, interfaces, opts);
|
|
305
|
+
const loc = facts.location;
|
|
306
|
+
if (loc.address && loc.answered) {
|
|
307
|
+
// Only ports that just answered are asked; a printer with no IPP port is left alone.
|
|
308
|
+
const open = (t) => {
|
|
309
|
+
const p = loc.probes.find((x) => x.port === t.port);
|
|
310
|
+
return !p || p.state === "open";
|
|
311
|
+
};
|
|
312
|
+
facts.device = await (opts.ask || askPrinter)(loc.address, ippTries(loc.addressChanged ? null : target, loc.match).filter(open));
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
facts.seconds = Math.round((now() - started) / 1000);
|
|
316
|
+
return facts;
|
|
317
|
+
}
|
package/src/lib/ipp.js
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// A small IPP (Internet Printing Protocol) client: just enough of RFC 8010 (the wire format) and
|
|
2
|
+
// RFC 8011 (the operations) to ASK a printer or a print system about itself. It can only build
|
|
3
|
+
// the read-only requests listed in OP below: there is no code here that could send a print job,
|
|
4
|
+
// cancel one, or change a setting.
|
|
5
|
+
import http from "node:http";
|
|
6
|
+
import https from "node:https";
|
|
7
|
+
|
|
8
|
+
/** The only operations this client can send. All of them only read. */
|
|
9
|
+
export const OP = {
|
|
10
|
+
GET_JOBS: 0x000a,
|
|
11
|
+
GET_PRINTER_ATTRIBUTES: 0x000b,
|
|
12
|
+
CUPS_GET_DEFAULT: 0x4001,
|
|
13
|
+
CUPS_GET_PRINTERS: 0x4002,
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const T = {
|
|
17
|
+
OPERATION: 0x01,
|
|
18
|
+
END: 0x03,
|
|
19
|
+
INTEGER: 0x21,
|
|
20
|
+
BOOLEAN: 0x22,
|
|
21
|
+
ENUM: 0x23,
|
|
22
|
+
OCTET_STRING: 0x30,
|
|
23
|
+
DATE_TIME: 0x31,
|
|
24
|
+
RESOLUTION: 0x32,
|
|
25
|
+
RANGE: 0x33,
|
|
26
|
+
BEG_COLLECTION: 0x34,
|
|
27
|
+
TEXT_LANG: 0x35,
|
|
28
|
+
NAME_LANG: 0x36,
|
|
29
|
+
END_COLLECTION: 0x37,
|
|
30
|
+
KEYWORD: 0x44,
|
|
31
|
+
URI: 0x45,
|
|
32
|
+
CHARSET: 0x47,
|
|
33
|
+
LANGUAGE: 0x48,
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export class IppError extends Error {}
|
|
37
|
+
|
|
38
|
+
// ---------- encoding ---------------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
function attribute(tag, name, values) {
|
|
41
|
+
const parts = [];
|
|
42
|
+
(Array.isArray(values) ? values : [values]).forEach((v, i) => {
|
|
43
|
+
// Extra values of the same attribute are written with an empty name (RFC 8010, 3.1.3).
|
|
44
|
+
const n = Buffer.from(i === 0 ? name : "", "utf8");
|
|
45
|
+
const val = tag === T.INTEGER || tag === T.ENUM ? int32(v) : tag === T.BOOLEAN ? Buffer.from([v ? 1 : 0]) : Buffer.from(String(v), "utf8");
|
|
46
|
+
if (n.length > 0xffff || val.length > 0xffff) throw new IppError("attribute too long");
|
|
47
|
+
const head = Buffer.alloc(3);
|
|
48
|
+
head[0] = tag;
|
|
49
|
+
head.writeUInt16BE(n.length, 1);
|
|
50
|
+
const len = Buffer.alloc(2);
|
|
51
|
+
len.writeUInt16BE(val.length);
|
|
52
|
+
parts.push(head, n, len, val);
|
|
53
|
+
});
|
|
54
|
+
return Buffer.concat(parts);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const int32 = (n) => {
|
|
58
|
+
const b = Buffer.alloc(4);
|
|
59
|
+
b.writeInt32BE(n);
|
|
60
|
+
return b;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Builds one read-only request.
|
|
65
|
+
* op one of OP
|
|
66
|
+
* uri the printer-uri (left out for the CUPS operations that have none)
|
|
67
|
+
* requested attribute names to ask for
|
|
68
|
+
* extra further operation attributes as [tag name, attribute name, value]
|
|
69
|
+
*/
|
|
70
|
+
export function encodeRequest({ op, uri = null, requested = [], extra = [], requestId = 1, version = [1, 1] }) {
|
|
71
|
+
if (!Object.values(OP).includes(op)) throw new IppError("this client only sends read-only requests");
|
|
72
|
+
const head = Buffer.alloc(8);
|
|
73
|
+
head[0] = version[0];
|
|
74
|
+
head[1] = version[1];
|
|
75
|
+
head.writeUInt16BE(op, 2);
|
|
76
|
+
head.writeUInt32BE(requestId, 4);
|
|
77
|
+
const parts = [head, Buffer.from([T.OPERATION]), attribute(T.CHARSET, "attributes-charset", "utf-8"), attribute(T.LANGUAGE, "attributes-natural-language", "en")];
|
|
78
|
+
if (uri) parts.push(attribute(T.URI, "printer-uri", uri));
|
|
79
|
+
for (const [tag, name, value] of extra) parts.push(attribute(T[tag], name, value));
|
|
80
|
+
if (requested.length) parts.push(attribute(T.KEYWORD, "requested-attributes", requested));
|
|
81
|
+
parts.push(Buffer.from([T.END]));
|
|
82
|
+
return Buffer.concat(parts);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ---------- decoding ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
function dateTime(raw) {
|
|
88
|
+
if (raw.length !== 11) return null;
|
|
89
|
+
const sign = String.fromCharCode(raw[8]) === "-" ? -1 : 1;
|
|
90
|
+
const offsetMin = sign * (raw[9] * 60 + raw[10]);
|
|
91
|
+
const ms = Date.UTC(raw.readUInt16BE(0), raw[2] - 1, raw[3], raw[4], raw[5], raw[6]) - offsetMin * 60000;
|
|
92
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function withLanguage(raw) {
|
|
96
|
+
// language length, language, text length, text
|
|
97
|
+
if (raw.length < 4) return null;
|
|
98
|
+
const langLen = raw.readUInt16BE(0);
|
|
99
|
+
if (2 + langLen + 2 > raw.length) return null;
|
|
100
|
+
const textLen = raw.readUInt16BE(2 + langLen);
|
|
101
|
+
const start = 2 + langLen + 2;
|
|
102
|
+
if (start + textLen > raw.length) return null;
|
|
103
|
+
return raw.toString("utf8", start, start + textLen);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function value(tag, raw) {
|
|
107
|
+
if (tag === T.INTEGER || tag === T.ENUM) return raw.length === 4 ? raw.readInt32BE(0) : null;
|
|
108
|
+
if (tag === T.BOOLEAN) return raw.length === 1 ? raw[0] !== 0 : null;
|
|
109
|
+
if (tag === T.DATE_TIME) return dateTime(raw);
|
|
110
|
+
if (tag === T.RANGE) return raw.length === 8 ? { lower: raw.readInt32BE(0), upper: raw.readInt32BE(4) } : null;
|
|
111
|
+
if (tag === T.RESOLUTION) return raw.length === 9 ? { x: raw.readInt32BE(0), y: raw.readInt32BE(4), unit: raw[8] === 3 ? "dpi" : "dpcm" } : null;
|
|
112
|
+
if (tag === T.TEXT_LANG || tag === T.NAME_LANG) return withLanguage(raw);
|
|
113
|
+
if (tag === T.OCTET_STRING) return raw.toString("latin1");
|
|
114
|
+
if (tag >= 0x40 && tag <= 0x4f) return raw.toString("utf8"); // text, name, keyword, uri, charset, language, mime type
|
|
115
|
+
return null; // "unsupported", "unknown", "no-value", and anything newer than this reader
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Reads a reply into { version, status, requestId, complete, groups: [{ tag, attrs }] }, where
|
|
120
|
+
* attrs maps each attribute name to the list of its values. Collections (nested attributes) are
|
|
121
|
+
* stepped over. Every length is checked against the data that is really there, so a damaged or
|
|
122
|
+
* hostile reply ends in an IppError, never in a crash or an endless loop.
|
|
123
|
+
*/
|
|
124
|
+
export function decodeResponse(buf, { maxAttributes = 20000 } = {}) {
|
|
125
|
+
if (!Buffer.isBuffer(buf) || buf.length < 9) throw new IppError("reply too short");
|
|
126
|
+
const out = { version: `${buf[0]}.${buf[1]}`, status: buf.readUInt16BE(2), requestId: buf.readUInt32BE(4), complete: false, groups: [] };
|
|
127
|
+
let pos = 8;
|
|
128
|
+
let group = null;
|
|
129
|
+
let current = null;
|
|
130
|
+
let depth = 0;
|
|
131
|
+
let count = 0;
|
|
132
|
+
while (pos < buf.length) {
|
|
133
|
+
const tag = buf[pos];
|
|
134
|
+
if (tag <= 0x0f) {
|
|
135
|
+
// A delimiter: the start of a new group of attributes, or the end of them.
|
|
136
|
+
pos += 1;
|
|
137
|
+
if (tag === T.END) {
|
|
138
|
+
out.complete = true;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
group = { tag, attrs: Object.create(null) };
|
|
142
|
+
out.groups.push(group);
|
|
143
|
+
current = null;
|
|
144
|
+
depth = 0;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (pos + 3 > buf.length) throw new IppError("reply cut off inside an attribute");
|
|
148
|
+
const nameLen = buf.readUInt16BE(pos + 1);
|
|
149
|
+
const nameEnd = pos + 3 + nameLen;
|
|
150
|
+
if (nameEnd + 2 > buf.length) throw new IppError("attribute name runs past the end of the reply");
|
|
151
|
+
const valueLen = buf.readUInt16BE(nameEnd);
|
|
152
|
+
const valueEnd = nameEnd + 2 + valueLen;
|
|
153
|
+
if (valueEnd > buf.length) throw new IppError("attribute value runs past the end of the reply");
|
|
154
|
+
if (++count > maxAttributes) throw new IppError("too many attributes");
|
|
155
|
+
if (!group) throw new IppError("attribute outside a group");
|
|
156
|
+
const name = nameLen ? buf.toString("utf8", pos + 3, nameEnd) : null;
|
|
157
|
+
const raw = buf.subarray(nameEnd + 2, valueEnd);
|
|
158
|
+
pos = valueEnd; // always moves forward by at least 5 bytes
|
|
159
|
+
if (tag === T.BEG_COLLECTION) {
|
|
160
|
+
if (depth === 0 && name) current = null; // a new attribute whose values are not kept
|
|
161
|
+
depth += 1;
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
if (tag === T.END_COLLECTION) {
|
|
165
|
+
if (depth > 0) depth -= 1;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (depth > 0) continue; // inside a collection
|
|
169
|
+
if (name) {
|
|
170
|
+
current = [];
|
|
171
|
+
group.attrs[name] = current;
|
|
172
|
+
} else if (!current) {
|
|
173
|
+
continue; // an extra value with no attribute before it
|
|
174
|
+
}
|
|
175
|
+
current.push(value(tag, raw));
|
|
176
|
+
}
|
|
177
|
+
return out;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Was the request carried out? (status codes below 0x0100 are the "successful" class) */
|
|
181
|
+
export const isOk = (res) => Boolean(res) && res.status < 0x0100;
|
|
182
|
+
|
|
183
|
+
/** First value of an attribute, or null. */
|
|
184
|
+
export const one = (attrs, name) => {
|
|
185
|
+
const v = attrs?.[name];
|
|
186
|
+
return v && v.length && v[0] !== undefined ? v[0] : null;
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
/** All values of an attribute as a list (empty when it is missing). */
|
|
190
|
+
export const many = (attrs, name) => (attrs?.[name] || []).filter((x) => x !== null && x !== undefined);
|
|
191
|
+
|
|
192
|
+
/** The attribute groups of one kind: 0x04 printers, 0x02 jobs. */
|
|
193
|
+
export const groupsOf = (res, tag) => (res?.groups || []).filter((g) => g.tag === tag).map((g) => g.attrs);
|
|
194
|
+
|
|
195
|
+
// ---------- sending ----------------------------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
/** The HTTP Host header for an address: an IPv6 address goes in square brackets. */
|
|
198
|
+
export const hostHeader = (host, port) => {
|
|
199
|
+
const h = String(host || "").includes(":") ? `[${host}]` : String(host || "");
|
|
200
|
+
return port ? `${h}:${port}` : h;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Sends one request and reads the reply. Never throws: resolves with
|
|
205
|
+
* { ok, response, error, httpStatus }.
|
|
206
|
+
*
|
|
207
|
+
* target: { host, port, path, secure, hostHeader, socketPath }
|
|
208
|
+
* secure use TLS (an ipps:// printer). The certificate is NOT checked: home printers
|
|
209
|
+
* sign their own certificates, so a check would fail on every one of them. Nothing
|
|
210
|
+
* secret is sent, only the question "what is your state?".
|
|
211
|
+
* socketPath talk to the local print system through its local socket instead of the network
|
|
212
|
+
*/
|
|
213
|
+
export function ippSend(target, body, { timeoutMs = 4000, maxBytes = 2 * 1024 * 1024 } = {}) {
|
|
214
|
+
return new Promise((resolve) => {
|
|
215
|
+
let settled = false;
|
|
216
|
+
const finish = (r) => {
|
|
217
|
+
if (settled) return;
|
|
218
|
+
settled = true;
|
|
219
|
+
resolve(r);
|
|
220
|
+
};
|
|
221
|
+
const options = {
|
|
222
|
+
method: "POST",
|
|
223
|
+
path: target.path || "/",
|
|
224
|
+
agent: false,
|
|
225
|
+
timeout: timeoutMs,
|
|
226
|
+
headers: {
|
|
227
|
+
"content-type": "application/ipp",
|
|
228
|
+
"content-length": body.length,
|
|
229
|
+
host: target.hostHeader || hostHeader(target.host, target.port),
|
|
230
|
+
"user-agent": "printer-doctor",
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
if (target.socketPath) options.socketPath = target.socketPath;
|
|
234
|
+
else {
|
|
235
|
+
options.host = target.host;
|
|
236
|
+
options.port = target.port || 631;
|
|
237
|
+
}
|
|
238
|
+
if (target.secure) options.rejectUnauthorized = false;
|
|
239
|
+
let req;
|
|
240
|
+
try {
|
|
241
|
+
req = (target.secure ? https : http).request(options, (res) => {
|
|
242
|
+
if (res.statusCode !== 200) {
|
|
243
|
+
res.resume();
|
|
244
|
+
return finish({ ok: false, error: res.statusCode === 426 ? "needs-tls" : res.statusCode === 401 || res.statusCode === 403 ? "needs-password" : "http", httpStatus: res.statusCode });
|
|
245
|
+
}
|
|
246
|
+
const chunks = [];
|
|
247
|
+
let size = 0;
|
|
248
|
+
res.on("data", (d) => {
|
|
249
|
+
size += d.length;
|
|
250
|
+
if (size > maxBytes) {
|
|
251
|
+
req.destroy();
|
|
252
|
+
return finish({ ok: false, error: "too-big" });
|
|
253
|
+
}
|
|
254
|
+
chunks.push(d);
|
|
255
|
+
});
|
|
256
|
+
res.on("end", () => {
|
|
257
|
+
try {
|
|
258
|
+
const response = decodeResponse(Buffer.concat(chunks));
|
|
259
|
+
finish({ ok: isOk(response), response, error: isOk(response) ? null : "ipp-status" });
|
|
260
|
+
} catch (e) {
|
|
261
|
+
finish({ ok: false, error: "unreadable", detail: e.message });
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
res.on("error", () => finish({ ok: false, error: "broken" }));
|
|
265
|
+
});
|
|
266
|
+
} catch (e) {
|
|
267
|
+
return finish({ ok: false, error: e.code || "error" });
|
|
268
|
+
}
|
|
269
|
+
// One overall limit as well: a device that answers one byte at a time must not hold things up.
|
|
270
|
+
const hard = setTimeout(() => {
|
|
271
|
+
req.destroy();
|
|
272
|
+
finish({ ok: false, error: "timeout" });
|
|
273
|
+
}, timeoutMs + 1500);
|
|
274
|
+
hard.unref?.();
|
|
275
|
+
req.on("timeout", () => {
|
|
276
|
+
req.destroy();
|
|
277
|
+
finish({ ok: false, error: "timeout" });
|
|
278
|
+
});
|
|
279
|
+
req.on("error", (e) => finish({ ok: false, error: e.code || "error" }));
|
|
280
|
+
req.on("close", () => clearTimeout(hard));
|
|
281
|
+
req.end(body);
|
|
282
|
+
});
|
|
283
|
+
}
|