Debian Codegraph @

probe_printer.py

raw
1 ## system-config-printer
2
3 ## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014 Red Hat, Inc.
4 ## Copyright (C) 2006 Florian Festi <[email protected]>
5 ## Copyright (C) 2007, 2008, 2009, 2014 Tim Waugh <[email protected]>
6
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
11
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
16
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, write to the Free Software
19 ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
21 import cupshelpers
22 from debug import *
23 import errno
24 import socket, time
25 from gi.repository import Gdk
26 from gi.repository import Gtk
27 from timedops import TimedOperation
28 import subprocess
29 import threading
30 import cups
31 from gi.repository import GObject
32 from gi.repository import GLib
33 import smburi
34
35 try:
36 import pysmb
37 PYSMB_AVAILABLE=True
38 except:
39 PYSMB_AVAILABLE=False
40 class pysmb:
41 class AuthContext:
42 pass
43
44 def wordsep (line):
45 words = []
46 escaped = False
47 quoted = False
48 in_word = False
49 word = ''
50 n = len (line)
51 for i in range (n):
52 ch = line[i]
53 if escaped:
54 word += ch
55 escaped = False
56 continue
57
58 if ch == '\\':
59 in_word = True
60 escaped = True
61 continue
62
63 if in_word:
64 if quoted:
65 if ch == '"':
66 quoted = False
67 else:
68 word += ch
69 elif ch.isspace ():
70 words.append (word)
71 word = ''
72 in_word = False
73 elif ch == '"':
74 quoted = True
75 else:
76 word += ch
77 else:
78 if ch == '"':
79 in_word = True
80 quoted = True
81 elif not ch.isspace ():
82 in_word = True
83 word += ch
84
85 if word != '':
86 words.append (word)
87
88 return words
89
90 ### should be ['network', 'foo bar', ' ofoo', '"', '2 3']
91 ##print wordsep ('network "foo bar" \ ofoo "\\"" 2" "3')
92
93 def open_socket(hostname, port):
94 try:
95 host, port = hostname.split(":", 1)
96 except ValueError:
97 host = hostname
98
99 s = None
100 try:
101 ai = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
102 socket.SOCK_STREAM)
103 except (socket.gaierror, socket.error):
104 ai = []
105
106 for res in ai:
107 af, socktype, proto, canonname, sa = res
108 try:
109 s = socket.socket(af, socktype, proto)
110 s.settimeout(0.5)
111 except socket.error:
112 s = None
113 continue
114 try:
115 s.connect(sa)
116 except socket.error:
117 s.close()
118 s = None
119 continue
120 break
121 return s
122
123 class LpdServer:
124 def __init__(self, hostname):
125 self.hostname = hostname
126 self.max_lpt_com = 8
127 self.stop = False
128
129 def probe_queue(self,name, result):
130 s = open_socket(self.hostname, 515)
131 if not s:
132 return None
133 debugprint(name)
134
135 try:
136 s.send(('\2%s\n' % name).encode('UTF-8')) # cmd send job to queue
137 data = s.recv(1024).decode('UTF-8') # receive status
138 debugprint(repr(data))
139 except socket.error as msg:
140 debugprint(msg)
141 try:
142 s.close ()
143 except:
144 pass
145
146 return False
147
148 if len(data)>0 and ord(data[0])==0:
149 try:
150 s.send(b'\1\n') # abort job again
151 s.close ()
152 except:
153 pass
154
155 result.append(name)
156 return True
157
158 try:
159 s.close()
160 except:
161 pass
162
163 return False
164
165 def get_possible_queue_names (self):
166 candidate = ["PASSTHRU", "ps", "lp", "PORT1", ""]
167 for nr in range (self.max_lpt_com):
168 candidate.extend (["LPT%d" % nr,
169 "LPT%d_PASSTHRU" % nr,
170 "COM%d" % nr,
171 "COM%d_PASSTHRU" % nr])
172 for nr in range (50):
173 candidate.append ("pr%d" % nr)
174
175 return candidate
176
177 def destroy(self):
178 debugprint ("LpdServer exiting: destroy called")
179 self.stop = True
180
181 def probe(self):
182 result = []
183 for name in self.get_possible_queue_names ():
184 while Gtk.events_pending ():
185 Gtk.main_iteration ()
186
187 if self.stop:
188 break
189
190 found = self.probe_queue(name, result)
191 if found is None:
192 # Couldn't even connect.
193 break
194
195 if not found and name.startswith ("pr"):
196 break
197 time.sleep(0.1) # avoid DOS and following counter measures
198
199 return result
200
201 class BackgroundSmbAuthContext(pysmb.AuthContext):
202 """An SMB AuthContext class that is only ever run from
203 a non-GUI thread."""
204
205 def __init__ (self, *args, **kwargs):
206 self._gui_event = threading.Event ()
207 pysmb.AuthContext.__init__ (self, *args, **kwargs)
208
209 def _do_perform_authentication (self):
210 Gdk.threads_enter ()
211 result = pysmb.AuthContext.perform_authentication (self)
212 Gdk.threads_leave ()
213 self._do_perform_authentication_result = result
214 self._gui_event.set ()
215
216 def perform_authentication (self):
217 if (self.passes == 0 or
218 not self.has_failed or
219 not self.auth_called or
220 (self.auth_called and not self.tried_guest)):
221 # Safe to call the base function. It won't try any UI stuff.
222 return pysmb.AuthContext.perform_authentication (self)
223
224 self._gui_event.clear ()
225 GLib.timeout_add (1, self._do_perform_authentication)
226 self._gui_event.wait ()
227 return self._do_perform_authentication_result
228
229 class PrinterFinder:
230 def __init__ (self):
231 self.quit = False
232
233 def find (self, hostname, callback_fn):
234 self.hostname = hostname
235 self.callback_fn = callback_fn
236 self.op = TimedOperation (self._do_find, callback=lambda x, y: None)
237
238 def cancel (self):
239 self.op.cancel ()
240 self.quit = True
241
242 def _do_find (self):
243 self._cached_attributes = dict()
244 for fn in [self._probe_hplip,
245 self._probe_jetdirect,
246 self._probe_ipp,
247 self._probe_snmp,
248 self._probe_lpd,
249 self._probe_smb]:
250 if self.quit:
251 return
252
253 try:
254 fn ()
255 except Exception:
256 nonfatalException ()
257
258 # Signal that we've finished.
259 if not self.quit:
260 self.callback_fn (None)
261
262 def _new_device (self, uri, info, location = None):
263 device_dict = { 'device-class': 'network',
264 'device-info': "%s" % info }
265 if location:
266 device_dict['device-location']=location
267 device_dict.update (self._cached_attributes)
268 new_device = cupshelpers.Device (uri, **device_dict)
269 debugprint ("Device found: %s" % uri)
270 self.callback_fn (new_device)
271
272 def _probe_snmp (self):
273 # Run the CUPS SNMP backend, pointing it at the host.
274 try:
275 debugprint ("snmp: trying")
276 p = subprocess.Popen (args=["/usr/lib/cups/backend/snmp",
277 self.hostname],
278 close_fds=True,
279 stdin=subprocess.DEVNULL,
280 stdout=subprocess.PIPE,
281 stderr=subprocess.DEVNULL)
282 except OSError as e:
283 debugprint ("snmp: no good")
284 if e.errno == errno.ENOENT:
285 return
286
287 raise
288
289 (stdout, stderr) = p.communicate ()
290 if p.returncode != 0:
291 debugprint ("snmp: no good (return code %d)" % p.returncode)
292 return
293
294 if self.quit:
295 debugprint ("snmp: no good")
296 return
297
298 for line in stdout.decode ().split ('\n'):
299 words = wordsep (line)
300 n = len (words)
301 if n == 6:
302 (device_class, uri, make_and_model,
303 info, device_id, device_location) = words
304 elif n == 5:
305 (device_class, uri, make_and_model, info, device_id) = words
306 elif n == 4:
307 (device_class, uri, make_and_model, info) = words
308 else:
309 continue
310
311 device_dict = { 'device-class': device_class,
312 'device-make-and-model': make_and_model,
313 'device-info': info }
314 if n == 5:
315 debugprint ("snmp: Device ID found:\n%s" %
316 device_id)
317 device_dict['device-id'] = device_id
318 if n == 6:
319 device_dict['device-location'] = device_location
320
321 device = cupshelpers.Device (uri, **device_dict)
322 debugprint ("Device found: %s" % uri)
323 self.callback_fn (device)
324
325 # Cache the make and model for use by other search methods
326 # that are not able to determine it.
327 self._cached_attributes['device-make-and-model'] = make_and_model
328 self._cached_attributes['device_id'] = device_id
329
330 debugprint ("snmp: done")
331
332 def _probe_lpd (self):
333 debugprint ("lpd: trying")
334 lpd = LpdServer (self.hostname)
335 for name in lpd.get_possible_queue_names ():
336 if self.quit:
337 debugprint ("lpd: no good")
338 return
339
340 found = lpd.probe_queue (name, [])
341 if found is None:
342 # Couldn't even connect.
343 debugprint ("lpd: couldn't connect")
344 break
345
346 if found:
347 uri = "lpd://%s/%s" % (self.hostname, name)
348 self._new_device(uri, self.hostname)
349
350 if not found and name.startswith ("pr"):
351 break
352
353 time.sleep(0.1) # avoid DOS and following counter measures
354
355 debugprint ("lpd: done")
356
357 def _probe_hplip (self):
358 if ('device-make-and-model' in self._cached_attributes and \
359 self._cached_attributes['device-make-and-model'] != "Unknown" and \
360 not self._cached_attributes['device-make-and-model'].lower ().startswith ("hp") and \
361 not self._cached_attributes['device-make-and-model'].lower ().startswith ("hewlett")):
362 debugprint ("hplip: no good (Non-HP printer: %s)" %
363 self._cached_attributes['device-make-and-model'])
364 return
365
366 try:
367 debugprint ("hplip: trying")
368 p = subprocess.Popen (args=["hp-makeuri", "-c", self.hostname],
369 close_fds=True,
370 stdin=subprocess.DEVNULL,
371 stdout=subprocess.PIPE,
372 stderr=subprocess.DEVNULL)
373 except OSError as e:
374 if e.errno == errno.ENOENT:
375 return
376
377 raise
378
379 (stdout, stderr) = p.communicate ()
380 if p.returncode != 0:
381 debugprint ("hplip: no good (return code %d)" % p.returncode)
382 return
383
384 if self.quit:
385 debugprint ("hplip: no good")
386 return
387
388 uri = stdout.decode ().strip ()
389 debugprint ("hplip: uri is %s" % uri)
390 if uri.find (":") != -1:
391 self._new_device(uri, uri)
392
393 debugprint ("hplip: done")
394
395 def _probe_smb (self):
396 if not PYSMB_AVAILABLE:
397 return
398
399 smbc_auth = BackgroundSmbAuthContext ()
400 debug = 0
401 if get_debugging ():
402 debug = 10
403 ctx = pysmb.smbc.Context (debug=debug,
404 auth_fn=smbc_auth.callback)
405 entries = []
406 uri = "smb://%s/" % self.hostname
407 debugprint ("smb: trying")
408 try:
409 while smbc_auth.perform_authentication () > 0:
410 if self.quit:
411 debugprint ("smb: no good")
412 return
413
414 try:
415 entries = ctx.opendir (uri).getdents ()
416 except Exception as e:
417 smbc_auth.failed (e)
418 except RuntimeError as e:
419 (e, s) = e.args
420 if e not in [errno.ENOENT, errno.EACCES, errno.EPERM]:
421 debugprint ("Runtime error: %s" % repr ((e, s)))
422 except:
423 nonfatalException ()
424
425 if self.quit:
426 debugprint ("smb: no good")
427 return
428
429 for entry in entries:
430 if entry.smbc_type == pysmb.smbc.PRINTER_SHARE:
431 uri = "smb://%s/%s" % (smburi.urlquote (self.hostname),
432 smburi.urlquote (entry.name))
433 info = "SMB (%s)" % self.hostname
434 self._new_device(uri, info)
435
436 debugprint ("smb: done")
437
438 def _probe_jetdirect (self):
439 port = 9100 #jetdirect
440 sock_address = (self.hostname, port)
441 debugprint ("jetdirect: trying")
442 s = open_socket(self.hostname, port)
443 if not s:
444 debugprint ("jetdirect: %s:%d CLOSED" % sock_address)
445 else:
446 # port is open so assume its a JetDirect device
447 debugprint ("jetdirect %s:%d OPEN" % sock_address)
448 uri = "socket://%s:%d" % sock_address
449 info = "JetDirect (%s)" % self.hostname
450 self._new_device(uri, info)
451 s.close ()
452
453 debugprint ("jetdirect: done")
454
455 def _probe_ipp (self):
456 debugprint ("ipp: trying")
457 try:
458 ai = socket.getaddrinfo(self.hostname, 631, socket.AF_UNSPEC,
459 socket.SOCK_STREAM)
460 except socket.gaierror:
461 debugprint ("ipp: can't resolve %s" % self.hostname)
462 debugprint ("ipp: no good")
463 return
464 for res in ai:
465 af, socktype, proto, canonname, sa = res
466 if (af == socket.AF_INET and sa[0] == '127.0.0.1' or
467 af == socket.AF_INET6 and sa[0] == '::1'):
468 debugprint ("ipp: do not probe local cups server")
469 debugprint ("ipp: no good")
470 return
471
472 try:
473 c = cups.Connection (host = self.hostname)
474 except RuntimeError:
475 debugprint ("ipp: can't connect to server/printer")
476 debugprint ("ipp: no good")
477 return
478
479 try:
480 printers = c.getPrinters ()
481 except cups.IPPError:
482 debugprint ("%s is probably not a cups server but IPP printer" %
483 self.hostname)
484 uri = "ipp://%s:631/ipp" % (self.hostname)
485 info = "IPP (%s)" % self.hostname
486 self._new_device(uri, info)
487 debugprint ("ipp: done")
488 return
489
490 for name, queue in printers.items ():
491 uri = queue['printer-uri-supported']
492 info = queue['printer-info']
493 location = queue['printer-location']
494 self._new_device(uri, info, location)
495
496 debugprint ("ipp: done")
497
498 if __name__ == '__main__':
499 import sys
500 if len (sys.argv) < 2:
501 print("Need printer address")
502 sys.exit (1)
503
504 set_debugging (True)
505 loop = GObject.MainLoop ()
506
507 def display (device):
508 if device is None:
509 loop.quit ()
510
511 addr = sys.argv[1]
512 p = PrinterFinder ()
513 p.find (addr, display)
514 loop.run ()