forked from OpenPrinting/system-config-printer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
probe_printer.py
514 lines (432 loc) · 15.8 KB
/
probe_printer.py
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
## system-config-printer
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014 Red Hat, Inc.
## Copyright (C) 2006 Florian Festi <ffesti@redhat.com>
## Copyright (C) 2007, 2008, 2009, 2014 Tim Waugh <twaugh@redhat.com>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import cupshelpers
from debug import *
import errno
import socket, time
from gi.repository import Gdk
from gi.repository import Gtk
from timedops import TimedOperation
import subprocess
import threading
import cups
from gi.repository import GObject
from gi.repository import GLib
import smburi
try:
import pysmb
PYSMB_AVAILABLE=True
except:
PYSMB_AVAILABLE=False
class pysmb:
class AuthContext:
pass
def wordsep (line):
words = []
escaped = False
quoted = False
in_word = False
word = ''
n = len (line)
for i in range (n):
ch = line[i]
if escaped:
word += ch
escaped = False
continue
if ch == '\\':
in_word = True
escaped = True
continue
if in_word:
if quoted:
if ch == '"':
quoted = False
else:
word += ch
elif ch.isspace ():
words.append (word)
word = ''
in_word = False
elif ch == '"':
quoted = True
else:
word += ch
else:
if ch == '"':
in_word = True
quoted = True
elif not ch.isspace ():
in_word = True
word += ch
if word != '':
words.append (word)
return words
### should be ['network', 'foo bar', ' ofoo', '"', '2 3']
##print wordsep ('network "foo bar" \ ofoo "\\"" 2" "3')
def open_socket(hostname, port):
try:
host, port = hostname.split(":", 1)
except ValueError:
host = hostname
s = None
try:
ai = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM)
except (socket.gaierror, socket.error):
ai = []
for res in ai:
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
s.settimeout(0.5)
except socket.error:
s = None
continue
try:
s.connect(sa)
except socket.error:
s.close()
s = None
continue
break
return s
class LpdServer:
def __init__(self, hostname):
self.hostname = hostname
self.max_lpt_com = 8
self.stop = False
def probe_queue(self,name, result):
s = open_socket(self.hostname, 515)
if not s:
return None
print(name)
try:
s.send(('\2%s\n' % name).encode('UTF-8')) # cmd send job to queue
data = s.recv(1024).decode('UTF-8') # receive status
print(repr(data))
except socket.error as msg:
print(msg)
try:
s.close ()
except:
pass
return False
if len(data)>0 and ord(data[0])==0:
try:
s.send(b'\1\n') # abort job again
s.close ()
except:
pass
result.append(name)
return True
try:
s.close()
except:
pass
return False
def get_possible_queue_names (self):
candidate = ["PASSTHRU", "ps", "lp", "PORT1", ""]
for nr in range (self.max_lpt_com):
candidate.extend (["LPT%d" % nr,
"LPT%d_PASSTHRU" % nr,
"COM%d" % nr,
"COM%d_PASSTHRU" % nr])
for nr in range (50):
candidate.append ("pr%d" % nr)
return candidate
def destroy(self):
debugprint ("LpdServer exiting: destroy called")
self.stop = True
def probe(self):
result = []
for name in self.get_possible_queue_names ():
while Gtk.events_pending ():
Gtk.main_iteration ()
if self.stop:
break
found = self.probe_queue(name, result)
if found is None:
# Couldn't even connect.
break
if not found and name.startswith ("pr"):
break
time.sleep(0.1) # avoid DOS and following counter measures
return result
class BackgroundSmbAuthContext(pysmb.AuthContext):
"""An SMB AuthContext class that is only ever run from
a non-GUI thread."""
def __init__ (self, *args, **kwargs):
self._gui_event = threading.Event ()
pysmb.AuthContext.__init__ (self, *args, **kwargs)
def _do_perform_authentication (self):
Gdk.threads_enter ()
result = pysmb.AuthContext.perform_authentication (self)
Gdk.threads_leave ()
self._do_perform_authentication_result = result
self._gui_event.set ()
def perform_authentication (self):
if (self.passes == 0 or
not self.has_failed or
not self.auth_called or
(self.auth_called and not self.tried_guest)):
# Safe to call the base function. It won't try any UI stuff.
return pysmb.AuthContext.perform_authentication (self)
self._gui_event.clear ()
GLib.timeout_add (1, self._do_perform_authentication)
self._gui_event.wait ()
return self._do_perform_authentication_result
class PrinterFinder:
def __init__ (self):
self.quit = False
def find (self, hostname, callback_fn):
self.hostname = hostname
self.callback_fn = callback_fn
self.op = TimedOperation (self._do_find, callback=lambda x, y: None)
def cancel (self):
self.op.cancel ()
self.quit = True
def _do_find (self):
self._cached_attributes = dict()
for fn in [self._probe_hplip,
self._probe_jetdirect,
self._probe_ipp,
self._probe_snmp,
self._probe_lpd,
self._probe_smb]:
if self.quit:
return
try:
fn ()
except Exception:
nonfatalException ()
# Signal that we've finished.
if not self.quit:
self.callback_fn (None)
def _new_device (self, uri, info, location = None):
device_dict = { 'device-class': 'network',
'device-info': "%s" % info }
if location:
device_dict['device-location']=location
device_dict.update (self._cached_attributes)
new_device = cupshelpers.Device (uri, **device_dict)
debugprint ("Device found: %s" % uri)
self.callback_fn (new_device)
def _probe_snmp (self):
# Run the CUPS SNMP backend, pointing it at the host.
try:
debugprint ("snmp: trying")
p = subprocess.Popen (args=["/usr/lib/cups/backend/snmp",
self.hostname],
close_fds=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
except OSError as e:
debugprint ("snmp: no good")
if e.errno == errno.ENOENT:
return
raise
(stdout, stderr) = p.communicate ()
if p.returncode != 0:
debugprint ("snmp: no good (return code %d)" % p.returncode)
return
if self.quit:
debugprint ("snmp: no good")
return
for line in stdout.decode ().split ('\n'):
words = wordsep (line)
n = len (words)
if n == 6:
(device_class, uri, make_and_model,
info, device_id, device_location) = words
elif n == 5:
(device_class, uri, make_and_model, info, device_id) = words
elif n == 4:
(device_class, uri, make_and_model, info) = words
else:
continue
device_dict = { 'device-class': device_class,
'device-make-and-model': make_and_model,
'device-info': info }
if n == 5:
debugprint ("snmp: Device ID found:\n%s" %
device_id)
device_dict['device-id'] = device_id
if n == 6:
device_dict['device-location'] = device_location
device = cupshelpers.Device (uri, **device_dict)
debugprint ("Device found: %s" % uri)
self.callback_fn (device)
# Cache the make and model for use by other search methods
# that are not able to determine it.
self._cached_attributes['device-make-and-model'] = make_and_model
self._cached_attributes['device_id'] = device_id
debugprint ("snmp: done")
def _probe_lpd (self):
debugprint ("lpd: trying")
lpd = LpdServer (self.hostname)
for name in lpd.get_possible_queue_names ():
if self.quit:
debugprint ("lpd: no good")
return
found = lpd.probe_queue (name, [])
if found is None:
# Couldn't even connect.
debugprint ("lpd: couldn't connect")
break
if found:
uri = "lpd://%s/%s" % (self.hostname, name)
self._new_device(uri, self.hostname)
if not found and name.startswith ("pr"):
break
time.sleep(0.1) # avoid DOS and following counter measures
debugprint ("lpd: done")
def _probe_hplip (self):
if ('device-make-and-model' in self._cached_attributes and \
self._cached_attributes['device-make-and-model'] != "Unknown" and \
not self._cached_attributes['device-make-and-model'].lower ().startswith ("hp") and \
not self._cached_attributes['device-make-and-model'].lower ().startswith ("hewlett")):
debugprint ("hplip: no good (Non-HP printer: %s)" %
self._cached_attributes['device-make-and-model'])
return
try:
debugprint ("hplip: trying")
p = subprocess.Popen (args=["hp-makeuri", "-c", self.hostname],
close_fds=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
except OSError as e:
if e.errno == errno.ENOENT:
return
raise
(stdout, stderr) = p.communicate ()
if p.returncode != 0:
debugprint ("hplip: no good (return code %d)" % p.returncode)
return
if self.quit:
debugprint ("hplip: no good")
return
uri = stdout.decode ().strip ()
debugprint ("hplip: uri is %s" % uri)
if uri.find (":") != -1:
self._new_device(uri, uri)
debugprint ("hplip: done")
def _probe_smb (self):
if not PYSMB_AVAILABLE:
return
smbc_auth = BackgroundSmbAuthContext ()
debug = 0
if get_debugging ():
debug = 10
ctx = pysmb.smbc.Context (debug=debug,
auth_fn=smbc_auth.callback)
entries = []
uri = "smb://%s/" % self.hostname
debugprint ("smb: trying")
try:
while smbc_auth.perform_authentication () > 0:
if self.quit:
debugprint ("smb: no good")
return
try:
entries = ctx.opendir (uri).getdents ()
except Exception as e:
smbc_auth.failed (e)
except RuntimeError as e:
(e, s) = e.args
if e not in [errno.ENOENT, errno.EACCES, errno.EPERM]:
debugprint ("Runtime error: %s" % repr ((e, s)))
except:
nonfatalException ()
if self.quit:
debugprint ("smb: no good")
return
for entry in entries:
if entry.smbc_type == pysmb.smbc.PRINTER_SHARE:
uri = "smb://%s/%s" % (smburi.urlquote (self.hostname),
smburi.urlquote (entry.name))
info = "SMB (%s)" % self.hostname
self._new_device(uri, info)
debugprint ("smb: done")
def _probe_jetdirect (self):
port = 9100 #jetdirect
sock_address = (self.hostname, port)
debugprint ("jetdirect: trying")
s = open_socket(self.hostname, port)
if not s:
debugprint ("jetdirect: %s:%d CLOSED" % sock_address)
else:
# port is open so assume its a JetDirect device
debugprint ("jetdirect %s:%d OPEN" % sock_address)
uri = "socket://%s:%d" % sock_address
info = "JetDirect (%s)" % self.hostname
self._new_device(uri, info)
s.close ()
debugprint ("jetdirect: done")
def _probe_ipp (self):
debugprint ("ipp: trying")
try:
ai = socket.getaddrinfo(self.hostname, 631, socket.AF_UNSPEC,
socket.SOCK_STREAM)
except socket.gaierror:
debugprint ("ipp: can't resolve %s" % self.hostname)
debugprint ("ipp: no good")
return
for res in ai:
af, socktype, proto, canonname, sa = res
if (af == socket.AF_INET and sa[0] == '127.0.0.1' or
af == socket.AF_INET6 and sa[0] == '::1'):
debugprint ("ipp: do not probe local cups server")
debugprint ("ipp: no good")
return
try:
c = cups.Connection (host = self.hostname)
except RuntimeError:
debugprint ("ipp: can't connect to server/printer")
debugprint ("ipp: no good")
return
try:
printers = c.getPrinters ()
except cups.IPPError:
debugprint ("%s is probably not a cups server but IPP printer" %
self.hostname)
uri = "ipp://%s:631/ipp" % (self.hostname)
info = "IPP (%s)" % self.hostname
self._new_device(uri, info)
debugprint ("ipp: done")
return
for name, queue in printers.items ():
uri = queue['printer-uri-supported']
info = queue['printer-info']
location = queue['printer-location']
self._new_device(uri, info, location)
debugprint ("ipp: done")
if __name__ == '__main__':
import sys
if len (sys.argv) < 2:
print("Need printer address")
sys.exit (1)
set_debugging (True)
loop = GObject.MainLoop ()
def display (device):
if device is None:
loop.quit ()
addr = sys.argv[1]
p = PrinterFinder ()
p.find (addr, display)
loop.run ()